Best replacement for var x = y || false - javascript

A codebase I'm working on contains many uses of the javascript 'default operator' such as:
var x = y || false;
I'm wondering what the best possible replacement to use in order to guarantee that the value is never undefined, null, etc. Should I replace them with "false" and check against the string? Should I replace them with their longhand counterpart (explicit checks for null and undefined)? Or does each use case need to be evaluated for something I'm not taking into account?

To set a non-falsy default when your input could be a valid falsy value, one way is to do two tests
if (!x && x !== 0) {
x = 1; // 1 is the default value but 0 is a valid input
}
The advantage of doing it like this is you can exclude non-valid falsy values, e.g. NaN
This said, you may be better off casting or type checking
if (typeof x !== 'number') x = 1;
or
x = +x;
if (x !== x) x = 1; // NaN goes to default

Related

In Javascript why, console.log(0 && 0 === 0); returns 0 instead of true? [duplicate]

Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
I want to understand why it returns result of obj.fn() (if it is defined) OR obj._ but not boolean result.
In JavaScript, both || and && are logical short-circuit operators that return the first fully-determined “logical value” when evaluated from left to right.
In expression X || Y, X is first evaluated, and interpreted as a boolean value. If this boolean value is “true”, then it is returned. And Y is not evaluated. (Because it doesn’t matter whether Y is true or Y is false, X || Y has been fully determined.) That is the short-circuit part.
If this boolean value is “false”, then we still don’t know if X || Y is true or false until we evaluate Y, and interpret it as a boolean value as well. So then Y gets returned.
And && does the same, except it stops evaluating if the first argument is false.
The first tricky part is that when an expression is evaluated as “true”, then the expression itself is returned. Which counts as "true" in logical expressions, but you can also use it. So this is why you are seeing actual values being returned.
The second tricky part is that when an expression is evaluated as “false”, then in JS 1.0 and 1.1 the system would return a boolean value of “false”; whereas in JS 1.2 on it returns the actual value of the expression.
In JS false, 0, -0, "", null, undefined, NaN and document.all all count as false.
Here I am of course quoting logical values for discussion’s sake. Of course, the literal string "false" is not the same as the value false, and is therefore true.
In the simplest terms:
The || operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).
The && operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).
It's really that simple. Experiment in your console to see for yourself.
console.log("" && "Dog"); // ""
console.log("Cat" && "Dog"); // "Dog"
console.log("" || "Dog"); // "Dog"
console.log("Cat" || "Dog"); // "Cat"
var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false
will return boolean.
UPDATE
Note that this is based on my testing. I am not to be fully relied upon.
It is an expression that does not assign true or false value. Rather it assigns the calculated value.
Let's have a look at this expression.
An example expression:
var a = 1 || 2;
// a = 1
// it's because a will take the value (which is not null) from left
var a = 0 || 2;
// so for this a=2; //its because the closest is 2 (which is not null)
var a = 0 || 2 || 1; //here also a = 2;
Your expression:
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
// _ = closest of the expression which is not null
// in your case it must be (obj.fn && obj.fn())
// so you are gettig this
Another expression:
var a = 1 && 2;
// a = 2
var a = 1 && 2 && 3;
// a = 3 //for && operator it will take the fartest value
// as long as every expression is true
var a = 0 && 2 && 3;
// a = 0
Another expression:
var _ = obj && obj._;
// _ = obj._
In most programming languages, the && and || operators returns boolean. In JavaScript it's different.
OR Operator:
It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).
Example 1:
var a = 0 || 1 || 2 || 3;
^ ^ ^ ^
f t t t
^
first operand that validates as true
so, a = 1
Example 2:
var a = 0 || false || null || '';
^ ^ ^ ^
f f f f
^
no operand validates as true,
so, a = ''
AND Operator:
It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.
Example 1:
var a = 1 && 2 && 3 && 4;
^ ^ ^ ^
t t t t
^
last operand that validates as true
so, a = 4
Example 2:
var a = 2 && '' && 3 && null;
^ ^ ^ ^
t f t f
^
return first operand that validates as false,
so, a = ''
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use Boolean() function, like this:
var a = Boolean(1 || 2 || 3);// a = true
You should think of the short-circuit operators as conditionals rather than logical operators.
x || y roughly corresponds to:
if ( x ) { return x; } else { return y; }
and x && y roughly corresponds to:
if ( x ) { return y; } else { return x; }
Given this, the result is perfectly understandable.
From MDN documentation:
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.
And here's the table with the returned values of all logical operators.
I think you have basic JavaScript methodology question here.
Now, JavaScript is a loosely typed language. As such, the way and manner in which it treats logical operations differs from that of other standard languages like Java and C++. JavaScript uses a concept known as "type coercion" to determine the value of a logical operation and always returns the value of the first true type. For instance, take a look at the code below:
var x = mystuff || document;
// after execution of the line above, x = document
This is because mystuff is an a priori undefined entity which will always evaluate to false when tested and as such, JavaScript skips this and tests the next entity for a true value. Since the document object is known to JavaScript, it returns a true value and JavaScript returns this object.
If you wanted a boolean value returned to you, you would have to pass your logical condition statement to a function like so:
var condition1 = mystuff || document;
function returnBool(cond){
if(typeof(cond) != 'boolean'){ //the condition type will return 'object' in this case
return new Boolean(cond).valueOf();
}else{ return; }
}
// Then we test...
var condition2 = returnBool(condition1);
window.console.log(typeof(condition2)); // outputs 'boolean'
We can refer to the spec(11.11) of JS here of:
Semantics
The production LogicalANDExpression :LogicalANDExpression &&BitwiseORExpression is evaluated as follows:
Evaluate LogicalANDExpression.
2.Call GetValue(Result(1)).
3.Call ToBoolean(Result(2)).
4.If Result(3) is false, return Result(2).
5.Evaluate BitwiseORExpression.
6.Call GetValue(Result(5)).
7.Return Result(6).
see here for the spec
First, it has to be true to return, so if you are testing for truthfulness then it makes no difference
Second, it lets you do assignments along the lines of:
function bar(foo) {
foo = foo || "default value";
Compare:
var prop;
if (obj.value) {prop=obj.value;}
else prop=0;
with:
var prop=obj.value||0;
Returning a truthy expression - rather than just true or false - usually makes your code shorter and still readable. This is very common for ||, not so much for &&.

JavaScript - OR Operation with two false values [duplicate]

Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
I want to understand why it returns result of obj.fn() (if it is defined) OR obj._ but not boolean result.
In JavaScript, both || and && are logical short-circuit operators that return the first fully-determined “logical value” when evaluated from left to right.
In expression X || Y, X is first evaluated, and interpreted as a boolean value. If this boolean value is “true”, then it is returned. And Y is not evaluated. (Because it doesn’t matter whether Y is true or Y is false, X || Y has been fully determined.) That is the short-circuit part.
If this boolean value is “false”, then we still don’t know if X || Y is true or false until we evaluate Y, and interpret it as a boolean value as well. So then Y gets returned.
And && does the same, except it stops evaluating if the first argument is false.
The first tricky part is that when an expression is evaluated as “true”, then the expression itself is returned. Which counts as "true" in logical expressions, but you can also use it. So this is why you are seeing actual values being returned.
The second tricky part is that when an expression is evaluated as “false”, then in JS 1.0 and 1.1 the system would return a boolean value of “false”; whereas in JS 1.2 on it returns the actual value of the expression.
In JS false, 0, -0, "", null, undefined, NaN and document.all all count as false.
Here I am of course quoting logical values for discussion’s sake. Of course, the literal string "false" is not the same as the value false, and is therefore true.
In the simplest terms:
The || operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).
The && operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).
It's really that simple. Experiment in your console to see for yourself.
console.log("" && "Dog"); // ""
console.log("Cat" && "Dog"); // "Dog"
console.log("" || "Dog"); // "Dog"
console.log("Cat" || "Dog"); // "Cat"
var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false
will return boolean.
UPDATE
Note that this is based on my testing. I am not to be fully relied upon.
It is an expression that does not assign true or false value. Rather it assigns the calculated value.
Let's have a look at this expression.
An example expression:
var a = 1 || 2;
// a = 1
// it's because a will take the value (which is not null) from left
var a = 0 || 2;
// so for this a=2; //its because the closest is 2 (which is not null)
var a = 0 || 2 || 1; //here also a = 2;
Your expression:
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
// _ = closest of the expression which is not null
// in your case it must be (obj.fn && obj.fn())
// so you are gettig this
Another expression:
var a = 1 && 2;
// a = 2
var a = 1 && 2 && 3;
// a = 3 //for && operator it will take the fartest value
// as long as every expression is true
var a = 0 && 2 && 3;
// a = 0
Another expression:
var _ = obj && obj._;
// _ = obj._
In most programming languages, the && and || operators returns boolean. In JavaScript it's different.
OR Operator:
It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).
Example 1:
var a = 0 || 1 || 2 || 3;
^ ^ ^ ^
f t t t
^
first operand that validates as true
so, a = 1
Example 2:
var a = 0 || false || null || '';
^ ^ ^ ^
f f f f
^
no operand validates as true,
so, a = ''
AND Operator:
It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.
Example 1:
var a = 1 && 2 && 3 && 4;
^ ^ ^ ^
t t t t
^
last operand that validates as true
so, a = 4
Example 2:
var a = 2 && '' && 3 && null;
^ ^ ^ ^
t f t f
^
return first operand that validates as false,
so, a = ''
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use Boolean() function, like this:
var a = Boolean(1 || 2 || 3);// a = true
You should think of the short-circuit operators as conditionals rather than logical operators.
x || y roughly corresponds to:
if ( x ) { return x; } else { return y; }
and x && y roughly corresponds to:
if ( x ) { return y; } else { return x; }
Given this, the result is perfectly understandable.
From MDN documentation:
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.
And here's the table with the returned values of all logical operators.
I think you have basic JavaScript methodology question here.
Now, JavaScript is a loosely typed language. As such, the way and manner in which it treats logical operations differs from that of other standard languages like Java and C++. JavaScript uses a concept known as "type coercion" to determine the value of a logical operation and always returns the value of the first true type. For instance, take a look at the code below:
var x = mystuff || document;
// after execution of the line above, x = document
This is because mystuff is an a priori undefined entity which will always evaluate to false when tested and as such, JavaScript skips this and tests the next entity for a true value. Since the document object is known to JavaScript, it returns a true value and JavaScript returns this object.
If you wanted a boolean value returned to you, you would have to pass your logical condition statement to a function like so:
var condition1 = mystuff || document;
function returnBool(cond){
if(typeof(cond) != 'boolean'){ //the condition type will return 'object' in this case
return new Boolean(cond).valueOf();
}else{ return; }
}
// Then we test...
var condition2 = returnBool(condition1);
window.console.log(typeof(condition2)); // outputs 'boolean'
We can refer to the spec(11.11) of JS here of:
Semantics
The production LogicalANDExpression :LogicalANDExpression &&BitwiseORExpression is evaluated as follows:
Evaluate LogicalANDExpression.
2.Call GetValue(Result(1)).
3.Call ToBoolean(Result(2)).
4.If Result(3) is false, return Result(2).
5.Evaluate BitwiseORExpression.
6.Call GetValue(Result(5)).
7.Return Result(6).
see here for the spec
First, it has to be true to return, so if you are testing for truthfulness then it makes no difference
Second, it lets you do assignments along the lines of:
function bar(foo) {
foo = foo || "default value";
Compare:
var prop;
if (obj.value) {prop=obj.value;}
else prop=0;
with:
var prop=obj.value||0;
Returning a truthy expression - rather than just true or false - usually makes your code shorter and still readable. This is very common for ||, not so much for &&.

Null and Booleans operator

I'm really new at programming and although I understand the concepts I have some trouble putting them in practice. For example I understood the concept of null and undefined values... and booleans operators.. all good!!! but when it comes to simple exercise I get stuck.
For example I got this :
Write an expression that evaluates x, so long as x is not null; if x is null, the expression should evaluate to 100. x is equal to null when no value has been assigned to it (e.g. var x;), but you could also assign it the value of null (var x = null;). Test your expression for several different values of x, including null - does it behave like you expect?
This is what I did:
var x ;
myExpression = (x - 50 + 20 + 30);
if (x === null) {
myExpression === true;
}
else if (x !== null) {
myExpression === 50;
}
It doesn't look right to me at all , and I know it's not. I think my real problem is understanding the problem itself. Can you please try to help me understanding it?
Thank you very much!
You are making this too hard. The expression:
((x == null) ? 100 : x)
A sample use:
y = ((x == null) ? 100 : x);
Your assignment said:
Write an expression that evaluates x, so long as x is not null; if x is null, the expression should evaluate to 100.
An expression is something which evaluates to a value. The number 6 is an expression. A variable, like x is an expression. More complicated expressions can be built using mathematical operators, for example 6 + x and so on.
The ternary (or "question mark") operator is a very powerful tool for building expressions.
condition ? value1 : value2
this works like something like a "mini-function":
function questionmark ( condition ) {
if ((condition) != 0) {
return value1;
} else {
return value2;
}
}
So:
(x == null) ? 100 : x
evaluates to 100 if x is null and the value of x otherwise.
Think of this expression as using 100 as the default value for something -- for example, we are going to do something x times, but if they haven't told us x we'll do it 100 times.
You should see that
(x != null) ? x : 100
is an equivalent expression.
In JavaScript there are more compact ("trickier") ways to write this kind of expression. I include them here just so you might recognize them if you see them in code:
(x ? x : 100)
(x || 100)

What is this JS syntax? Assignment in expression? (x != null && (y = x))

I'm working with this JS plugin, and I've encountered some syntax I've never seen before. I understand what it's doing, but I'm not sure why it works.
Here's an example of one instance of it:
settings.maxId != null && (params.max_id = settings.maxId);
Is this just taking advantage of conditionals and the single = ? Is this common syntax for JS?
In JavaScript the = operator is an expression and evaluates the assigned value. Because it is an expression it can be used anywhere an expression is allowed even though it causes a side-effect.
Thus:
settings.maxId != null && (params.max_id = settings.maxId)
Means: If settings.maxId is not null then (and only then, since && is short circuiting) evaluate the right-expression (params.max_id = settings.maxId) which in turn causes the value of settings.maxId to be assigned to params.max_id.
This is much more clearly written as:
if (settings.maxId != null) {
params.max_id = settings.maxId
}
Happy coding.
The && operator is known as "boolean AND". Typically, you'd see it in an if statement:
if (x == true && y == false) {
but that's not a restriction. You may use it in any valid expression to "combine" the boolean values of its operands into a single boolean result, according to the logical "AND" operation:
var z = (x == true && y == false);
// z is now true or false, accordingly
One of the lovely things about && is that it "short circuits". In false && true, because the first operand is false the entire expression may only evaluate to false, so the second operand is not even evaluated.
Let's check that again:
var z = (false && foo());
// z is now false
In this statement, the function foo is never even called! It doesn't have to be, for the program to know that z will be false.
This is more than an optimisation — you can rely on it.
Some silly people use this technique to rewrite conditional statements:
if (x == 0) {
foo();
}
into hard-to-read single expressions:
(x == 0) && foo();
Now, consider that assignment can be an expression just like a function call:
var a = (b = c);
Or:
var a = (b = foo());
And add in a conditional via the above technique:
var a = ((x == 0) && (b = foo()));
Now the entire expression b = foo() won't be evaluated at all if x is not 0, because of short circuiting.
We don't even need to do anything with the result of the && operation, and if we don't store it to a you're left with just:
(x == 0) && (b = foo());
which is a statement that'll assign b to the value of foo() only if x is 0.
Avoid it. It's hard to read. Just use an if statement.
this statement will assign params.max_id = settings.maxId only if settings.maxId != null due to the fact that && is a short-circuit logic operator
this behaviour is due to the fact that javascript will evaluate the condition until it's necessary. thus, if first condition is false and the second is in AND there's no need to check further

Why don't logical operators (&& and ||) always return a boolean result?

Why do these logical operators return an object and not a boolean?
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
var _ = obj && obj._;
I want to understand why it returns result of obj.fn() (if it is defined) OR obj._ but not boolean result.
In JavaScript, both || and && are logical short-circuit operators that return the first fully-determined “logical value” when evaluated from left to right.
In expression X || Y, X is first evaluated, and interpreted as a boolean value. If this boolean value is “true”, then it is returned. And Y is not evaluated. (Because it doesn’t matter whether Y is true or Y is false, X || Y has been fully determined.) That is the short-circuit part.
If this boolean value is “false”, then we still don’t know if X || Y is true or false until we evaluate Y, and interpret it as a boolean value as well. So then Y gets returned.
And && does the same, except it stops evaluating if the first argument is false.
The first tricky part is that when an expression is evaluated as “true”, then the expression itself is returned. Which counts as "true" in logical expressions, but you can also use it. So this is why you are seeing actual values being returned.
The second tricky part is that when an expression is evaluated as “false”, then in JS 1.0 and 1.1 the system would return a boolean value of “false”; whereas in JS 1.2 on it returns the actual value of the expression.
In JS false, 0, -0, "", null, undefined, NaN and document.all all count as false.
Here I am of course quoting logical values for discussion’s sake. Of course, the literal string "false" is not the same as the value false, and is therefore true.
In the simplest terms:
The || operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).
The && operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).
It's really that simple. Experiment in your console to see for yourself.
console.log("" && "Dog"); // ""
console.log("Cat" && "Dog"); // "Dog"
console.log("" || "Dog"); // "Dog"
console.log("Cat" || "Dog"); // "Cat"
var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false
will return boolean.
UPDATE
Note that this is based on my testing. I am not to be fully relied upon.
It is an expression that does not assign true or false value. Rather it assigns the calculated value.
Let's have a look at this expression.
An example expression:
var a = 1 || 2;
// a = 1
// it's because a will take the value (which is not null) from left
var a = 0 || 2;
// so for this a=2; //its because the closest is 2 (which is not null)
var a = 0 || 2 || 1; //here also a = 2;
Your expression:
var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
// _ = closest of the expression which is not null
// in your case it must be (obj.fn && obj.fn())
// so you are gettig this
Another expression:
var a = 1 && 2;
// a = 2
var a = 1 && 2 && 3;
// a = 3 //for && operator it will take the fartest value
// as long as every expression is true
var a = 0 && 2 && 3;
// a = 0
Another expression:
var _ = obj && obj._;
// _ = obj._
In most programming languages, the && and || operators returns boolean. In JavaScript it's different.
OR Operator:
It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).
Example 1:
var a = 0 || 1 || 2 || 3;
^ ^ ^ ^
f t t t
^
first operand that validates as true
so, a = 1
Example 2:
var a = 0 || false || null || '';
^ ^ ^ ^
f f f f
^
no operand validates as true,
so, a = ''
AND Operator:
It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.
Example 1:
var a = 1 && 2 && 3 && 4;
^ ^ ^ ^
t t t t
^
last operand that validates as true
so, a = 4
Example 2:
var a = 2 && '' && 3 && null;
^ ^ ^ ^
t f t f
^
return first operand that validates as false,
so, a = ''
Conclusion:
If you want JavaScript to act the same way how other programming languages work, use Boolean() function, like this:
var a = Boolean(1 || 2 || 3);// a = true
You should think of the short-circuit operators as conditionals rather than logical operators.
x || y roughly corresponds to:
if ( x ) { return x; } else { return y; }
and x && y roughly corresponds to:
if ( x ) { return y; } else { return x; }
Given this, the result is perfectly understandable.
From MDN documentation:
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.
And here's the table with the returned values of all logical operators.
I think you have basic JavaScript methodology question here.
Now, JavaScript is a loosely typed language. As such, the way and manner in which it treats logical operations differs from that of other standard languages like Java and C++. JavaScript uses a concept known as "type coercion" to determine the value of a logical operation and always returns the value of the first true type. For instance, take a look at the code below:
var x = mystuff || document;
// after execution of the line above, x = document
This is because mystuff is an a priori undefined entity which will always evaluate to false when tested and as such, JavaScript skips this and tests the next entity for a true value. Since the document object is known to JavaScript, it returns a true value and JavaScript returns this object.
If you wanted a boolean value returned to you, you would have to pass your logical condition statement to a function like so:
var condition1 = mystuff || document;
function returnBool(cond){
if(typeof(cond) != 'boolean'){ //the condition type will return 'object' in this case
return new Boolean(cond).valueOf();
}else{ return; }
}
// Then we test...
var condition2 = returnBool(condition1);
window.console.log(typeof(condition2)); // outputs 'boolean'
We can refer to the spec(11.11) of JS here of:
Semantics
The production LogicalANDExpression :LogicalANDExpression &&BitwiseORExpression is evaluated as follows:
Evaluate LogicalANDExpression.
2.Call GetValue(Result(1)).
3.Call ToBoolean(Result(2)).
4.If Result(3) is false, return Result(2).
5.Evaluate BitwiseORExpression.
6.Call GetValue(Result(5)).
7.Return Result(6).
see here for the spec
First, it has to be true to return, so if you are testing for truthfulness then it makes no difference
Second, it lets you do assignments along the lines of:
function bar(foo) {
foo = foo || "default value";
Compare:
var prop;
if (obj.value) {prop=obj.value;}
else prop=0;
with:
var prop=obj.value||0;
Returning a truthy expression - rather than just true or false - usually makes your code shorter and still readable. This is very common for ||, not so much for &&.

Categories