Overload `?` operator in javascript to handle null or undefined [duplicate] - javascript

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.

Related

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

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;

What does ?. and ?? operator in javascript do? [duplicate]

This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
Optional Chaining in JavaScript [duplicate]
(8 answers)
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Closed 3 years ago.
I recently noticed usage like this in a java script code base what does it do. I was unable to find any relevant documentation regarding that. Though intuitively operators seem to checking whether property is present. Is there any official documentation regarding this.
Ex:
args?.propertyName !== 'someValue'
const value = props.someProp ?? props.defaultProp;
They are for optionals:
val ?? other is called nullish coalescing operator and is equivalent to val == null ? other : val
and optionalThing?.property is refered as optional chaining and is the same as optionalThing == null ? null : optionalThing.property
This optional chaining expressions result in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing ( allows you to do things like optionalThing?.optionalProperty?.anotherOptionalProperty?.property ).
The ?. is called the optional chaining operator (TC39 Stage 4), it is used when you are not sure whether a nested property exists or not. If you try to use the . operator to access a property which is undefined you get a TypeError.
For example:
const obj = {foo: {} };
//This is safe, results in undefined
console.log(obj?.foo?.bar?.baz);
//This results in Uncaught TypeError: Cannot read property 'baz' of undefined
console.log(obj.foo.bar.baz);
Where as the ?? is called the null coalescing operator (TC39 Stage 3). When you are using falsy values like an empty string "" or a 0 with a || operator the operand on the right hand side of the || is returned as the falsy value is ignored.
The ?? comes handy when you don't want that and actually you want to consider the falsy values. If the value on the left is a null or undefined only then the value on the right of the ?? is taken:
For example:
const empString = "";
const defaultValue = empString || "A default value";
//Outputs A default value as "" empty string is falsy
console.log(defaultValue);
const actualValue = empString ?? "A default value";
//Does not print the default value as the empString is neither null or undefined
console.log(actualValue);
Same for other falsy values like 0, false, in disagreement with the || operator which will output the 'default string:
console.log(false ?? 'default') //false
console.log(0 ?? 'default') // 0
Only for undefined and null this will output the default value provided in agreement with the || operator:
console.log(undefined ?? 'default') //default
console.log(null ?? 'default') //default

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.

Object is not null and not undefined. What is better - double inversion `!!` or strict equillity `!==` in JavaScript [duplicate]

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.

Javascript Set: any way to override comparison between elements? [duplicate]

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.

Categories