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
Related
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.
This question already has answers here:
What is the difference between null and undefined in JavaScript?
(38 answers)
JavaScript checking for null vs. undefined and difference between == and ===
(8 answers)
Closed 4 years ago.
In below code snippet a==b return true, i.e they point to same memory location, hence they will have same value.
I would like to know, how JS engine knows a===b is false.
How is type information determined when 2 different types point to same memory location?
Edit 1: From comments it looks like my question might not be clear. I totally understand difference between == and === in terms of usage in JS language. I am more interested in knowing how JS engine saves type information for null and undefined. As per my understanding variables a & b point to same memory location that is why I get a==b, if this understanding is wrong, please correct me.
Edit 2: Ok I will put my question in another way. How typeof operator knows a is object and b is undefined despite having a==b.
var a = null;
var b = undefined;
console.log(a==b);
console.log(a===b);
console.log(typeof a);
console.log(typeof b);
In the code snippet added in the question:
var a = null; var b = undefined;
console.log(a==b);
console.log(a===b);
console.log(a==b) returns true because == uses type coercion to check the equality of both the variables. Therefore, null and undefined are thought of as equals.
console.log(a===b) returns false because === does not use type coercion. For ===, null and undefined are not same types and it doesn't care about checking deep equality when the operands aren't of the same type.
This has got nothing to do with memory locations.
a = null, b= undefined;
a == b /* only check their values */
a === b /* also check their types + values */
typeof a == typeof b // false
typeof "variable" gives the type of the variable.
This question already has answers here:
All falsey values in JavaScript
(4 answers)
Closed 6 years ago.
I recently got some JS code and I saw very often statements like the following:
if(object) {
//do something
}
or
if(object.attr) {
//do something
}
Is this a short form for if(object !== undefined) or for if(object !== null)?
It's a short form for
if (object !== "" &&
!Number.isNaN(object) &&
object !== 0 &&
object !== false &&
object !== undefined &&
object !== null)
The isNaN() check is a little tricky; the "old" global isNaN() would coerce its parameter to a number, so passing a string like "foo" to isNaN() returns true, even though the string "foo" isn't really NaN. The newer isNaN() method on the number constructor doesn't perform that coercion, so Number.isNaN("foo") is false.
Note that when checking for the existence of an object property there's an ambiguity with undefined. It's possible for a property to be present on an object but have no value. The in operator is useful in such cases:
if ("something" in object)
tests whether the object has a property named "something" regardless of value.
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:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 9 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Can someone help me by explaining the difference. From what I understand the === does an exact match but what does this mean when comparing with null ?
What does this mean when comparing with null?
It means exactly what you already said: It checks whether the value is exactly null.
a === null is true if the value of a is null.
See The Strict Equality Comparison Algorithm in the specification:
1. If Type(x) is different from Type(y), return false.
2. If Type(x) is Undefined, return true.
3. If Type(x) is Null, return true.
So, only if Type(a) is Null, the comparison returns true.
Important: Don't confuse the internal Type function with the typeof operator. typeof null would actually return the string "object", which is more confusing than helping.
a == null is true if the value of a is null or undefined.
See The Abstract Equality Comparison Algorithm in the specification:
2. If x is null and y is undefined, return true.
3. If x is undefined and y is null, return true.
=== means it checks both the value and the type of the variables. For example pulled from the w3c page, given x = 5, x is an int, so x==="5" is false because it is comparing and int to string and x ===5 is true because it is both an int and the right value.
=== is strict operator it not only compare value, but also type of variables so
string===string
int===int
== only compare values.
Using the triple equals, the values must be equal in type as well.But not in ==.
i.e
1==true // this return true
1===true // but return false
a==null // will true if a is null or undefined
1==true will be true
but 1===true will be false
eg. === compares on data type level while using == JavaScript will typecast by it self