Do we have a simpler ternary operator in JavaScript? [duplicate] - javascript

This question already has answers here:
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Closed 5 years ago.
I just saw this syntax in PHP:
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
Why don't we have the same in JavaScript?
I am tired of doing:
var name = obj['name'] ? obj['name'] : 'GOD';

The Null coalescing operator is a recent addition to PHP. It was introduced in PHP 7 (released in December 2015), more than 10 years after the feature was proposed for the first time.
In Javascript, the logical OR operator can be used for this purpose for ages (since Javascript was created?!).
As the documentation explains:
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; if both are false, returns false.
Instead of writing
var name = obj['name'] ? obj['name'] : 'GOD';
you can use the shorter:
var name = obj['name'] || 'GOD';
The || operator can be used several times to create a longer expression that evaluates to the value of the first operand that is not empty:
var name = obj['name'] || obj['desc'] || 'GOD';

In javascript you can do the following:
var name = obj['name'] || "GOD"
If the first value is false (null, false, 0, NaN, "" or undefined), then the second value is going to be assigned.

Related

returning the higher value in logical operators in javascript [duplicate]

This question already has answers here:
Logical operators in JavaScript — how do you use them?
(2 answers)
Javascript AND operator within assignment
(7 answers)
Closed 1 year ago.
I am practising the logical operators in JavaScript and fully understood the concepts, but It seems that I didn't with this equation.
const one = 1;
const two = 5;
console.log(one && two);
Why in this case it returns five and not one, shouldn't be returned the first value since both are true ?
From MDN on the && operator:
"If expr1 can be converted to true, returns expr2; else, returns
expr1."
So in this case, 1 can be converted to true, so it returns the second value, 5.
The LOGICAL && operator returns the last value if all other values are true, or else it will return the first non truthy value.
i.e. Java != JavaScript

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.

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.

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.

What does || mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this construct mean?
I'm encountering this syntax for the first time and am not sure what it's doing:
self.name = _searchString(settings.dataBrowser) || "An unknown browser";
What does the or (double pipes) condition do? When would self.name be set to the second value?
This is the logical or operator.
It evaluates to its first "truthy" operand.
In particular, it will evaluate to the second operand if the first operand is "falsy" — null, false, undefined, 0, "", or NaN.
Crockford calls / called it a default operator
this is directly related to a question i have asked, you can read about it here
Short-circuit evaluation via the AND operator in PHP
so basically, it sets self.name to the value returned from the function, but if the function returns false, it sets itself to "An unknown browser";

Categories

Resources