How to check if module function exist in Node js - javascript

I have created a module and defined functions in it. Sometimes I need to check if a certain function is actually already created.
For example
var newyork = function() {
console.log("newyork");
};
var washington = function() {
console.log("washington");
};
exports.newyork = newyork;
exports.washington = washington;
Now in the different file, I want to first check if the function exists, something like:
var cities = require('./city');
if(cities.newyork) {
console.log("city function exist");
}
else {
//false
}

As I said in the comments what you wrote actually works because
if(cities.newyork){
Checks if cities.newyork is truthy. The following things are truthy:
functions (thats why it works here)
numbers except 0
strings except an empty one
objects / arrays
If it is however not defined, cities.newyork will be undefined which is falsy (will enter the else branch)

typeof cities.cityName === 'function'
if city's name is assigned to some variable
typeof cities[cityName] === 'function'

Related

assigning a numeric value inside an object literal is not throwing any error

consider the following code:
let logged = 1;
let x = {logged} //{logged: 1}
x['logged']; // 1
x['logged']['index']; //undefined
x['logged']['index'] = 0;
x; // {logged: 1}
x['logged']['index']; //undefined
So, my questions are:
isn't
x[logged]['index'] doing something like 1['index']. Shouldn't
which give something like cannot index a numeric literal kind of
error?
x[logged]['index'] = 0;, this doesn't throw any error, as if the
element is stored somewhere, but, where is this value being stored?
As shown in line 6, the value of x is still {logged: 1}. And why does it not throw error?
and why is x[logged]['index'] is still undefined?
I tested this on a nodejs terminal, with node version 14.16.0
Not sure if my comments above actually fully illuminated the issue for you.
I have written a small program that may be helpfull to visualize what happens. Note I'm doing a method lookup on a primitive value rather than a regular property lookup - but this is all just the same and allows to illustrate what happens better.
function captureThis() {
return this
}
(function setUpObjectPrototype() {
if (Object.prototype.captureThis !== undefined) throw new Error("Couldn't set up Object prototype properly.")
Object.prototype.captureThis = captureThis
process.nextTick(() => delete Object.prototype.captureThis)
})()
var number = 1
var thisObject = number.captureThis()
console.log("Is thisObject an object? " + (typeof thisObject == "object"))
console.log("Is number still just a number? " + (typeof number == "number"))
console.log("Is thisObject an instance of Number? " + (thisObject instanceof Number))
// Output
// Is thisObject an object? true
// Is number still just a number? true
// Is thisObject an instance of Number? true
Note that at no point is the number variable actually coerced to an object - a temporary object is created that wraps the value contained in the number variable. This object is never actually assigned to a variable - unless it is captured like it is in this little program.
Hopefully that helps.

check for object is undefined works only on first array item

I'm trying to check if the object properties 'compliancestatus' and 'comments' are empty, undefined, undeclared i.e. no real value.
I am first checking that the item exists in the object array and my console.log shows that the values do exist and that both object properties are undefined.
The issue is that the second object triggers the else (obj array after2) somehow...
My object is created using:
// Create the object.
let contentObj = new Object();
contentObj.prefix = clausePrefix;
contentObj.no = clauseNo;
if (clauseComplianceStatus != null) {
contentObj.compliancestatus = clauseComplianceStatus;
}
if (clauseComments != null) {
contentObj.comments = clauseComments;
}
code
// Check if current iteration exists in the content array.
if (content.some(e => e.prefix === tempOBJ.content[y].prefix && e.no === tempOBJ.content[y].no)) {
// THIS WORKS FOR ALL OBJECTS
let currentIterationIndexOfClauseNo = content.findIndex(e => e.prefix === tempOBJ.content[y].prefix && e.no === tempOBJ.content[y].no);
if (!content[currentIterationIndexOfClauseNo].compliancestatus && !content[currentIterationIndexOfClauseNo].comments) {
// THIS WILL ONLY WORK FOR THE FIRST OBJECT
} else {
// SECOND OBJECT EXECUTES HERE FOR SOME REASONS DESPITE HAVING BOTH VALUES 'undefined' THE SAME AS THE FIRST OBJECT.
}
}
I can't comment, so I'll have to ask this way. Have you checked if your currentIterationIndexOfClauseNo actually changes? The code is still a little bit hard to understand, but I have one small suggestion to make (no solution but makes the code a bit simpler). Are the values of the first object also both undefined?
const obj = content.find(e => e.prefix === tempOBJ.content[y].prefix && e.no === tempOBJ.content[y].no); // will be undefined if nothing was found
if (obj !== undefined) {
if (!obj.compliancestatus && !obj.comments) {
// THIS WILL ONLY WORK FOR THE FIRST OBJECT
} else {
// SECOND OBJECT EXECUTES HERE FOR SOME REASONS DESPITE HAVING BOTH VALUES 'undefined' THE SAME AS THE FIRST OBJECT.
}
}

Node.js : check if a property is absent from object

I’m checking if a property 'lessons' (not inherited) is not present in obj,
All these give me true
(typeof obj['lessons'] == undefined)
(!(obj.hasOwnProperty('lessons')))
(!(hasOwnProperty.call(obj,'lessons')))
(!(_.has(obj, 'lessons')))
(!Object.prototype.hasOwnProperty.call(obj, 'lessons’))
but the property is present in the object, when i print keys by using (key in obj). I don't want to use it as it's very slow and my object is huge.
I found this on stackoverflow, but I don't understand what it's trying to do or how to use it with node.js.
I'd also like to know how are the mentioned ways of using hasOwnProperty are different.
EDIT
adding code
My code is:
console.log("LS:",JSON.stringify(obj)) ;
if (typeof obj['lessons'] == undefined)
console.log('typeof undefined');
else {console.log('typeof not undefined');}
if (!(obj.hasOwnProperty('lessons')))
console.log('hasOwnProperty: false');
else {console.log('hasOwnProperty not undefined');}
if (!(hasOwnProperty.call(obj,'lessons')))
console.log('hasOwnProperty.call');
else {console.log('hasOwnProperty.call not undefined');}
if (!(_.has(obj, 'lessons')))
console.log('_.hash');
else {console.log('_has not undefined');}
if (!(_.has(obj, 'lessons')))
{obj['lessons'] = {"levels": []};}
else
{console.log("has lesson level ");}
console.log("Lesson ", JSON.stringify(obj.lessons));
And the output I'm getting is:
LS: {"_id":"N9zmznzAWx","time":"1970-01-01T00:33:36.000Z","lessons":{"levels":["abc"]}}
typeof not undefined
hasOwnProperty: false
hasOwnProperty.call
_.hash
Lesson {"levels":[]}
Same case with all others..
SOLUTION
It works when I use JSON.parse(JSON.stringify(obj)) instead of obj.
Your checks aren't working because Mongoose document objects don't use simple object properties to expose their fields.
Instead, you can use the Document#get method to do this (with your obj renamed to doc):
var isMissing = (doc.get('lessons') === undefined);
Or you can create a plain JS object from your document by calling toObject() on it, and then use hasOwnProperty on that:
var obj = doc.toObject();
var isMissing = !obj.hasOwnProperty('lessons');
Here is a function that I wrote as an example to test three ways you have listed in your question:
function check(obj) {
if (!obj.hasOwnProperty("lessons")) {
console.log('nope');
}
if (!_.has(obj, 'lessons')) {
console.log('nope');
}
if (!obj.lessons) {
console.log('nope');
}
}
Here is JSBIN that runs the function on two objects, one with 'lessons' and one without:
Example JsBIN
typeof returns a string
var obj = {};
console.log(typeof (typeof obj.lessons));
https://jsfiddle.net/0ar2ku7v/
So you must compare it as such:
if (typeof obj.lessons === 'undefined')
console.log('nope');

what is the value of an ignored parameter in javascript?

I was wondering what is the value of an ignored parameter in JS. Lets say that a function takes 2 values as parameters and we only provide one on the call. What is the value of the other one? I thought it would be undefined but the following piece of code only displays "1".
var test = function(par1, par2){
document.write(par1.toString());
document.write(par2.toString());
if(typeof par2 === "undefined"){
document.write('undefined');
}
};
test(1);
the following code would work:
var test = function(par1, par2){
document.write(par1.toString());
document.write(par2);
if(par2 === undefined){
document.write('undefined');
}
};
test(1);
When parameter is not supplied, its value is undefined. Note that variable itself is available (after all, its name is already supplied to a function via arguments list, and it's the name that counts in JavaScript), so there's no need to check it via typeof var === 'undefined' to avoid those pesky ReferenceErrors.
undefined is a special value in JavaScript. While you cannot call any method on it (fails with undefined is not an object Error), you still can use it in expressions and function calls. In this particular case document.write will implicitly convert this value to String before displaying it; the result will be a String - 'undefined'.
Demo.
Try:
var test = function(par1, par2){
if(par2 === undefined){
document.write('undefined');
}
};
test(1);
Working demo
You can also check, if your attributes are set. Example:
var test = function(par1, par2){
if(par1 === undefined){
document.write('par1 is undefined');
}else{
document.write('par1 is set');
}
if(par2 === undefined){
document.write('par2 is undefined');
}else{
document.write('par2 is set');
}
};
test(1);
And output will be:
par1 is set
par2 is undefined
Demo 2
Hope it'll help :)

Check if object exists in JavaScript

How do I verify the existence of an object in JavaScript?
The following works:
if (!null)
alert("GOT HERE");
But this throws an Error:
if (!maybeObject)
alert("GOT HERE");
The Error:
maybeObject is not defined.
You can safely use the typeof operator on undefined variables.
If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.
Therefore
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
There are a lot of half-truths here, so I thought I make some things clearer.
Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).
The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined
var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)
So both a variable that exists and another one that doesn't can report you the undefined type.
As for #Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.
If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.
The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.
You can use:
if (typeof objectName == 'object') {
//do something
}
Two ways:
typeof for local variables
You can test for a local object using typeof:
if (typeof object !== "undefined") {}
window for global variables
You can test for a global object (one defined on the global scope) by inspecting the window object:
if (window.FormData) {}
If that's a global object, you can use if (!window.maybeObject)
You could use "typeof".
if(typeof maybeObject != "undefined")
alert("GOT HERE");
If you care about its existence only ( has it been declared ? ), the approved answer is enough :
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
If you care about it having an actual value, you should add:
if (typeof maybeObject != "undefined" && maybeObject != null ) {
alert("GOT THERE");
}
As typeof( null ) == "object"
e.g. bar = { x: 1, y: 2, z: null}
typeof( bar.z ) == "object"
typeof( bar.not_present ) == "undefined"
this way you check that it's neither null or undefined, and since typeof does not error if value does not exist plus && short circuits, you will never get a run-time error.
Personally, I'd suggest adding a helper fn somewhere (and let's not trust typeof() ):
function exists(data){
data !== null && data !== undefined
}
if( exists( maybeObject ) ){
alert("Got here!");
}
I used to just do a if(maybeObject) as the null check in my javascripts.
if(maybeObject){
alert("GOT HERE");
}
So only if maybeObject - is an object, the alert would be shown.
I have an example in my site.
https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes
The thread was opened quite some time ago. I think in the meanwhile the usage of a ternary operator is the simplest option:
maybeObject ? console.log(maybeObject.id) : ""
I've just tested the typeOf examples from above and none worked for me, so instead I've used this:
btnAdd = document.getElementById("elementNotLoadedYet");
if (btnAdd) {
btnAdd.textContent = "Some text here";
} else {
alert("not detected!");
}
Apart from checking the existence of the object/variable you may want to provide a "worst case" output or at least trap it into an alert so it doesn't go unnoticed.
Example of function that checks, provides alternative, and catch errors.
function fillForm(obj) {
try {
var output;
output = (typeof obj !== 'undefined') ? obj : '';
return (output);
}
catch (err) {
// If an error was thrown, sent it as an alert
// to help with debugging any problems
alert(err.toString());
// If the obj doesn't exist or it's empty
// I want to fill the form with ""
return ('');
} // catch End
} // fillForm End
I created this also because the object I was passing to it could be x , x.m , x.m[z] and typeof x.m[z] would fail with an error if x.m did not exist.
I hope it helps. (BTW, I am novice with JS)
for me this worked for a DOM-object:
if(document.getElementsById('IDname').length != 0 ){
alert("object exist");
}
if (n === Object(n)) {
// code
}
if (maybeObject !== undefined)
alert("Got here!");
set Textbox value to one frame to inline frame using div alignmnt tabbed panel.
So first of all, before set the value we need check selected tabbed panels frame available or not using following codes:
Javascript Code :
/////////////////////////////////////////
<script>
function set_TextID()
{
try
{
if(!parent.frames["entry"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["entry"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["education"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["education"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["contact"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["contact"].document.getElementById("form_id").value=setText;
}
}catch(exception){}
}
</script>
zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.
if(obj) console.log("exists");
I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.
Think it's easiest like this
if(myobject_or_myvar)
alert('it exists');
else
alert("what the hell you'll talking about");
Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible. i.e.:
Things like: exists("blabla"), or even: exists("foreignObject.guessedProperty.guessNext.propertyNeeded") are also possible...

Categories