What does the construct x = x || y mean? - javascript

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.

Related

Why is (null==undefined) true in JavaScript? [duplicate]

How do I check a variable if it's null or undefined and what is the difference between the null and undefined?
What is the difference between == and === (it's hard to search Google for "===" )?
How do I check a variable if it's null or undefined...
Is the variable null:
if (a === null)
// or
if (a == null) // but see note below
...but note the latter will also be true if a is undefined.
Is it undefined:
if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below
...but again, note that the last one is vague; it will also be true if a is null.
Now, despite the above, the usual way to check for those is to use the fact that they're falsey:
if (!a) {
// `a` is falsey, which includes `undefined` and `null`
// (and `""`, and `0`, and `NaN`, and [of course] `false`)
}
This is defined by ToBoolean in the spec.
...and what is the difference between the null and undefined?
They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)
null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).
Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.
What is the difference between "==" and "==="
The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.
Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).
More in the spec:
Abstract Equality Comparison (==, also called "loose" equality)
Strict Equality Comparison (===)
The difference is subtle.
In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.
But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).
Example:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.
As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.
You may use those operators to check between undefined an null. For example:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
The spec is the place to go for full answers to these questions. Here's a summary:
For a variable x, you can:
check whether it's null by direct comparison using ===. Example: x === null
check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.
The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.
More reading:
Angus Croll's Truth, Equality and JavaScript
Andrea Giammarchi's JavaScript Coercion Demystified
comp.lang.javascript FAQs: JavaScript Type-Conversion
How do I check a variable if it's null or undefined
just check if a variable has a valid value like this :
if(variable)
it will return true if variable does't contain :
null
undefined
0
false
"" (an empty string)
NaN
undefined
It means the variable is not yet intialized .
Example :
var x;
if(x){ //you can check like this
//code.
}
equals(==)
It only check value is equals not datatype .
Example :
var x = true;
var y = new Boolean(true);
x == y ; //returns true
Because it checks only value .
Strict Equals(===)
Checks the value and datatype should be same .
Example :
var x = true;
var y = new Boolean(true);
x===y; //returns false.
Because it checks the datatype x is a primitive type and y is a boolean object .
Ad 1. null is not an identifier for a property of the global object, like undefined can be
let x; // undefined
let y=null; // null
let z=3; // has value
// 'w' // is undeclared
if(!x) console.log('x is null or undefined');
if(!y) console.log('y is null or undefined');
if(!z) console.log('z is null or undefined');
try { if(w) 0 } catch(e) { console.log('w is undeclared') }
// typeof not throw exception for undelared variabels
if(typeof w === 'undefined') console.log('w is undefined');
Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
If your (logical) check is for a negation (!) and you want to capture both JS null and undefined (as different Browsers will give you different results) you would use the less restrictive comparison:
e.g.:
var ItemID = Item.get_id();
if (ItemID != null)
{
//do stuff
}
This will capture both null and undefined
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
//If data has valid value
alert("data "+data);
}
else
{
//If data has null, blank, undefined, zero etc.
alert("data is "+data);
}
}

What is the reason that the OR operator is in this function?

I read the following code but I can not understand what it means "||" in this context:
function factorial(numero) {
numero = numero || 1
return numero * factorial(numero - 1)
}
I understand the logical operators but I do not find the sense to call the function if you pass any argument. That is why the reason for my question.
That's called short-circuiting. || is the OR operator, but the way it is evaluated, it will look at the left side (and never look at the right side, thus "short-circuiting".
If it is true, it will use that value. If it is false, it will use the right side. Here, if 'numero' is undefined, it will be false, and therefore the placeholder default value of 1 will be used.
It is like a fallback. If numero is a falsy value (false, '', undefined, null, NaN, 0) it will set the value to 1.
As we can see here in these two tests, if a values is not passed it will use the fallback otherwise it will use the value passed as a parameter.
function test(value) {
console.log(value || 'Not Set')
}
test()
test('Awesome')
There are also more advanced ways which work differently but also produce the similar effect. Here we can do the complete opposite by using && instead which will only run the next item if the previous command is truthy.
let items = []
function addItem(a) {
let contains = items.includes(a)
!contains && items.push(a)
}
addItem('cat')
addItem('dog')
addItem('pig')
addItem('cat')
addItem('cat')
console.log(items)
In the above we use && instead which will do the exact opposite of ||, so if contains is true, we run the next command, otherwise end the current statement.
Lastly, we can combine the two and get a whole new result:
let items = []
function addItem(a) {
let contains = items.includes(a)
!contains && a % 2 == 0 && items.push(a) || console.log('Item', a, 'is not valid')
}
addItem(1)
addItem(2)
addItem(10)
addItem(15)
addItem(10)
addItem(100)
addItem(102)
addItem(103)
console.log(items)
And with this example we only insert items into the array if they are not already in the array and are an even number. otherwise we will output that the value isn't a valid insert either because it was already in the array, or it wasn't event.
It means or it always means or in JavaScript. What that statement does is to set numero to the current value of numero if it is a truthy value or 1 if it is not.
The new syntax, allows you to do this:
function factorial(numero = 1) {
....
}
Which is more convenient for setting default values to parameters.
In Javascript, but also in other languages, the operator || is defined as:
Logical OR (||) expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.
(https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/Logical_Operators)
That snippet is a shorthand for:
if (!numero)
numero = 1;
So, if numero is a falsey value (0, Nan, null, undefined or an empty string) it will be set at 1.
It only expands the second branch If In your case parameter is not given , as mentioned above It is called Short circuit evaluations.
Treat it like IF numero was passed assign it to variable ELSE set variable to 1

OR logical operator when set a variable on javascript [duplicate]

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.

!! sytactic sugar to check undefined in javascript for boolean values

var x = false;
if (!!x) { // syntactic sugar for x ! =undefined
alert('I will not be shown');
}
here we do have the value "false" for x and so it is defined . Question here is that is it a proper way to check undefined?
If you want to reject only undefined then better to use:
if (typeof x !== "undefined") {
// code
}
because, !!x will neglect other values like x = false / x = ''. Simple for a truth test you can use:
if (x) { ... }
There's really no point to
if (!!x)
as opposed to
if (x)
as the boolean conversion performed by ! is exactly the same thing that the if statement will do anyway.
The !! "trick" is useful when you want to force a boolean conversion and preserve the result:
var xIsTruthy = !!x;
After that, the variable xIsTruthy will contain either true or false.
Of course,
if (x)
will succeed when x is anything other than undefined, null, 0, "", false, or NaN. Sometimes that's OK because you know that x is supposed to be, for example, either nothing or an object reference. However, if you need a more specific test, you have to write that explicitly.
Probably the most widely used check for undefined (or not-undefined, which is what you are checking for) is:
if (typeof x !== "undefined") {
console.log("x is defined");
}
As (I think) you have noted, your test will produce a true value for anything that is falsy, in other words, for null, undefined, 0, "", false, and NaN.

Perk in evaluation of Boolean variables in JavaScript?

I have this slightly peculiar situation, a boolean statement I have is giving me two different evaluations, in the alert and if operator.
var test = new Boolean(homePageNonActive && ((firstTime && homePageHash) || (!firstTime && !homePageHash)));
alert(homePageNonActive && ((firstTime && homePageHash) || (!firstTime && !homePageHash))); // GIVES ME FALSE
alert(test); // GIVES ME TRUE ??? WHY?
if(test){
alert(homePageNonActive); // GIVES ME TRUE
alert(firstTime); // GIVES ME TRUE
alert(homePageHash); // GIVES ME FALSE
}
Everything seems to work just fine as long as you use boolean primitives.
But the issue is that you are mixing Boolean objects (homePageHash) with boolean primitives (homePageNonActive and firstTime). The reason why test is "true" is because a "Boolean object false" is "truthy".
Boolean object is not the same as a boolean primitive.
Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.
var x = new Boolean(false),
y = false;
if (x) {/*this code is executed*/}
if (y) {/*this code is NOT executed*/}

Categories

Resources