'&&' and '||' vs '? :' - javascript

Why would you use this syntax?
var myVar = myArray.length && myArray || myObject;
instead of
var myVar = myArray.length ? myArray : myObject;
Edit: I just had a thought that if in the case of the && || syntax both sides of the || evaluated to false, as you might expect if myObject was undefined or null, if false would be returned. But it isn't, the objects value undefined or null is returned.
true || true //true
true || false //true
false || true //true
false || false //false
Edit2:
!!(myArray.length ? myArray : myObject);
This does however return false if myObject is undefined or null

x && y || z is different than x ? y : z even if it "works" in the case presented.
Consider when y evaluates to a false-value (in the post y can't be a false-value when it is evaluated because it is dependent upon x and thus it "works" as expected).
Using ?: is the much better and more clear construct in this case. The only reason I can give for using the other syntax is "too much cleverness".

A ternary is the only correct thing to do here, unless you guarantee that myObject.name has a "true" value.
Consider
res = a ? b : c;
vs.
res = a && b || c;
What is the difference? The first does what it is supposed to. But the second tests a. If a is false, it gets c, as the ternary version.
But if a is true, it only gets b if this is true as well, if not, it gets c, what is not wanted at all.

Tastes vary. Maybe somebody just got in the habit of writing things like
var myName = myObject && myObject.name || "unknown";
and stuck with it even when a ternary would work as well.

http://jsperf.com/conditional-operators
It looks like you use && || when you want your code to go slower and you want to obfuscate it a little more :)
There's also a difference between what is going on.
foo && bar || foobar // if foo or bar is false, then foobar will be returned
foo?bar:foobar // the bar, or foobar, is decided solely on foo
If you wanted the ternary to act like the logical conditional it would be:
foo&&bar?bar:foobar

Related

in Javascript, why would you write 'b || (b = a);'?

Digging through the glMatrix-0.9.5.min.js source used in my webGL project and I came across several lines of code like this...
vec3.negate = function (a, b)
{
b || (b = a); // <-- What exactly does this line do?
b[0] = -a[0];
b[1] = -a[1];
b[2] = -a[2];
return b;
};
Not sure what that code is doing or even if it's a bug considering it's a third-party file, but I also know I'm not completely up to speed about JavaScript as a language. (For instance, I just learned about protocols because of this. Odd/interesting concept.)
So is that valid, and if so, what exactly is it doing?
My guess is it's shorthand for the following, saying 'If 'b' isn't set, set it to a'
if(!b)
{
b = a;
}
which can also just be written
if(!b) b = a;
which I'd argue is much more clear. But again, I'm guessing as to what that actually means/does. Could be wrong.
Follow-up:
Are these two if-conditions equal?
if(!b){ ... }
if(b == undefined){ ... }
I'm wondering if there's a complication between 'undefined' and a defined value that's 'null'
a better way to write that would be
b = b || a;
That means:
b = b ? b : a; //or
b = b || a;
This is shorthand for
if (!b) { b = a }
Lets break it down:
To the left of the || it is asserting on the truthiness of b http://james.padolsey.com/javascript/truthy-falsey/
If b is truthy, then the part to the right of the || will not be evaluated. If b is falsey, then b will get assigned the value/reference of a.
It's basically setting the value of b to a if b is undefined via the || operator which can be used as a null-coalescing operator in Javascript.
You could think of it in terms of an if-statement as follows :
if(b == undefined){
b = a;
}
A Matter of Preference
It's ultimately a matter of preference with regards to what makes the most sense, but any of the approaches that you'll find in this discussion are likely valid options :
// Explicitly using undefined in the comparison
if(b == undefined) { b = a }
// Using an if-statement (with a not)
if(!b){ b = a }
// Using a ternary operator
b = b ? || a
Regarding Your Follow-up
Follow-up: Are these two if-conditions equal?
if(!b){ ... }
if(b == undefined){ ... }
I'm wondering if there's a complication
between 'undefined' and a defined value that's 'null'
Yes, there can be differences as seen with an empty string, which would have the following results :
var b = '';
!b // true
b == undefined // false
Differentiating null and undefined values can be tricky and since it's a bit of out the scope of this question, you might consider checking out this related discussion on the topic, which commonly recommends the use of if(b == null) { b = a; } as opposed to checks against undefined.

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.

&& evaluation issue

As far as I know, The logical && works like the following
var test = false;
var foo = test && 42;
This code, will assign 42 to foo only if the first condition gets evaluated to true. So in this example, foo will keep its current value.
I'm wondering why this snippet doesn't work at all:
var test = "";
var foo = test && 42;
Now, foo gets the value from test assigned. I'm very confused. The empty string is one of Javascripts falsy values, so why would the && operator fail in this scenario ?
Can someone help me out with the spec on this one please ?
You're misunderstanding the operator.
foo = x && y will always assign foo.
The && operator evaluates to its left-most "falsy" operand.
false && 42 evaluates to false; "" && 42 evaluates to "".
var foo = test && 42; assigns false to foo.
You have answered your question yourself.
var foo = test && 42;
42 will be assigned to foo only if test evaluated to true.
So if test is empty string (evaluated to false), 42 won't assigned to foo, foo will be the empty string.

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

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.

What does "options = options || {}" mean in Javascript? [duplicate]

This question already has answers here:
What does the construct x = x || y mean?
(12 answers)
Closed 7 years ago.
I came over a snippet of code the other day that I got curious about, but I'm not really sure what it actually does;
options = options || {};
My thought so far; sets variable options to value options if exists, if not, set to empty object.
Yes/no?
This is useful to setting default values to function arguments, e.g.:
function test (options) {
options = options || {};
}
If you call test without arguments, options will be initialized with an empty object.
The Logical OR || operator will return its second operand if the first one is falsy.
Falsy values are: 0, null, undefined, the empty string (""), NaN, and of course false.
ES6 UPDATE: Now, we have real default parameter values in the language since ES6.
function test (options = {}) {
//...
}
If you call the function with no arguments, or if it's called explicitly with the value undefined, the options argument will take the default value. Unlike the || operator example, other falsy values will not cause the use of the default value.
It's the default-pattern..
What you have in your snippet is the most common way to implement the default-pattern, it will return the value of the first operand that yields a true value when converted to boolean.
var some_data = undefined;
var some_obj_1 = undefined;
var some_obj_2 = {foo: 123};
var str = some_data || "default";
var obj = some_obj1 || some_obj2 || {};
/* str == "default", obj == {foo: 123} */
the above is basically equivalent to doing the following more verbose alternative
var str = undefined;
var obj = undefined;
if (some_data) str = some_data;
else str = "default";
if (some_obj1) obj = some_obj1;
else if (some_obj2) obj = some_obj2;
else obj = {};
examples of values yield by the logical OR operator:
1 || 3 -> 1
0 || 3 -> 3
undefined || 3 -> 3
NaN || 3 -> 3
"" || "default" -> "default"
undefined || undefined -> undefined
false || true -> true
true || false -> true
null || "test" -> "test"
undefined || {} -> {}
{} || true -> {}
null || false || {} -> {}
0 || "!!" || 9 -> "!!"
As you can see, if no match is found the value of the last operand is yield.
When is this useful?
There are several cases, though the most popular one is to set the default value of function arguments, as in the below:
function do_something (some_value) {
some_value = some_value || "hello world";
console.log ("saying: " + some_value);
}
...
do_something ("how ya doin'?");
do_something ();
saying: how ya doin'?
saying: hello world
Notes
This is notably one of the differences that javascript have compared to many other popular programming languages.
The operator || doesn't implicitly yield a boolean value but it keeps the operand types and yield the first one that will evaluate to true in a boolean expression.
Many programmers coming from languages where this isn't the case (C, C++, PHP, Python, etc, etc) find this rather confusing at first, and of course there is always the opposite; people coming from javascript (perl, etc) wonders why this feature isn't implemented elsewhere.
Yes. The sample is equivalent to this:
if (options) {
options = options;
} else {
options = {};
}
The OR operator (||) will short-circuit and return the first truthy value.
Yes, that's exactly what it does.
Found another variation of this:
options || (options = {});
Seems to do the same trick.

Categories

Resources