Related
I am debugging some JavaScript and can't explain what this || does:
function (title, msg) {
var title = title || 'Error';
var msg = msg || 'Error on Request';
}
Why is this guy using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.
What is the double pipe operator (||)?
The double pipe operator (||) is the logical OR operator . In most languages it works the following way:
If the first value is false, it checks the second value. If that's true, it returns true and if the second value is false, it returns false.
If the first value is true, it always returns true, no matter what the second value is.
So basically it works like this function:
function or(x, y) {
if (x) {
return true;
} else if (y) {
return true;
} else {
return false;
}
}
If you still don't understand, look at this table:
| true false
------+---------------
true | true true
false | true false
In other words, it's only false when both values are false.
How is it different in JavaScript?
JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use || operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:
(function(){}) || {}
What happens there?
If values are not boolean, JavaScript makes implicit conversion to boolean. It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.
So the above example should give true, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's || operator doesn't work as I wrote at the beginning. It works the following way:
If the first value is falsey, it returns the second value.
If the first value is truthy, it returns the first value.
Surprised? Actually, it's "compatible" with the traditional || operator. It could be written as following function:
function or(x, y) {
if (x) {
return x;
} else {
return y;
}
}
If you pass a truthy value as x, it returns x, that is, a truthy value. So if you use it later in if clause:
(function(x, y) {
var eitherXorY = x || y;
if (eitherXorY) {
console.log("Either x or y is truthy.");
} else {
console.log("Neither x nor y is truthy");
}
}(true/*, undefined*/));
you get "Either x or y is truthy.".
If x was falsey, eitherXorY would be y. In this case you would get the "Either x or y is truthy." if y was truthy; otherwise you'd get "Neither x nor y is truthy".
The actual question
Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x, so actually nothing happens; otherwise y is assigned to x. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined or null) as a parameter. Consider following example:
function badFunction(/* boolean */flagA) {
flagA = flagA || true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
It looks valid at the first sight. However, what would happen if you passed false as flagA parameter (since it's boolean, i.e. can be true or false)? It would become true. In this example, there is no way to set flagA to false.
It would be a better idea to explicitly check whether flagA is undefined, like that:
function goodFunction(/* boolean */flagA) {
flagA = typeof flagA !== "undefined" ? flagA : true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
Though it's longer, it always works and it's easier to understand.
You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.
See also Logical Operators on MDN.
It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".
It's shorthand for writing:
if (!title) {
title = "Error";
}
This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:
a OR b
it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:
var title = title || "Error";
basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.
If title is not set, use 'ERROR' as default value.
More generic:
var foobar = foo || default;
Reads: Set foobar to foo or default.
You could even chain this up many times:
var foobar = foo || bar || something || 42;
Explaining this a little more...
The || operator is the logical-or operator. The result is true if the first part is true and it is true if the second part is true and it is true if both parts are true. For clarity, here it is in a table:
X | Y | X || Y
---+---+--------
F | F | F
---+---+--------
F | T | T
---+---+--------
T | F | T
---+---+--------
T | T | T
---+---+--------
Now notice something here? If X is true, the result is always true. So if we know that X is true we don't have to check Y at all. Many languages thus implement "short circuit" evaluators for logical-or (and logical-and coming from the other direction). They check the first element and if that's true they don't bother checking the second at all. The result (in logical terms) is the same, but in terms of execution there's potentially a huge difference if the second element is expensive to calculate.
So what does this have to do with your example?
var title = title || 'Error';
Let's look at that. The title element is passed in to your function. In JavaScript if you don't pass in a parameter, it defaults to a null value. Also in JavaScript if your variable is a null value it is considered to be false by the logical operators. So if this function is called with a title given, it is a non-false value and thus assigned to the local variable. If, however, it is not given a value, it is a null value and thus false. The logical-or operator then evaluates the second expression and returns 'Error' instead. So now the local variable is given the value 'Error'.
This works because of the implementation of logical expressions in JavaScript. It doesn't return a proper boolean value (true or false) but instead returns the value it was given under some rules as to what's considered equivalent to true and what's considered equivalent to false. Look up your JavaScript reference to learn what JavaScript considers to be true or false in boolean contexts.
|| is the boolean OR operator. As in JavaScript, undefined, null, 0, false are considered as falsy values.
It simply means
true || true = true
false || true = true
true || false = true
false || false = false
undefined || "value" = "value"
"value" || undefined = "value"
null || "value" = "value"
"value" || null = "value"
0 || "value" = "value"
"value" || 0 = "value"
false || "value" = "value"
"value" || false = "value"
Basically, it checks if the value before the || evaluates to true. If yes, it takes this value, and if not, it takes the value after the ||.
Values for which it will take the value after the || (as far as I remember):
undefined
false
0
'' (Null or Null string)
Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.
var title = title || 'Error';
var msg = msg || 'Error on Request';
Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:
false.
0 (zero)
"" (empty string)
null.
undefined.
NaN (a special Number value meaning Not-a-Number!)
So in the line
var title = title || 'Error';
If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).
If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.
It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.
i.e.
return ("" || undefined)
returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running
var foo = undefined
foo = foo || ""
foo would be set to ""
Double pipe stands for logical "OR". This is not really the case when the "parameter not set", since strictly in JavaScript if you have code like this:
function foo(par) {
}
Then calls
foo()
foo("")
foo(null)
foo(undefined)
foo(0)
are not equivalent.
Double pipe (||) will cast the first argument to Boolean and if the resulting Boolean is true - do the assignment, otherwise it will assign the right part.
This matters if you check for unset parameter.
Let's say, we have a function setSalary that has one optional parameter. If the user does not supply the parameter then the default value of 10 should be used.
If you do the check like this:
function setSalary(dollars) {
salary = dollars || 10
}
This will give an unexpected result for a call like:
setSalary(0)
It will still set the 10 following the flow described above.
Double pipe operator
This example may be useful:
var section = document.getElementById('special');
if(!section){
section = document.getElementById('main');
}
It can also be:
var section = document.getElementById('special') || document.getElementById('main');
To add some explanation to all said before me, I should give you some examples to understand logical concepts.
var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true
It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.
And operator have the opposite structure like below.
var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh
Quote: "What does the construct x = x || y mean?"
Assigning a default value.
This means providing a default value of y to x,
in case x is still waiting for its value but hasn't received it yet or was deliberately omitted in order to fall back to a default.
And I have to add one more thing: This bit of shorthand is an abomination. It misuses an accidental interpreter optimization (not bothering with the second operation if the first is truthy) to control an assignment. That use has nothing to do with the purpose of the operator. I do not believe it should ever be used.
I prefer the ternary operator for initialization, for example,
var title = title?title:'Error';
This uses a one-line conditional operation for its correct purpose. It still plays unsightly games with truthiness but, that's JavaScript for you.
I am debugging some JavaScript and can't explain what this || does:
function (title, msg) {
var title = title || 'Error';
var msg = msg || 'Error on Request';
}
Why is this guy using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.
What is the double pipe operator (||)?
The double pipe operator (||) is the logical OR operator . In most languages it works the following way:
If the first value is false, it checks the second value. If that's true, it returns true and if the second value is false, it returns false.
If the first value is true, it always returns true, no matter what the second value is.
So basically it works like this function:
function or(x, y) {
if (x) {
return true;
} else if (y) {
return true;
} else {
return false;
}
}
If you still don't understand, look at this table:
| true false
------+---------------
true | true true
false | true false
In other words, it's only false when both values are false.
How is it different in JavaScript?
JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use || operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:
(function(){}) || {}
What happens there?
If values are not boolean, JavaScript makes implicit conversion to boolean. It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.
So the above example should give true, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's || operator doesn't work as I wrote at the beginning. It works the following way:
If the first value is falsey, it returns the second value.
If the first value is truthy, it returns the first value.
Surprised? Actually, it's "compatible" with the traditional || operator. It could be written as following function:
function or(x, y) {
if (x) {
return x;
} else {
return y;
}
}
If you pass a truthy value as x, it returns x, that is, a truthy value. So if you use it later in if clause:
(function(x, y) {
var eitherXorY = x || y;
if (eitherXorY) {
console.log("Either x or y is truthy.");
} else {
console.log("Neither x nor y is truthy");
}
}(true/*, undefined*/));
you get "Either x or y is truthy.".
If x was falsey, eitherXorY would be y. In this case you would get the "Either x or y is truthy." if y was truthy; otherwise you'd get "Neither x nor y is truthy".
The actual question
Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x, so actually nothing happens; otherwise y is assigned to x. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined or null) as a parameter. Consider following example:
function badFunction(/* boolean */flagA) {
flagA = flagA || true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
It looks valid at the first sight. However, what would happen if you passed false as flagA parameter (since it's boolean, i.e. can be true or false)? It would become true. In this example, there is no way to set flagA to false.
It would be a better idea to explicitly check whether flagA is undefined, like that:
function goodFunction(/* boolean */flagA) {
flagA = typeof flagA !== "undefined" ? flagA : true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
Though it's longer, it always works and it's easier to understand.
You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.
See also Logical Operators on MDN.
It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".
It's shorthand for writing:
if (!title) {
title = "Error";
}
This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:
a OR b
it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:
var title = title || "Error";
basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.
If title is not set, use 'ERROR' as default value.
More generic:
var foobar = foo || default;
Reads: Set foobar to foo or default.
You could even chain this up many times:
var foobar = foo || bar || something || 42;
Explaining this a little more...
The || operator is the logical-or operator. The result is true if the first part is true and it is true if the second part is true and it is true if both parts are true. For clarity, here it is in a table:
X | Y | X || Y
---+---+--------
F | F | F
---+---+--------
F | T | T
---+---+--------
T | F | T
---+---+--------
T | T | T
---+---+--------
Now notice something here? If X is true, the result is always true. So if we know that X is true we don't have to check Y at all. Many languages thus implement "short circuit" evaluators for logical-or (and logical-and coming from the other direction). They check the first element and if that's true they don't bother checking the second at all. The result (in logical terms) is the same, but in terms of execution there's potentially a huge difference if the second element is expensive to calculate.
So what does this have to do with your example?
var title = title || 'Error';
Let's look at that. The title element is passed in to your function. In JavaScript if you don't pass in a parameter, it defaults to a null value. Also in JavaScript if your variable is a null value it is considered to be false by the logical operators. So if this function is called with a title given, it is a non-false value and thus assigned to the local variable. If, however, it is not given a value, it is a null value and thus false. The logical-or operator then evaluates the second expression and returns 'Error' instead. So now the local variable is given the value 'Error'.
This works because of the implementation of logical expressions in JavaScript. It doesn't return a proper boolean value (true or false) but instead returns the value it was given under some rules as to what's considered equivalent to true and what's considered equivalent to false. Look up your JavaScript reference to learn what JavaScript considers to be true or false in boolean contexts.
|| is the boolean OR operator. As in JavaScript, undefined, null, 0, false are considered as falsy values.
It simply means
true || true = true
false || true = true
true || false = true
false || false = false
undefined || "value" = "value"
"value" || undefined = "value"
null || "value" = "value"
"value" || null = "value"
0 || "value" = "value"
"value" || 0 = "value"
false || "value" = "value"
"value" || false = "value"
Basically, it checks if the value before the || evaluates to true. If yes, it takes this value, and if not, it takes the value after the ||.
Values for which it will take the value after the || (as far as I remember):
undefined
false
0
'' (Null or Null string)
Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.
var title = title || 'Error';
var msg = msg || 'Error on Request';
Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:
false.
0 (zero)
"" (empty string)
null.
undefined.
NaN (a special Number value meaning Not-a-Number!)
So in the line
var title = title || 'Error';
If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).
If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.
It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.
i.e.
return ("" || undefined)
returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running
var foo = undefined
foo = foo || ""
foo would be set to ""
Double pipe stands for logical "OR". This is not really the case when the "parameter not set", since strictly in JavaScript if you have code like this:
function foo(par) {
}
Then calls
foo()
foo("")
foo(null)
foo(undefined)
foo(0)
are not equivalent.
Double pipe (||) will cast the first argument to Boolean and if the resulting Boolean is true - do the assignment, otherwise it will assign the right part.
This matters if you check for unset parameter.
Let's say, we have a function setSalary that has one optional parameter. If the user does not supply the parameter then the default value of 10 should be used.
If you do the check like this:
function setSalary(dollars) {
salary = dollars || 10
}
This will give an unexpected result for a call like:
setSalary(0)
It will still set the 10 following the flow described above.
Double pipe operator
This example may be useful:
var section = document.getElementById('special');
if(!section){
section = document.getElementById('main');
}
It can also be:
var section = document.getElementById('special') || document.getElementById('main');
To add some explanation to all said before me, I should give you some examples to understand logical concepts.
var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true
It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.
And operator have the opposite structure like below.
var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh
Quote: "What does the construct x = x || y mean?"
Assigning a default value.
This means providing a default value of y to x,
in case x is still waiting for its value but hasn't received it yet or was deliberately omitted in order to fall back to a default.
And I have to add one more thing: This bit of shorthand is an abomination. It misuses an accidental interpreter optimization (not bothering with the second operation if the first is truthy) to control an assignment. That use has nothing to do with the purpose of the operator. I do not believe it should ever be used.
I prefer the ternary operator for initialization, for example,
var title = title?title:'Error';
This uses a one-line conditional operation for its correct purpose. It still plays unsightly games with truthiness but, that's JavaScript for you.
I am debugging some JavaScript and can't explain what this || does:
function (title, msg) {
var title = title || 'Error';
var msg = msg || 'Error on Request';
}
Why is this guy using var title = title || 'ERROR'? I sometimes see it without a var declaration as well.
What is the double pipe operator (||)?
The double pipe operator (||) is the logical OR operator . In most languages it works the following way:
If the first value is false, it checks the second value. If that's true, it returns true and if the second value is false, it returns false.
If the first value is true, it always returns true, no matter what the second value is.
So basically it works like this function:
function or(x, y) {
if (x) {
return true;
} else if (y) {
return true;
} else {
return false;
}
}
If you still don't understand, look at this table:
| true false
------+---------------
true | true true
false | true false
In other words, it's only false when both values are false.
How is it different in JavaScript?
JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use || operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:
(function(){}) || {}
What happens there?
If values are not boolean, JavaScript makes implicit conversion to boolean. It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.
So the above example should give true, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's || operator doesn't work as I wrote at the beginning. It works the following way:
If the first value is falsey, it returns the second value.
If the first value is truthy, it returns the first value.
Surprised? Actually, it's "compatible" with the traditional || operator. It could be written as following function:
function or(x, y) {
if (x) {
return x;
} else {
return y;
}
}
If you pass a truthy value as x, it returns x, that is, a truthy value. So if you use it later in if clause:
(function(x, y) {
var eitherXorY = x || y;
if (eitherXorY) {
console.log("Either x or y is truthy.");
} else {
console.log("Neither x nor y is truthy");
}
}(true/*, undefined*/));
you get "Either x or y is truthy.".
If x was falsey, eitherXorY would be y. In this case you would get the "Either x or y is truthy." if y was truthy; otherwise you'd get "Neither x nor y is truthy".
The actual question
Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x, so actually nothing happens; otherwise y is assigned to x. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined or null) as a parameter. Consider following example:
function badFunction(/* boolean */flagA) {
flagA = flagA || true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
It looks valid at the first sight. However, what would happen if you passed false as flagA parameter (since it's boolean, i.e. can be true or false)? It would become true. In this example, there is no way to set flagA to false.
It would be a better idea to explicitly check whether flagA is undefined, like that:
function goodFunction(/* boolean */flagA) {
flagA = typeof flagA !== "undefined" ? flagA : true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
Though it's longer, it always works and it's easier to understand.
You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.
See also Logical Operators on MDN.
It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".
It's shorthand for writing:
if (!title) {
title = "Error";
}
This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:
a OR b
it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:
var title = title || "Error";
basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.
If title is not set, use 'ERROR' as default value.
More generic:
var foobar = foo || default;
Reads: Set foobar to foo or default.
You could even chain this up many times:
var foobar = foo || bar || something || 42;
Explaining this a little more...
The || operator is the logical-or operator. The result is true if the first part is true and it is true if the second part is true and it is true if both parts are true. For clarity, here it is in a table:
X | Y | X || Y
---+---+--------
F | F | F
---+---+--------
F | T | T
---+---+--------
T | F | T
---+---+--------
T | T | T
---+---+--------
Now notice something here? If X is true, the result is always true. So if we know that X is true we don't have to check Y at all. Many languages thus implement "short circuit" evaluators for logical-or (and logical-and coming from the other direction). They check the first element and if that's true they don't bother checking the second at all. The result (in logical terms) is the same, but in terms of execution there's potentially a huge difference if the second element is expensive to calculate.
So what does this have to do with your example?
var title = title || 'Error';
Let's look at that. The title element is passed in to your function. In JavaScript if you don't pass in a parameter, it defaults to a null value. Also in JavaScript if your variable is a null value it is considered to be false by the logical operators. So if this function is called with a title given, it is a non-false value and thus assigned to the local variable. If, however, it is not given a value, it is a null value and thus false. The logical-or operator then evaluates the second expression and returns 'Error' instead. So now the local variable is given the value 'Error'.
This works because of the implementation of logical expressions in JavaScript. It doesn't return a proper boolean value (true or false) but instead returns the value it was given under some rules as to what's considered equivalent to true and what's considered equivalent to false. Look up your JavaScript reference to learn what JavaScript considers to be true or false in boolean contexts.
|| is the boolean OR operator. As in JavaScript, undefined, null, 0, false are considered as falsy values.
It simply means
true || true = true
false || true = true
true || false = true
false || false = false
undefined || "value" = "value"
"value" || undefined = "value"
null || "value" = "value"
"value" || null = "value"
0 || "value" = "value"
"value" || 0 = "value"
false || "value" = "value"
"value" || false = "value"
Basically, it checks if the value before the || evaluates to true. If yes, it takes this value, and if not, it takes the value after the ||.
Values for which it will take the value after the || (as far as I remember):
undefined
false
0
'' (Null or Null string)
Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.
var title = title || 'Error';
var msg = msg || 'Error on Request';
Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:
false.
0 (zero)
"" (empty string)
null.
undefined.
NaN (a special Number value meaning Not-a-Number!)
So in the line
var title = title || 'Error';
If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).
If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.
It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.
i.e.
return ("" || undefined)
returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running
var foo = undefined
foo = foo || ""
foo would be set to ""
Double pipe stands for logical "OR". This is not really the case when the "parameter not set", since strictly in JavaScript if you have code like this:
function foo(par) {
}
Then calls
foo()
foo("")
foo(null)
foo(undefined)
foo(0)
are not equivalent.
Double pipe (||) will cast the first argument to Boolean and if the resulting Boolean is true - do the assignment, otherwise it will assign the right part.
This matters if you check for unset parameter.
Let's say, we have a function setSalary that has one optional parameter. If the user does not supply the parameter then the default value of 10 should be used.
If you do the check like this:
function setSalary(dollars) {
salary = dollars || 10
}
This will give an unexpected result for a call like:
setSalary(0)
It will still set the 10 following the flow described above.
Double pipe operator
This example may be useful:
var section = document.getElementById('special');
if(!section){
section = document.getElementById('main');
}
It can also be:
var section = document.getElementById('special') || document.getElementById('main');
To add some explanation to all said before me, I should give you some examples to understand logical concepts.
var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true
It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.
And operator have the opposite structure like below.
var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh
Quote: "What does the construct x = x || y mean?"
Assigning a default value.
This means providing a default value of y to x,
in case x is still waiting for its value but hasn't received it yet or was deliberately omitted in order to fall back to a default.
And I have to add one more thing: This bit of shorthand is an abomination. It misuses an accidental interpreter optimization (not bothering with the second operation if the first is truthy) to control an assignment. That use has nothing to do with the purpose of the operator. I do not believe it should ever be used.
I prefer the ternary operator for initialization, for example,
var title = title?title:'Error';
This uses a one-line conditional operation for its correct purpose. It still plays unsightly games with truthiness but, that's JavaScript for you.
I want to know what the difference is between null and undefined in JavaScript.
undefined means a variable has been declared but has not yet been assigned a value :
var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined
null is an assignment value. It can be assigned to a variable as a representation of no value :
var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object
From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Proof :
console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)
and
null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
The difference can be explained with toilet tissue holder:
A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.
A zero value is like a holder with an empty toilet tissue tube.
A null value is like a holder that doesn't even have a tissue tube.
An undefined value is similar to the holder itself being missing.
I picked this from here
The undefined value is a primitive value used when a variable has not
been assigned a value.
The null value is a primitive value that represents the null, empty,
or non-existent reference.
When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:
var s;
WScript.Echo(s);
WScript.Echo("" + s);
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.
You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
undefined == null
null == undefined
They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:
var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));
Running the above script will result in the following output:
undefined
object
Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).
You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.
Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.
var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);
The result of the above script is:
0.) a
1.) undefined
2.) c
You will also get undefined returned when reading a subscript or member that never existed.
The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.
Please read the following carefully. It should remove all your doubts regarding the difference between null and undefined in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.
In JavaScript we can have the following types of variables:
Undeclared Variables
Declared but Unassigned Variables
Variables assigned with literal undefined
Variables assigned with literal null
Variables assigned with anything other than undefined or null
The following explains each of these cases one by one:
Undeclared Variables
Can only be checked with the typeof operator which returns string 'undefined'
Cannot be checked with the loose equality operator ( == undefined ), let alone the strict equality operator ( === undefined ),
as well as if-statements and ternary operators ( ? : ) — these throw Reference Errors
Declared but Unassigned Variables
typeof returns string 'undefined'
== check with null returns true
== check with undefined returns true
=== check with null returns false
=== check with undefined returns true
Is falsy to if-statements and ternary operators ( ? : )
Variables assigned with literal undefined
These variables are treated exactly the same as Declared But Unassigned Variables.
Variables assigned with literal null
typeof returns string 'object'
== check with null returns true
== check with undefined returns true
=== check with null returns true
=== check with undefined returns false
Is falsy to if-statements and ternary operators ( ? : )
Variables assigned with anything other than undefined or null
typeof returns one of the following strings: 'bigint', 'boolean', 'function', 'number', 'object', 'string', 'symbol'
Following provides the algorithm for correct type checking of a variable:
Get the typeof our variable and return it if it isn't 'object'
Check for null, as typeof null returns 'object' as well
Evaluate Object.prototype.toString.call(o) with a switch statement to return a more precise value. Object's toString method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'
If that last part is the case (the stringified version of the variable being '[object Object]') and the parameter returnConstructorBoolean is true, it will try to get the name of the constructor by toString-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned
(supports all types up to ECMAScript 2020)
function TypeOf(o, returnConstructorBoolean) {
const type = typeof o
if (type !== 'object') return type
if (o === null) return 'null'
const toString = Object.prototype.toString.call(o)
switch (toString) {
// Value types: 6
case '[object BigInt]': return 'bigint'
case '[object Boolean]': return 'boolean'
case '[object Date]': return 'date'
case '[object Number]': return 'number'
case '[object String]': return 'string'
case '[object Symbol]': return 'symbol'
// Error types: 7
case '[object Error]': return 'error'
case '[object EvalError]': return 'evalerror'
case '[object RangeError]': return 'rangeerror'
case '[object ReferenceError]': return 'referenceerror'
case '[object SyntaxError]': return 'syntaxerror'
case '[object TypeError]': return 'typeerror'
case '[object URIError]': return 'urierror'
// Indexed Collection and Helper types: 13
case '[object Array]': return 'array'
case '[object Int8Array]': return 'int8array'
case '[object Uint8Array]': return 'uint8array'
case '[object Uint8ClampedArray]': return 'uint8clampedarray'
case '[object Int16Array]': return 'int16array'
case '[object Uint16Array]': return 'uint16array'
case '[object Int32Array]': return 'int32array'
case '[object Uint32Array]': return 'uint32array'
case '[object Float32Array]': return 'float32array'
case '[object Float64Array]': return 'float64array'
case '[object ArrayBuffer]': return 'arraybuffer'
case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
case '[object DataView]': return 'dataview'
// Keyed Collection types: 2
case '[object Map]': return 'map'
case '[object WeakMap]': return 'weakmap'
// Set types: 2
case '[object Set]': return 'set'
case '[object WeakSet]': return 'weakset'
// Operation types: 3
case '[object RegExp]': return 'regexp'
case '[object Proxy]': return 'proxy'
case '[object Promise]': return 'promise'
// Plain objects
case '[object Object]':
if (!returnConstructorBoolean)
return type
const _prototype = Object.getPrototypeOf(o)
if (!_prototype)
return type
const _constructor = _prototype.constructor
if (!_constructor)
return type
const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
return matches ? matches[1] : 'anonymous'
default: return toString.split(' ')[1].slice(0, -1)
}
}
null is a special keyword that indicates an absence of value.
think about it as a value, like:
"foo" is string,
true is boolean ,
1234 is number,
null is undefined.
undefined property indicates that a variable has not been assigned a value including null too .
Like
var foo;
defined empty variable is null of datatype undefined
Both of them are representing a value of a variable with no value
AND
null doesn't represent a string that has no value - empty string-
Like
var a = '';
console.log(typeof a); // string
console.log(a == null); //false
console.log(a == undefined); // false
Now if
var a;
console.log(a == null); //true
console.log(a == undefined); //true
BUT
var a;
console.log(a === null); //false
console.log(a === undefined); // true
SO each one has it own way to use
undefined use it to compare the variable data type
null use it to empty a value of a variable
var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object
null: absence of value for a variable; undefined: absence of variable itself;
..where variable is a symbolic name associated with a value.
JS could be kind enough to implicitly init newly declared variables with null, but it does not.
You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.
via JavaScript:The Definitive Guide
The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:
let supervisor = "None"
// I have a supervisor named "None"
let supervisor = null
// I do NOT have a supervisor. It is a FACT that I do not.
let supervisor = undefined
// I may or may not have a supervisor. I either don't know
// if I do or not, or I am choosing not to tell you. It is
// irrelevant or none of your business.
There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values, null and undefined. You are free to use those values explicitly to convey those meanings.
So what are some of the JavaScript-specific issues that arise due to this philosophical basis?
A declared variable without an initializer gets the value undefined because you never said anything about the what the intended value was.
let supervisor;
assert(supervisor === undefined);
A property of an object that has never been set evaluates to undefined because no one ever said anything about that property.
const dog = { name: 'Sparky', age: 2 };
assert(dog.breed === undefined);
null and undefined are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.
assert(null == undefined);
assert(null !== undefined);
null and undefined thankfully have different types. null belongs to the type Null and undefined to the type Undefined. This is in the spec, but you would never know this because of the typeof weirdness which I will not repeat here.
A function reaching the end of its body without an explicit return statement returns undefined since you don't know anything about what it returned.
By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)
NaN
Using a variable that has never been declared and receiving a ReferenceError
Using a let or const defined local variable in its temporal dead zone and receiving a ReferenceError
Empty cells in sparse arrays. Yes these are not even undefined although they compare === to undefined.
$ node
> const a = [1, undefined, 2]
> const b = [1, , 2]
> a
[ 1, undefined, 2 ]
> b
[ 1, <1 empty item>, 2 ]
A lot of "technical" answers have been given, all of them mostly correct from the limited point of view of JS as a mere programming language.
However, I would like to add the following thoughts, especially when you're writing TypeScript code as part of a bigger project / (enterprise) application:
When talking with a Backend of some kind you'll most probably receive JSON
While some backends correctly avoid the use of "null" in their JSON (removing those properties), others do not
Now, while "null" may mean that the value is missing deliberately, more often it does not convey this meaning. Most databases use "null" just because they don't have an "undefined" type. But the meaning really just is "undefined".
Because of that, you can never know if a "null" value really means deliberate absence. Therefore "null" cannot really mean the deliberate choice of "missing value". It is undecidable in general.
As a consequence, semantically, "null" and "undefined" are exactly the same thing in practice.
Therefore, in an effort to harmonize things I'm strictly against using "null" and want to encourage you to stop using "null" in your code. It's far easier than you might think. Don't get me wrong. I'm not talking about not handling "null" values, only to avoid explicitly using them in your code. Put differently: your code should still be able to work with accidentally passed "null" values coming from outside your application, e.g. via a 3rd party lib like Angular, or a 3rd party backend.
Here are the guidelines that make it possible:
avoid direct undefined type guards (e.g. if (value === undefined) { ... }.
Instead, use indirect type guards (aka truthiness checks) e.g. if (value) { ... }
Whenever 0 or empty strings are meaningful, use either
an explicit helper method like Lodash's isNil
or include the meaningful value in the comparison (e.g. if (!value && value !== 0) { ... })
Consider using a lint rule that disallows the usage of null
null is a special value meaning "no value". null is a special object because typeof null returns 'object'.
On the other hand, undefined means that the variable has not been declared, or has not been given a value.
I'll explain undefined, null and Uncaught ReferenceError:
1 - Uncaught ReferenceError : variable has not been declared in your script, there is no reference to this varaible
2 - undefined: Variable declared but does not initialised
3 - null : Variable declared and is an empty value
null and undefined are two distinct object types which have the following in common:
both can only hold a single value, null and undefined respectively;
both have no properties or methods and an attempt to read any properties of either will result in a run-time error (for all other objects, you get value undefined if you try to read a non-existent property);
values null and undefined are considered equal to each other and to nothing else by == and != operators.
The similarities however end here. For once, there is a fundamental difference in the way how keywords null and undefined are implemented. This is not obvious, but consider the following example:
var undefined = "foo";
WScript.Echo(undefined); // This will print: foo
undefined, NaN and Infinity are just names of preinitialized "superglobal" variables - they are initialized at run-time and can be overridden by normal global or local variable with the same names.
Now, let's try the same thing with null:
var null = "foo"; // This will cause a compile-time error
WScript.Echo(null);
Oops! null, true and false are reserved keywords - compiler won't let you use them as variable or property names
Another difference is that undefined is a primitive type, while null is an object type (indicating the absense of an object reference). Consider the following:
WScript.Echo(typeof false); // Will print: boolean
WScript.Echo(typeof 0); // Will print: number
WScript.Echo(typeof ""); // Will print: string
WScript.Echo(typeof {}); // Will print: object
WScript.Echo(typeof undefined); // Will print: undefined
WScript.Echo(typeof null); // (!!!) Will print: object
Also, there is an important difference in the way null and undefined are treated in numeric context:
var a; // declared but uninitialized variables hold the value undefined
WScript.Echo(a === undefined); // Prints: -1
var b = null; // the value null must be explicitly assigned
WScript.Echo(b === null); // Prints: -1
WScript.Echo(a == b); // Prints: -1 (as expected)
WScript.Echo(a >= b); // Prints: 0 (WTF!?)
WScript.Echo(a >= a); // Prints: 0 (!!!???)
WScript.Echo(isNaN(a)); // Prints: -1 (a evaluates to NaN!)
WScript.Echo(1*a); // Prints: -1.#IND (in Echo output this means NaN)
WScript.Echo(b >= b); // Prints: -1 (as expected)
WScript.Echo(isNaN(b)); // Prints: 0 (b evaluates to a valid number)
WScript.Echo(1*b); // Prints: 0 (b evaluates to 0)
WScript.Echo(a >= 0 && a <= 0); // Prints: 0 (as expected)
WScript.Echo(a == 0); // Prints: 0 (as expected)
WScript.Echo(b >= 0 && b <= 0); // Prints: -1 (as expected)
WScript.Echo(b == 0); // Prints: 0 (!!!)
null becomes 0 when used in arithmetic expressions or numeric comparisons - similarly to false, it is basically just a special kind of "zero". undefined, on the other hand, is a true "nothing" and becomes NaN ("not a number") when you try to use it in numeric context.
Note that null and undefined receive a special treatment from == and != operators, but you can test true numeric equality of a and b with the expression (a >= b && a <= b).
Undefined means a variable has been declared but has no value:
var var1;
alert(var1); //undefined
alert(typeof var1); //undefined
Null is an assignment:
var var2= null;
alert(var2); //null
alert(typeof var2); //object
tl;dr
Use null for set a variable you know it is an Object.
Use undefined for set a variable whose type is mixed.
This is my usage of both 5 primitives and Object type, and that explain the difference between « use case » of undefined or null.
String
If you know a variable is only a string while all lifecycle, by convention, you could initialize it, to "":
("") ? true : false; // false
typeof ""; // "string";
("Hello World") ? true : false; // true
typeof "Hello World"; // "string"
Number
If you know a variable is only a number while all lifecycle, by convention, you could initialize it, to 0 (or NaN if 0 is an important value in your usage):
(0) ? true : false; // false
typeof 0; // "number";
(16) ? true : false; // true
typeof 16; // "number"
or
(NaN) ? true : false; // false
typeof NaN; // "number";
(16) ? true : false; // true
typeof 16; // "number"
Boolean
If you know a variable is only a boolean while all lifecycle, by convention, you could initialize it, to false:
(false) ? true : false; // false
typeof false; // "boolean";
(true) ? true : false; // true
typeof true; // "boolean"
Object
If you know a variable is only an Object while all lifecycle, by convention, you could initialize it, to null:
(null) ? true : false; // false
typeof null; // "object";
({}) ? true : false; // true
typeof {}; // "object"
Note: the smart usage off null is to be the falsy version of an Object because an Object is always true, and because typeof null return object. That means typeof myVarObject return consistent value for both Object and null type.
All
If you know a variable has a mixed type (any type while all lifecycle), by convention, you could initialize it, to undefined.
In addition to a different meaning there are other differences:
Object destructuring works differently for these two values:
const { a = "default" } = { a: undefined }; // a is "default"
const { b = "default" } = { b: null }; // b is null
JSON.stringify() keeps null but omits undefined
const json = JSON.stringify({ undefinedValue: undefined, nullValue: null });
console.log(json); // prints {"nullValue":null}
typeof operator
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" instead of "null"
In JavasScript there are 5 primitive data types: String, Number, Boolean, null and undefined.
I will try to explain with some simple examples.
Let's say we have a simple function
function test(a) {
if(a == null) {
alert("a is null");
} else {
alert("The value of a is " + a);
}
}
Also, in above function if(a == null) is the same as if(!a).
Now when we call this function without passing the parameter a
test(); // will alert "a is null";
test(4); // will alert "The value of a is " + 4;
also
var a;
alert(typeof a);
This will give undefined; we have declared a variable but we have not asigned any value to this variable;
but if we write
var a = null;
alert(typeof a); // will give alert as object
so null is an object. In a way we have assigned a value null to 'a'
When you declare a variable in javascript, it is assigned the value undefined. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.
Now you can explicitly assign a variable null. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.
Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.
OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.
typeof null; //"object"
typeof undefined; //"undefined";
But if you check them with == as below, you see they are both falsy:
null==undefined; //true
Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.
I create a quick image to show the differences for you at a glance.
For the undefined type, there is one and only one value: undefined.
For the null type, there is one and only one value: null.
So for both of them, the label is both its type and its value.
The difference between them. For example:
null is an empty value
undefined is a missing value
Or:
undefined hasn't had a value yet
null had a value and doesn't anymore
Actually, null is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.
However, undefined is an identifier. In both non-strict mode and strict mode, however, you can create a local variable of the name undefined. But this is one terrible idea!
function foo() {
undefined = 2; // bad idea!
}
foo();
function foo() {
"use strict";
undefined = 2; // TypeError!
}
foo();
I want to add a knowledge point which pertains to a subtle difference between null and undefined. This is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:
null is a reserved keyword in JS while undefined is a property on
the global object of the run-time environment you're in.
While writing code, this difference is not identifiable as both null and undefined are always used in right hand side (RHS) of a JavaScript statement. But when you use them in left hand side (LHS) of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:
var null = 'foo'
It gives below error:
Uncaught SyntaxError: Unexpected token null
At the same time, below code runs successfully although I won't recommend doing so in real life:
var undefined = 'bar'
This works because undefined is a property on the global object (window object in case of JavaScript running in a browser)
null and undefined are both are used to represent the absence of some value.
var a = null;
a is initialized and defined.
typeof(a)
//object
null is an object in JavaScript
Object.prototype.toString.call(a) // [object Object]
var b;
b is undefined and uninitialized
undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.
Generally we assign null to variables not undefined.
Per Ryan Morr's thorough article on this subject...
"Generally, if you need to assign a non-value to a variable or property, pass it to a function, or return it from a function, null is almost always the best option. To put it simply, JavaScript uses undefined and programmers should use null."
See Exploring the Eternal Abyss of Null and Undefined
In javascript all variables are stored as key value pairs. Each variable is stored as variable_name : variable_value/reference.
undefined means a variable has been given a space in memory, but no value is assigned to it. As a best practice, you should not use this type as an assignment.
In that case how to denote when you want a variable to be without value at a later point in the code? You can use the type
null ,which is also a type that is used to define the same thing, absence of a value, but it is not the same as undefined, as in this case you actually have the value in memory. That value is null
Both are similar but usage and meaning are different.
The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.
From the Eloquent Javascript book
As typeof returns undefined, undefined is a type where as null is an initializer indicates the variable points to no object(virtually everything in Javascript is an object).
null - It is an assignment value, which is used with variable to represent no value (it's an object).
undefined - It is a variable which does not have any value assigned to it, so JavaScript will assign an undefined to it (it's a data type).
undeclared - If a variable is not created at all, it is known as undeclared.
Check this out. The output is worth thousand words.
var b1 = document.getElementById("b1");
checkif("1, no argument" );
checkif("2, undefined explicitly", undefined);
checkif("3, null explicitly", null);
checkif("4, the 0", 0);
checkif("5, empty string", '');
checkif("6, string", "string");
checkif("7, number", 123456);
function checkif (a1, a2) {
print("\ncheckif(), " + a1 + ":");
if (a2 == undefined) {
print("==undefined: YES");
} else {
print("==undefined: NO");
}
if (a2 === undefined) {
print("===undefined: YES");
} else {
print("===undefined: NO");
}
if (a2 == null) {
print("==null: YES");
} else {
print("==null: NO");
}
if (a2 === null) {
print("===null: YES");
} else {
print("===null: NO");
}
if (a2 == '') {
print("=='': YES");
} else {
print("=='': NO");
}
if (a2 === '') {
print("==='': YES");
} else {
print("==='': NO");
}
if (isNaN(a2)) {
print("isNaN(): YES");
} else {
print("isNaN(): NO");
}
if (a2) {
print("if-?: YES");
} else {
print("if-?: NO");
}
print("typeof(): " + typeof(a2));
}
function print(v) {
b1.innerHTML += v + "\n";
}
<!DOCTYPE html>
<html>
<body>
<pre id="b1"></pre>
</body>
</html>
See also:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
Cheers!
The difference between undefined and null is minimal, but there is a difference. A variable whose value is undefined has never been initialized. A variable whose value is null was explicitly given a value of null, which means that the variable was explicitly set to have no value. If you compare undefined and null by using the null==undefined expression, they will be equal.
Basically, Undefined is a global variable that javascript create at the run time whether null means that no value has assigned to the variable (actually null is itself an object).
Let's take an example:
var x; //we declared a variable x, but no value has been assigned to it.
document.write(x) //let's print the variable x
Undefined that's what you will get as output.
Now,
x=5;
y=null;
z=x+y;
and you will get 5 as output. That's the main difference between the Undefined and null
Both special values imply an empty state.
The main difference is that undefined represents the value of a variable that wasn’t yet initialized, while null represents an intentional absence of an object.
The variable number is defined, however, is not assigned with an initial value:
let number;
number; // => undefined
number variable is undefined, which clearly indicates an uninitialized variable
The same uninitialized concept happens when a non-existing object property is accessed:
const obj = { firstName: 'Dmitri' };
obj.lastName; // => undefined
Because lastName property does not exist in obj, JavaScript correctly evaluates obj.lastName to undefined.
In other cases, you know that a variable expects to hold an object or a function to return an object. But for some reason, you can’t instantiate the object. In such a case null is a meaningful indicator of a missing object.
For example, clone() is a function that clones a plain JavaScript object. The function is expected to return an object:
function clone(obj) {
if (typeof obj === 'object' && obj !== null) {
return Object.assign({}, obj);
}
return null;
}
clone({name: 'John'}); // => {name: 'John'}
clone(15); // => null
clone(null); // => null
However, clone() might be invoked with a non-object argument: 15 or null (or generally a primitive value, null or undefined). In such case, the function cannot create a clone, so it returns null - the indicator of a missing object.
typeof operator makes the distinction between the two values:
typeof undefined; // => 'undefined'
typeof null; // => 'object'
The strict quality operator === correctly differentiates undefined from null:
let nothing = undefined;
let missingObject = null;
nothing === missingObject; // => false
We are frequently using the following code pattern in our JavaScript code
if (typeof(some_variable) != 'undefined' && some_variable != null)
{
// Do something with some_variable
}
Is there a less verbose way of checking that has the same effect?
According to some forums and literature saying simply the following should have the same effect.
if (some_variable)
{
// Do something with some_variable
}
Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?
I think the most efficient way to test for "value is null or undefined" is
if ( some_variable == null ){
// some_variable is either null or undefined
}
So these two lines are equivalent:
if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}
Note 1
As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:
check for optional arguments:
function(foo){
if( foo == null ) {...}
check for properties on an existing object
if(my_obj.foo == null) {...}
On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.
Note 2
This - even shorter - variant is not equivalent:
if ( !some_variable ) {
// some_variable is either null, undefined, 0, NaN, false, or an empty string
}
so
if ( some_variable ) {
// we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}
Note 3
In general it is recommended to use === instead of ==.
The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.
From the jQuery style guide:
Strict equality checks (===) should be used in favor of ==. The only
exception is when checking for undefined and null by way of null.
// Check for both undefined and null values, for some important reason.
undefOrNull == null;
EDIT 2021-03:
Nowadays most browsers
support the Nullish coalescing operator (??)
and the Logical nullish assignment (??=), which allows a more concise way to
assign a default value if a variable is null or undefined, for example:
if (a.speed == null) {
// Set default if null or undefined
a.speed = 42;
}
can be written as any of these forms
a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
You have to differentiate between cases:
Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error
A variable that has been declared but not initialized is undefined.
let foo;
if (foo) //evaluates to false because foo === undefined
Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about
0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:
value = obj.prop || defaultValue
which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".
Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead
value = ('prop' in obj) ? obj.prop : defaultValue
Checking null with normal equality will also return true for undefined.
if (window.variable == null) alert('variable is null or undefined');
This is the only case in which == and != should be used:
if (val == null) console.log('val is null or undefined')
if (val != null) console.log('val is neither null nor undefined')
For any other comparisons, the strict comparators (=== and !==) should be used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
https://2ality.com/2011/12/strict-equality-exemptions.html
In newer JavaScript standards like ES5 and ES6 you can just say
> Boolean(0) //false
> Boolean(null) //false
> Boolean(undefined) //false
all return false, which is similar to Python's check of empty variables.
So if you want to write conditional logic around a variable, just say
if (Boolean(myvar)){
// Do something
}
here "null" or "empty string" or "undefined" will be handled efficiently.
If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.
Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:
if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)
to
if (myObj.some_property != null)
With this in mind, and the fact that global variables are accessible as properties of the global object (window in the case of a browser), you can use the following for global variables:
if (window.some_variable != null) {
// Do something with some_variable
}
In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof.
Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator: == and ===.
A function, test(val) that tests for null or undefined should have the following characteristics:
test(null) => true
test(undefined) => true
test(0) => false
test(1) => false
test(true) => false
test(false) => false
test('s') => false
test([]) => false
Let's see which of the ideas here actually pass our test.
These work:
val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null
These do not work:
typeof(val) === 'undefined'
!!val
I created a jsperf entry to compare the correctness and performance of these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!
At present, it seems that the simple val == null test gives the best performance. It's also pretty much the shortest. The test may be negated to val != null if you want the complement.
here's another way using the Array includes() method:
[undefined, null].includes(value)
Since there is no single complete and correct answer, I will try to summarize:
In general, the expression:
if (typeof(variable) != "undefined" && variable != null)
cannot be simplified, because the variable might be undeclared so omitting the typeof(variable) != "undefined" would result in ReferenceError. But, you can simplify the expression according to the context:
If the variable is global, you can simplify to:
if (window.variable != null)
If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:
if (variable != null)
If it is object property, you don't have to worry about ReferenceError:
if (obj.property != null)
This is an example of a very rare occasion where it is recommended to use == instead of ===. Expression somevar == null will return true for undefined and null, but false for everything else (an error if variable is undeclared).
Using the != will flip the result, as expected.
Modern editors will not warn for using == or != operator with null, as this is almost always the desired behavior.
Most common comparisions:
undeffinedVar == null // true
obj.undefinedProp == null // true
null == null // true
0 == null // false
'0' == null // false
'' == null // false
Try it yourself:
let undefinedVar;
console.table([
{ test : undefinedVar, result: undefinedVar == null },
{ test : {}.undefinedProp, result: {}.undefinedProp == null },
{ test : null, result: null == null },
{ test : false, result: false == null },
{ test : 0, result: 0 == null },
{ test : '', result: '' == null },
{ test : '0', result: '0' == null },
]);
You can just check if the variable has a value or not. Meaning,
if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false
}
If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.
if( typeof myVariable !== 'undefined' ) {
// myVariable will get resolved and it is defined
}
Similar to what you have, you could do something like
if (some_variable === undefined || some_variable === null) {
do stuff
}
This is also a nice (but verbose) way of doing it:
if((someObject.someMember ?? null) === null) {
// bladiebla
}
It's very clear what's happening and hard to misunderstand. And that can be VERY important! :-)
This uses the ?? operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator). If the value of someObject.someMember is null or undefined, the ?? operator kicks in and will make the value null.
TBH, I like the explicitness of this thing, but I usualle prefer someObject.someMember == null, it's more readable and skilled JS developers probably know what's going on here.
whatever yyy is undefined or null, it will return true
if (typeof yyy == 'undefined' || !yyy) {
console.log('yes');
} else {
console.log('no');
}
yes
if (!(typeof yyy == 'undefined' || !yyy)) {
console.log('yes');
} else {
console.log('no');
}
no
Open the Developer tools in your browser and just try the code shown in the below image.
If the purpose of the if statement is to check for null or undefined values before assigning a value to a variable, you can make use of the Nullish Coalescing Operator. According to the data from caniuse, it should be supported by around 85% of the browsers(as of January 2021). An example of the operator is shown below:
const a = some_variable ?? '';
This will ensure that the variable will be assigned to an empty string (or any other default value) if some_variable is null or undefined.
This operator is most suited for your use case, as it does not return the default value for other types of falsy value such as 0 and ''.
As mentioned in one of the answers, you can be in luck if you are talking about a variable that has a global scope. As you might know, the variables that you define globally tend to get added to the windows object. You can take advantage of this fact so lets say you are accessing a variable called bleh, just use the double inverted operator (!!)
!!window['bleh'];
This would return a false while bleh has not been declared AND assigned a value.
In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.
You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.
if (a === undefined || a === null || a==='') {
console.log("Nothing");
} else {
console.log("Something");
}
Also I want to point out one more thing.
What will be the result of Boolean(0)?
Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.
With Ramda, you can simply do R.isNil(yourValue)
Lodash and other helper libraries have the same function.
I have done this using this method
save the id in some variable
var someVariable = document.getElementById("someId");
then use if condition
if(someVariable === ""){
//logic
} else if(someVariable !== ""){
//logic
}
In ES5 or ES6 if you need check it several times you cand do:
const excluded = [null, undefined, ''];
if (!exluded.includes(varToCheck) {
// it will bee not null, not undefined and not void string
}
let varToCheck = ""; //U have to define variable firstly ,or it throw error
const excluded = [null, undefined, ""];
if (!excluded.includes(varToCheck)) {
// it will bee not null, not undefined and not void string
console.log("pass");
} else {
console.log("fail");
}
for example I copy vladernn's answer to test, u can just click button "Copy snippets to answer" to test too .
Testing nullity (if (value == null)) or non-nullity (if (value != null)) is less verbose than testing the definition status of a variable.
Moreover, testing if (value) (or if( obj.property)) to ensure the existence of your variable (or object property) fails if it is defined with a boolean false value. Caveat emptor :)
Best way to compare undefined or null or 0 with ES5 and ES6 standards
if ((Boolean(some_variable_1) && Boolean(some_variable_2)) === false) {
// do something
}
You can make use of lodash library.
_.isNil(value) gives true for both null and undefined
Test on - https://bazinga.tools/lodash
You must define a function of this form:
validate = function(some_variable){
return(typeof(some_variable) != 'undefined' && some_variable != null)
}
Both values can be easily distinguished by using the strict comparison operator.
Sample Code:
function compare(){
var a = null; //variable assigned null value
var b; // undefined
if (a === b){
document.write("a and b have same datatype.");
}
else{
document.write("a and b have different datatype.");
}
}