This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
Closed 4 years ago.
I was looking through a code and I came across this:
{{abc?.xvy=== tyu?abc?.xz:abc?.xz}}
I am unable to understand meaning of this expression. I know that it is Null-safe property access but I am bit confused about the chaining.
Any help is much appreciated
This looks to be an example of the optional chaining proposal, which is still very much a work in progress (only at Stage 1). It's not actually implemented in vanilla JS environments yet. Using
obj?.prop
means: if obj is undefined or null, the expression evaluates to undefined. But otherwise, it will evaluate to the prop property on the object. This is syntax sugar for
obj && obj.prop
(using just obj.prop alone will throw if obj is undefined or null)
So, your
abc?.xvy=== tyu?abc?.xz:abc?.xz
will evaluate to true if the nested value abc?.xvy is equal to the nested value abc?.xz - or, it will evaluate to true if at least one of the nested values doesn't exist, and the other is undefined.
Spaced out for easier reading:
abc?.xvy === tyu
? abc?.xz
: abc?.xz
As you can see, both ? and : expressions are the same, making the conditional operator unnecessary here. An equivalent test (assuming that referencing tyu doesn't throw) would be
abc?.xvy === abc?.xz
Its new ES proposal called "optionals" for safe check reading for object properties. Above expression is equivalent to:
(abc && abc.xvy) === (tyu) ? (abc && abc.xz) : (abc && abc.xz)
You can find more details here: https://github.com/davidyaha/ecmascript-optionals-proposal
It's called Null Propagation Operator.
We can think of each ?. operator as a short circuit where "if the expression up until this point is null or undefined, then the whole expression evaluates to undefined".
We could also optionally call functions.
Related
This question already has answers here:
Safe navigation operator (?.) or (!.) and null property paths
(7 answers)
Replacement of Elvis Operator of Angular2 in Typescript
(3 answers)
Closed 4 years ago.
We have the Null coalescing operator in .NET and we can use as below
string postal_code = address?.postal_code;
Same thing can we do in React JS?
What i found like we can do with && operator
in address.ts file
string postal_code = address && address.postal_code;
what i need like .net feature is possible in typescript with react JS, is that possible ?
something like:
string postal_code = address?.postal_code // I am getting the error in this line if I try to use like .NET
This is a proposed feature in TypeScript, under the legendary Issue #16
It won't be introduced into TypeScript until the ECMAScript spec for this feature is firm as there is a desire for the TypeScript implementation to follow that specification - so you'll get it early, but not massively early in this case.
It is referred to as any of the following:
Null Propagation Operator
Existential Operator
Null Coalesce Operator
Update in 2020: The nullish-coalescing operator mentioned below is now through the process and in ES2020, as is the optional chaining operator that lets you do:
let postal_code = address?.postal_code;
// −−−−−−−−−−−−−−−−−−−−−−^
With optional chaining, if address is null or undefined, postal_code will get undefined as its value. But if address is neither null nor undefined, postal_code will get the value of address.postal_code.
JavaScript doesn't have a null-coalescing operator (nor does TypeScript, which mostly limits itself to adding a type layer and adopting features that are reasonably far along the path to making it into JavaScript). There is a proposal for a JavaScript null-coalescing operator, but it's only at Stage 1 of the process.
Using the && idiom you've described is a fairly common approach:
let postal_code = address && address.postal_code;
If address is null (or any other falsy¹ value), postal_code will be that same value; otherwise, it will be whatever value address.postal_code was.
¹ The falsy values are 0, "", NaN, null, undefined, and of course false.
This question already has answers here:
JavaScript checking for null vs. undefined and difference between == and ===
(8 answers)
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 7 years ago.
Very often we check our objects if they are not null and not undefined. I always use condition if (obj !== null && obj !== undefined). Few days ago my colleague shown me the syntax of double inversion !! and now I can use condition if (!!obj). This syntax is less.
I'm not a person who are only learning js, but I have a little interest.
So is there any difference between these two ways of object validation? Performance difference? Semantic difference? Any difference?
There isn’t any particularly good reason to ever use if (!!obj), as it’s equivalent to if (obj). !!obj and obj !== null && obj !== undefined do different things, though, and you should use whichever’s most appropriate.
obj !== null && obj !== undefined (surprise, surprise) results in false for null and undefined.
!!obj results in false for anything falsy, including null, undefined, '', 0, NaN, and false.
!!foo is used to force coerce a value into its Boolean value. This is, in my experience, often used in APIs that want to return a Boolean value for a value that contains sensitive data. For example, to return whether or not a password is entered you might say return !!password rather than return password.
Continuing on that, if (!!obj) is not the same as if (obj !== null && obj !== undefined) for many values you can think of! Such as false.
This question already has answers here:
user defined object equality for a set in harmony (es6)
(2 answers)
Closed 7 years ago.
A Set handles 2 empty objects as different, e.g.:
let s = new Set([ {} ]);
s.has({}); // false
This is expected, but it would be useful to compare based on their contents instead, as is possible in various other languages.
Is there any way to override the Set's internal comparison operator?
Is there any way to override the Set's internal comparison operator?
No. Set.prototype.has is defined like this:
23.2.3.7 - Set.prototype.has ( value )
The following steps are taken:
Let S be the this value.
If Type(S) is not Object, throw a TypeError exception.
If S does not have a [[SetData]] internal slot throw a TypeError exception.
Let entries be the List that is the value of S’s [[SetData]] internal slot.
Repeat for each e that is an element of entries,
If e is not empty and SameValueZero(e, value) is true, return true.
Return false.
Therefore, Set must compare using SameValueZero comparison, and you can't change that.
No, there isn't. The comparison used for Set instances is almost the same as the === operator, except that NaN can be put in a Set (once), meaning that NaN is treated as being === to itself for that purpose.
This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
What does the construct x = x || y mean?
(12 answers)
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 8 years ago.
I've never seen the OR paramater || used outside of an if statement.
What does this line of code do?
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document
Is it saying making it equal to either one of those???
A || B
evaluates A first. If it is true, A is returned, and B never needs to be looked at.
If A is false, B is evaluated and returned.
For example, if you write
function (x)
{ x = x || 50
...
This would make x=50, if x is nil (or some kind of false value).
Otherwise, x would not be changed.
It is like having a default value, or a failsafe protection. If you know that the answer should never be false, then if A is false, you provide a backup value of B.
A way to get a DOM reference to the iframe's window object is to use:
contentWindow.document
Now, cause IE<8 has problems with it, a small polyfill is to use
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document;
// Browser you get this one ^^^ ? NO? Sh** you're IE7, go with^^
So earlyer versions of IE will skip the contentWindow cause not recognized, and thanks to the || (or) operator will follow up with the next contentDocument.
I don't have to repeat what's the OR operator cause other smart people already explained it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This is just a short form of the ternary operator, which always returns a value depending to a statement. So, e. g.:
var fruit = "apple";
var test = fruit === "apple" ? fruit : "banana";
This sets the variable test to the value of fruit, when fruit is set to "apple". Otherwise, test will be initialized with "banana".
This question already has answers here:
What does "javascript:void(0)" mean?
(14 answers)
Closed 9 years ago.
Let's assume for a moment that you must create a JavaScript link that doesn't have a meaningful href. (I know that this practice is questionable.) In this case, why do so many people use...
My link
Knowing that void(0) evaluates to undefined, can I simply use the following logic?
My link
Why people use void(x) instead of undefined?
Well both would work but undefined is a reserved variable and its value can be changed:
undefined = true;
This will give true instead of undefined.
Where as void() is a keyword which always returns undefined. Whatever you place inside the keyword:
void('return false plox'); //will return false
More info on this topic here: What does `void 0` mean?
jsFiddle
Note that <a href="#"> is not the same as it still acts as a link and will redirect you, where as the previous methods will cancel the event(similar to event.preventDefault).
Update
Since ECMAScript 5, the global undefined variable is no longer directly editable (See for example Mozilla docs). It now simply shadows the global variable as some have noted.
There are three differences,
void evaluates the given expression and then returns the undefined
window.undefined is writable whereas void operator will always return undefined
void has fewer characters and results in smaller code, if you are using lot of them
Also, if you are using void to return undefined then you can simply use void 0, which is equivalent to void(0).