javascript ternary statement equivilance [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: Is “z=(x||y)” same as “z=x?x:y” for non-boolean?
Are the following two lines of code equivalent in javascript?
a = b ? b : c
a = b || c
I want to express: "a should be assigned b if b is truthy, otherwise a should be assigned c"
I expect they would both work exactly the same, but I'm not 100% sure.

Yes. The two are almost exactly identical.
Both will first evaluate b. If it's truthy, it'll return b. Else, it'll return c.
As pointed out by #thesystem, if you have a getter method on b, it'll be called twice for the ternary, but only once for the or statement.
Test it using the following snippet:
var o = {};
o.__defineGetter__("b", function() {
console.log('ran');
return true;
});
var d = o.b || o.not;
console.log('-----');
var d = o.b ? o.b : o.not;
Here's the fiddle: http://jsfiddle.net/bqsey/

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 may
return a non-Boolean value.
ref: Logical Operators - MDN

Related

Javascript - succinct way to assign another value to variable if first value is not truthy [duplicate]

This question already has answers here:
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Closed 4 years ago.
I have a function that may return a value or may return null and I want to assign it to a variable. So at the moment I've got
someVar = (someFun())
? someFun()
: "foo";
Is there a shorterer way of doing it, where I don't have to call the function twice, or add an extra variable like:
funResult = someFun();
someVar = (funResult)
? funResult
: "foo";
Basically, something like:
someVar = someFun() | "foo"
The idiomatic way is
someVar = someFun() || "foo";
The || operator will yield the value of the left-hand expression if it's truthy. If not, it will move on to evaluate the right-hand side, and return its value.
For those unfamiliar with the term "truthy", in JavaScript it means values that are not considered by the language to be implicitly false. The implicitly false values are 0, NaN, false (of course), "", null, and undefined. Any reference to an object, even if it's completely empty, is considered to be "truthy".
In your specific example, the || approach is to be preferred because it means you only call someFun() once.

if a=2 and b=3 then how a && b = 3 rather than true? [duplicate]

This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Closed 5 years ago.
There is one interview question below.
The logical AND of two truths should be true. But the output is 3. Why?
var a = 2;
var b = 3;
var c = a && b; // value of c = 3
console.log(c);
Check this out.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
If you use && with non-boolean values, it returns the first element if it can be converted to false. If it cannot converted to false, it returns second element
Returns a if it can be converted to false; otherwise, returns b.

var w = q||q2; what does this expression means? [duplicate]

This question already has answers here:
JavaScript || or operator with an undefined variable
(6 answers)
Closed 7 years ago.
what does this means?
var q = [];
var q2 = ["canada","usa","mexico"];
var w = q||q2;
document.writeln(w);
the value of the variable w is : [] the empty list.
can someone explain to me why it is displaying this [] instead of ["canada","usa","mexico"].
You should read Logical Operators from MDN. According to the documentation
The logical operator 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; if both are false, returns false.
In a nutshell, logical operators evaluate from left to right. In your situation, since you have declare q as an empty array ([]), it evaluates to true and immediately goes and assigns w to that.
If you want q2 to take precedence, you can simply do
var w = q2 || q;
so that way only if q2 evaluates to falsey will it assign w to be q instead. The other option is to not declare q at all or declare it as something falsey. You can find out what evaluates to false here.

Why does `(state == 1 && 3)` make sense? [duplicate]

This question already has answers here:
Why the result of bool(true) && string is string in javascript?
(4 answers)
Closed 8 years ago.
I came across this code in Mithril.js:
finish(state == 1 && 3)
To my (Java/C programmer's) eyes it looks like it should always invoke finish(true) if state is 1 and finish(false) if state is not 1. But it actually seems to do finish(3) for the former and finish(false) for the latter.
What is the logic behind this?
Is this idiomatic in JavaScript, or is it a bad idea? To me it's horribly obscure.
You can interpret the operators || and && like this:
A || B
→ A ? A : B
A && B
→ A ? B : A
But without evaluating A twice.
It is a characteristic of JavaScript, && and || operators always return the last value it evaluated.
In JavaScript, the && operator doesn't force the result to a boolean. It's instead similar to:
var _temp = state == 1;
finish(_temp ? 3 : _temp);
Testing the truthiness of the left side, then returning either the right when truthy or the left otherwise.
The comparison a && b actually returns the value the last value evaluated in the expression and not true or false.
You can refer to the spec:
The production LogicalANDExpression : LogicalANDExpression &&
BitwiseORExpression is evaluated as follows:
Let lref be the result of evaluating LogicalANDExpression.
Let lval be GetValue(lref).
If ToBoolean(lval) is false, return lval.
Let rref be the result of evaluating BitwiseORExpression.
Return GetValue(rref).

What is the purpose of using !! in JavaScript? [duplicate]

This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 9 years ago.
I want to know the purpose of using !! in JS.
For ex:
this.enabled = function (value) {
if (arguments.length) {
enabled = !!value;
}
}
It's not related to angular
It's just a way to transform value to bool. ( according to truthy/falsy values)
There is a lot of articles about it.
examples :
!!"a" //true
!!"0" //true
!!0 //false
To be clear, this question has nothing to do with AngularJS--it is a JS syntax question.
The purpose of !! in JavaScript (and other langs) is to force a value to boolean.
Using a single ! forces it to boolean, but opposite of whether the value was "truthy" or "falsy". The second ! flips it back to be a boolean which matches the original "truthy" or "falsy" evaluation.
var a = 'a string';
var f = !a; // f is now boolean false because a was "truthy:
var t = !!a; // f is now boolean true because a was "truthy:
It's not specific to Angular, it serves to transform a non-boolean value like undefined to boolean.

Categories

Resources