This question already has answers here:
Nullish Coalescing operator in JavaScript
(5 answers)
Closed 4 years ago.
Easy question. Does exist something like php's ?? in javascript?
In php you can do condition ?? statement2
which is the same as condition? condition : statement2.
Is there something like that in javascript?
I would use the logical or operator (||)
console.log("true value" || "other")
console.log(false || "other")
This works because (source):
expr1 || expr2 Returns expr1 if it can be converted to true; otherwise, returns expr2
So, if condition is false, go with statement2.
That's as simple as condition || statement2
If condition is truthy, if will be selected. If not, statement2 will be evaluated.
Related
This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
(22 answers)
How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?
(1 answer)
Closed last year.
i have code like below,
const output = (data?.item?.someItem?.count ?? 0) === 0;
what is the value of output in this case what does ?? in above line mean. could someone help me understand this line of code.
I am new to programming. thanks.
The "optional chaining operator" ?. gets a property of an object, if that exists and the "nullish coalescing operator" ?? acts very similar to the || operator: It returns the first operand if it is NOT null or undefined , otherwise it returns the second one.
The || behaves slightly differently: It will return the seond operand if the first operand is "falsey" (i. e. 0 or false will also trigger the second operand to be returned).
You can find more details here: MDM Web Docs - Operators
First, as already pointed out, this isn't specific to React, but plain JavaScript syntax.
Let's break it down.
Optional Chaining ?.
const result1 = data?.item?.someItem?.count
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
So even if data, item or someItem is undefined or null, you could still use this statement without generating an error, but you would simply get an undefined value.
Read more about it in the docs here.
Nullish coalescing operator (??)
const result2 = result1 ?? 0
As described in the docs:
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
In your case, the expression will return 0 if element is null or undefined, otherwise it returns element.
Final output: Strict Equality Comparison
const output = result2 === 0
The expression evaluates to true if result2 is strictly equal to the numeric value 0. Also read the docs here.
This question already has answers here:
what does && return in javascript expression
(4 answers)
Closed 3 years ago.
> "s" && true;
true
> true && "s";
's'
I thought these two expressions would return same values.
Why not? How does it work?
See MDN:
expr1 && expr2: If expr1 can be converted to true, returns expr2; else, returns expr1.
&& evaluates to the value of the last truthy expression, so if both operands are truthy, the whole thing will evaluate to the first operand.
If the first operand is falsey, it'll evaluate to the (falsey) value of the first operand.
Similar to ||, you can think of it as evaluating to the value of the expression that determines the final value. (If evaluating the left operand provides a truthy result with ||, there's no need to evaluate the right - similarly, if the right operand produces a falsey result with &&, there's no need to evaluate the left.)
This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Logical AND (&&) and OR (||) operators
(1 answer)
Closed 6 years ago.
I have something like the following:
var val = "string";
var testVal = val && val.length;
I would expect testVal to be either true or false but it is the length of the string. Not sure why this is?
The logical && operator doesn't perform a type casting. The expression it forms is just evaluated to the left-hand operand if this operand is falsy, otherwise to the right-hand operand.
You have to explicitly convert to boolean:
var testVal = !!(val && val.length);
This question already has answers here:
Question mark and colon in JavaScript
(8 answers)
Closed 8 years ago.
So I used an online JavaScript optimizer and it did something strange to my IF statements that is new to me.
{1===a?window.addEventListener("scroll",turnOff):0===a&&window.removeEventListener("scroll",turnoff)}
What in the world is this? Help me to understand the parts of it please.
The three equal signs are a representation of strict comparison operators. Unlike the usual double equal signs, using === compares both the type and value of the expressions being compared. Both the type and value must be equal for the statement to evaluate to true.
The ? and : are shorthand versions of the if statement. When 1===a is true, the statement after the question mark is evaluated. Otherwise, the statement after the colon is evaluated. This shorthand version of the if statement is known as a Conditional (or Ternary) operator.
It is a Conditional (Ternary) operator.
You can read more about ternary operators at the developer Mozilla docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
It is structured like this:
condition ? code if true : code if false
The ? Operator is used just as an if.
if(a){
b;
} else {
c;
}
is equal to
a ? b : c;
It's called a ternary operator. It compares the condition
if a === 1
and returns the first result if the condition is true:
window.addEventListener("scroll",turnOff)
and the second if false:
0===a&&window.removeEventListener("scroll",turnoff)
This line of code does two things, sets a equal to 0 and removes an event listener.
See this tutorial
This question already has answers here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 9 years ago.
I found == is little confusing for newbies, So I want someone to explain how it works.
For example -
new String("a") == "a" and "a" == new String("a") are both true.
new String("a") == new String("a") is false.
Why?
== is called comparison/equality operator, it compares 2 values, but not their data types so for example
1 == '1' will return true, for stricter comparison, use === which will compare the data types too so 1 === '1' will return false
== is a comparison operator that means "equal to" but does not take variable typing into account.
=== is a stricter comparison operator that means "equal to and same type".
So if you have a string called numberStr with a value of 2 and an integer called numberInt with a value of 2, they will evaluate as follows:
numberStr == numberInt // evaluates to true
numberStr === numberInt // evaluates to false because types are different