Using ternary operator on Object?.property to check if object and object property is defined [duplicate] - javascript

This question already has answers here:
Optional Chaining in JavaScript [duplicate]
(8 answers)
Closed 2 years ago.
I met in code condition line like this someObject.arrParam?.length. What syntax is that? How does that question mark thing's called? I know an optional operator which used for parameters in functions. Is that a variation of usage of it? Never met before.

This is called Optional Chaining in JavaScript. It allows to drill
down on objects without raising null exception.
Eg: Try running the below code snippet, then uncomment the line and run it to understand a working example.
let employeeA ={ name: "Dane", address : { city:"London"}}
let employeeB ={ name: "John"}
console.log(employeeA.address.city)
// console.log(employeeB.address.city) <---- this will raise an error
console.log(employeeB.address?.city) // <--- this wont
This was introduced as new feature in the latest ESNext iterations.
NodeJS Support : https://node.green/#ES2020-features-optional-chaining-operator-----
Current Browser Support : https://caniuse.com/#feat=mdn-javascript_operators_optional_chaining
More Details here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

That is called Optional Chaining (or conditional chaining) which basically will evaluate the whole expression as undefined if arrParam is undefined or null.

It's called "Conditional (ternary) operator".
result=condition?ifTrue:ifFalse
In x=(y>10)?100:1, if y>10, x is set to 100, else, x is set to 1.
Equivalent to:
if(y>10) x=100;
else x= 1;

Related

What is the obj?.prop syntax in javascript? [duplicate]

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.

Not not (!!) inside if condition [duplicate]

This question already has answers here:
Why is the !! preferable in checking if an object is true? [duplicate]
(3 answers)
Closed 7 years ago.
Note: it's actually a duplicate of What is the difference between if(!!condition) and if(condition)
While I understand what the !! means (double not), for this same reason it doesn't make sense to me its use in the MDN documentation:
if (!!window.Worker) {
...
}
Isn't this exactly the same as this for this situation?
if (window.Worker) {
...
}
The casting to boolean makes no sense for me since the if will only be executed if the window.Worker exists. To say that it's True or Object for an if() conditional (I think) is the same.
So, why is the !! used here? Or, why is the window.Worker casted to boolean inside an if()?
Yes it is exactly the same. Nothing to add.
It might have been used to emphasize that the window.Worker property - expected to be a function - is cast to a boolean for detecting its presence, instead of looking like a forgotten () call. Regardless, it is now gone.

jScript/HTML5 - What's the difference between localStorage.setItem & localStorage.variable = x? [duplicate]

This question already has answers here:
localStorage - use getItem/setItem functions or access object directly?
(5 answers)
Closed 8 years ago.
What is the difference between the following two snippets of code? Is the square bracket syntax an old, deprecated syntax? When I first used localStorage, all the documentation I found definitely said to use the square bracket syntax, but now I can't find any documentation on it at all.
The documented syntax:
localStorage.setItem('hello', 'world');
localStorage.getItem('hello'); // world
The square bracket syntax:
localStorage.hello = 'world';
localStorage.hello; // world
This is what the documentation says about it:
Although the values can be set and read using the standard JavaScript property access method, using the getItem and setItem methods is recommended.

Why use void(0)? [duplicate]

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).

Can you set an undefined variable as a function parameter? [duplicate]

This question already has answers here:
Undefined variable as function argument javascript
(2 answers)
Closed 8 years ago.
I am building a function to match types of variables. It will be an alternative to typeof <var> === "something".
My function call looks like this : is("some text")["string"]. It returns true, or is([])["element"]. Now it returns false, But I have an issue with it.
For example, if I try to send an undefined variable like "undefVar" to a function I am expecting something like this: is(undefVar)["undefined"], but I get an error which says that "undefVar" is not defined.
Can I somehow make my function work using undefined variables? Is this possible at all?
p.s: I have to use this function a lot so it seems (for me) that it would be better to use something like this : is(var)[type] as opposed to typeof var === type.
typeof is special on nonexistent variables. You cannot mimic it with a function.
No, you cannot blindly pass undefined variables to your function from the call site and globally change the behavior of the JS engine to accomodate this.
typeof is a built-in operator and is not bound by the rules of "common" functions, which is why it can do things that custom functions cannot.
Finally, I strongly disagree that it would be practically preferable to use an alternative syntax even if that were possible.

Categories