Today I will share a few simple ways to deal with null values, avoiding redundant codes when using ternary operations, and or, if else, I hope it will be helpful to everyone.
optional chaining (?.)
let a;
let b = a.?age;
meaning:
Optional chain, only when a exists and a has the age attribute, the value will be assigned to b, otherwise undefined will be assigned to b, the important thing is, no matter whether a exists or not, a.?age does not Will report an error.
Example:
When not using ( ?. ):
If a value is null or undefined, what happens when we use the dot operator to call a method or access a property?
let a;
let b = a.age;
Run the code, you will get an error;
when using it:
let a;
let b = a?.age;
Run the code and print out an undefined ;
Null coalescing operator (??)
let a;
let b=a??c;
meaning:
Null coalescing operator (??), if a is not undefined or null, then a will be assigned to b, if a is undefined or null, then c will be assigned to b.
Example:
Do not use( ?? )
var u_defaultValueIfUndfined = function (value, defaultValue) {
if (typeof value == "undefined" || value == null) {
return defaultValue;
}
return value;
};
let a;
let c=1; // []、0、“字符串” 等均可
let b = u_defaultValueIfUndfined(a,c);
use( ??)
let a;
let c=1; // []、0、“字符串” 等均可
let b=a ?? c;
The above two code examples have the same effect;
Null assignment operator (??=)
b ??= a;
Similar to the ( ?? ) example above
meaning:
When the value on the left side of ??= is null or undefined, the value of the right variable will be assigned to the left variable, and all other values will not be assigned. Also in some scenarios, a lot of code can be omitted.
Example:
let b = '你好';
let a = 0
let c = null;
let d = ’123‘
b ??= a; // b = “你好”
c ??= d // c = '123'
Run the code, the result is as follows:
Well, that's all for today's sharing, welcome to exchange!