The three uses of the question mark in JavaScript ?? and ?. and ?: Did you know?

 I recently read some test scripts about JavaScript, and found the use of question marks in JS quite interesting, so I made a summary and shared it with you here! There are roughly three usages of question marks in JS, namely: null value coalescing operator, optional chain operator and ternary operation.

question mark question mark (??)

The null coalescing operator?? is a logical operator that returns its right operand when the left operand is null or undefined, otherwise it returns the left operand.

For example

console.log(null ?? "xx")
输出 xx
console.log(1 ?? "xx")
输出 1

question mark dot (?.)

The optional chaining operator (?.) The optional chaining operator allows reading the value of a property located deep in a chain of connection objects without having to explicitly verify that every reference in the chain is valid. The advantage of using it is that it will not cause an error if the reference is null or undefined.

Syntax: obj?.prop obj?.[expr] arr?.[index] func?.(args)

For example

var obj={a:{b:1}}
console.log(obj?.a?.b)
输出1
console.log(obj?.a?.c)
输出 undefined

question mark colon (?: )

This is a ternary operation, and the specific expression is (condition ? exprIfTrue : exprIfFalse)

The meaning of the expression is that the condition condition is true, then execute exprIfTrue, otherwise execute exprIfFalse

Give an example and everyone will understand

var n = 10;
console.log((n >= 11) ? "a" : "b");
输出b
当 var n = 12;
输出a

If you know any special usages of question marks in JS, please leave a message to discuss. If the article helped you, please like and forward it!

Guess you like

Origin blog.csdn.net/liwenxiang629/article/details/129987614
Recommended