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.
Related
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.)
I am looking at these lines of code from here:
if (callback)
callback(sig || graph);
I have never see vertical "or" bars in a javascript method call. What do they mean? Do they pass the "true" parameter (i.e. sig or graph)? Do they pass the defined parameter? I have never seen that syntax before.
This is the logical OR operator in JS (and most other languages). It is defined in the spec at 11.11. As noted in the spec, expressions on either side will be evaluated first and the logical OR is left-to-right associative. Note that evaluation of the operands follows standard ToBoolean semantics from section 9.2, so [null, undefined, 0, ''] all count as falsy.
Unlike most languages, JS returns the left operand if it is truthy or the right operand otherwise. This behavior has been covered before in a number of SO questions, but is worth noting as most languages simply return true or false. This behavior is often used to provide default values to otherwise undefined variables.
The Logical OR operator (||) is an operator that returns its first or second operand depending on whether the first is truthy. A "truthy" value means anything other than 0, undefined, null, "", or false.
This operator uses short-circuiting, meaning if the first expression is truthy, then the second expression is not evaluated and the first operand is returned immediately. This is akin to the Logical AND operator (&&), which does the opposite: if the first operand is falsey, it returns it, otherwise it returns the second expression.
It means 'or' (http://www.w3schools.com/js/js_comparisons.asp) So if(sig OR graph)
BE CAREFUL you can 'short circuit' your code using this.
example :
If (foo || foo2)
if foo is true, then JavaScript wont even test foo2 at all, it just skips it.
It passes whichever evaluates as true, or sig if both are true.
The double pipe (||) represents OR in JS. In simple words, either this or that is True. It requires any of the sides true to get a True result.
For example:
var x = 8;
var y = 'c';
x >= 8 || y === 'a'
The left side of the double pipe returns True where the right side is False. Thus, the result is True.
The operator || means OR.
If either sig or graph are true or not null variables, callback function will receive a true argument.
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
I came across the following and was unable to grasp the reason, can anyone explain please?
var foo = [0];
console.log(foo == !foo); // true
console.log(foo == foo); // true
The second comparison is simple to explain: foo is equal to itself.
The first one, however, is a bit tricky: foo is an array, which is an object, which evaluates to true when coerced to boolean. So !foo is false. But foo on the left side of the comparison is not being converted to boolean. Both operands are actually converted to numbers during the equality comparison. This is how it evaluates:
[0] == false
[0] == 0
"0" == 0
0 == 0
true
According to MDN, on comparisons with the equality operator ==:
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible
I know this explanation sounds superficial. It's actually much more complicated than that, but the basic steps are the ones I listed above. You can see the details on the ECMA-262 specification, particularly on sections 9 and 11.9.
You should use "===" and "!==" instead of "==" and "!="
More explanations there:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
http://net.tutsplus.com/tutorials/javascript-ajax/the-10-javascript-mistakes-youre-making/
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Javascript === vs ==
What's the diff between "===" and "==" ? Thanks!
'===' means equality without type coersion. In other words, if using the triple equals, the values must be equal in type as well.
e.g.
0==false // true
0===false // false, because they are of a different type
1=="1" // true, auto type coersion
1==="1" // false, because they are of a different type
Source: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
Ripped from my blog: keithdonegan.com
The Equality Operator (==)
The equality operator (==) checks whether two operands are the same and returns true if they are the same and false if they are different.
The Identity Operator (===)
The identity operator checks whether two operands are “identical”.
These rules determine whether two values are identical:
They have to have the same type.
If number values have the same value they are identical, unless one or both are NaN.
If string values have the same value they are identical, unless the strings differ in length or content.
If both values refer to the same object, array or function they are identical.
If both values are null or undefined they are identical.
The === operator means "is exactly equal to," matching by both value and data type.
The == operator means "is equal to," matching by value only.
It tests exact equality of both value and type.
given the assignment
x = 7
x===7 is true
x==="7" is false
In a nutshell "===" tests for the equality of value AND of type:
From here: