what is the value of an ignored parameter in javascript? - 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 :)

Related

How to check if module function exist in Node js

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'

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');

Javascript - Shorthand notation to safely check/access a property on a potential undefined object

What's the shortest syntax to check if jsonObject is not undefined before accessing its errorMessage property?
var jsonObject = SomeMethodReturningAnObject();
if (jsonObject.errorMessage === undefined) // jsonObject can be undefined and this will throw an error
/* success! */
else
alert(jsonObject.errorMessage);
You can use the && operator, since it doesn't evaluate the right-hand side if the left-hand side is undefined:
if (jsonObject && jsonObject.errorMessage === undefined)
Another way to do this is to use the typeof operator.
In JS if a variable has been declared but not set a value, such as:
var x;
Then x is set to undefined so you can check for it easily by:
if(x) //x is defined
if(!x) //x is undefined
However if you try to do if(x) on a variable that hasn't even been declared, you'll get the error you allude to in your post, "ReferenceError: x is not defined".
In this case we need to use typeof - MSDN Docs - to check.
So in your case something like:
if(typeof jsonObject !== "undefined") {
//jsonObject is set
if(jsonObject.errorMessage) {
//jsonObject set, errorMessage also set
} else {
//jsonObject set, no errorMessage!
}
} else {
//jsonObject didn't get set
}
This works because if you have a variable set to an empty object, x={}, and try to get at a variable within that object that doesn't exist, eg x.y, you get undefined returned, you don't get a ReferenceError.
Be aware that the typeof operator returns a string denoting the variable type, not the type itself. So it would return "undefined" not undefined.
Also, this very similar question on SO that could help you: How to check a not-defined variable in JavaScript
Hope this helps.
Jack.
var jsonObject = SomeMethodReturningAnObject();
if (jsonObject && jsonObject.errorMessage === undefined)
/* success! */
else
alert(!jsonObject ? "jsonObject not defined" : jsonObject.errorMessage);
if(jsonObject)
{
if (!jsonObject.errorMessage)
// success..
foo()
else
alert(jsonObject.errorMessage);
}
I'll answer the shorthand notation aspect as your specific situation is better served by an existing answer. As of ECMAScript 2018 we have spread syntax, which makes the whole thing much more concise:
if ( {...jsonObject}.errorMessage ) {
// we have errorMessage
} else {
// either jsonObject or jsonObject.errorMessage are undefined / falsey
// in either case, we don't get an exception
}
A straight if / else is not the perfect fit for your situation because you actually have 3 states, 2 of which are crammed into the same if branch above.
No jsonObject: Failure
Has jsonObject, has no errorMessage: Success
Has jsonObject, has errorMessage: Failure
Why this works:
Accessing a property foo from an object obj, assuming the object is undefined, is essentially doing this:
undefined.foo //exception, obviously
Spread syntax copies properties to a new object, so you end up with an object no matter what:
typeof {...undefined} === 'object'
So by spreading obj you avoid operating directly on a potentially undefined variable.
Some more examples:
({...undefined}).foo // === undefined, no exception thrown
({...{'foo': 'bar'}}).foo // === 'bar'

is there something like isset of php in javascript/jQuery? [duplicate]

This question already has answers here:
JavaScript isset() equivalent
(28 answers)
Closed 6 years ago.
Is there something in javascript/jQuery to check whether variable is set/available or not? In php, we use isset($variable) to check something like this.
thanks.
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
JavaScript isset() on PHP JS
function isset () {
// discuss at: http://phpjs.org/functions/isset
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: FremyCompany
// + improved by: Onno Marsman
// + improved by: Rafał Kukawski
// * example 1: isset( undefined, true);
// * returns 1: false
// * example 2: isset( 'Kevin van Zonneveld' );
// * returns 2: true
var a = arguments,
l = a.length,
i = 0,
undef;
if (l === 0) {
throw new Error('Empty isset');
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false;
}
i++;
}
return true;
}
typeof will serve the purpose I think
if(typeof foo != "undefined"){}
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window object) this can work well for checking if values have been declared.
Some parts of each of these answers work. I compiled them all down into a function "isset" just like the question was asking and works like it does in PHP.
// isset helper function
var isset = function(variable){
return typeof(variable) !== "undefined" && variable !== null && variable !== '';
}
Here is a usage example of how to use it:
var example = 'this is an example';
if(isset(example)){
console.log('the example variable has a value set');
}
It depends on the situation you need it for but let me break down what each part does:
typeof(variable) !== "undefined" checks if the variable is defined at all
variable !== null checks if the variable is null (some people explicitly set null and don't think if it is set to null that that is correct, in that case, remove this part)
variable !== '' checks if the variable is set to an empty string, you can remove this if an empty string counts as set for your use case
Hope this helps someone :)
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454
http://phpjs.org/functions/isset:454
phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.
The problem is that passing an undefined variable to a function causes an error.
This means you have to run typeof before passing it as an argument.
The cleanest way I found to do this is like so:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
Usage:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
Now the code is much more compact and readable.
This will still give an error if you try to call a variable from a non instantiated variable like:
isset(typeof(undefVar.subkey))
thus before trying to run this you need to make sure the object is defined:
undefVar = isset(typeof(undefVar))?undefVar:{};
Here :)
function isSet(iVal){
return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
in addition to #emil-vikström's answer, checking for variable!=null would be true for variable!==null as well as for variable!==undefined (or typeof(variable)!="undefined").
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}

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