Difference between operators?, ?? and || in Javascript / TypeScript

,

? , optional chaining operator,
This allows to read the value of a property located internally in the chain of linked objects, without having to explicitly verify each reference in the executed chain.

the operator ?. works as an operator . of chaining, except that instead of producing an error if the reference is null (null either undefined), the expression is “short-circuited” and returns the value of undefined, When used with function calls, returns undefined If the task performed does not exist.

When the reference probability is negligible, accessing chained properties results in shorter and simpler expressions. It can also help when searching for the contents of an object when the existence of certain imperative properties is not guaranteed.

Example

const user = {
  id: 13,
  name: "Thayto"
};

console.log(user?.name); // John
console.log(user?.fullName); // undefined, aplicação não vai quebrar.
console.log(user.fullName); // TypeError: Cannot read property ‘fullName’ of undefined, aplicação quebra.
enter fullscreen mode

exit fullscreen mode

,

?? , Nalish Coalescing Operator,
It is a logic operator that returns its right-handed operand when it has a left-handed operator. null either undefined, Otherwise, it returns the operand of its left hand.

Example

console.log(13 ?? "não encontrado") // 13
console.log(0  ?? "não encontrado") // 0

console.log("Dri"  ?? "não encontrado") // "Dri"
console.log(""     ?? "não encontrado") // ""

console.log(true  ?? "não encontrado") // true
console.log(false ?? "não encontrado") // false

console.log(undefined ?? "não encontrado") // "não encontrado"
console.log(null      ?? "não encontrado") // "não encontrado"
enter fullscreen mode

exit fullscreen mode

,

|| And this logical or operator
The logical OR expression is evaluated from left to right, testing it for possible “short circuit” evaluation using the following rule:

(alguma truthy expression) || expr To short-circuit the correct expression.

short circuit means that the part expr The above is not evaluated, so any side effects of doing so have no effect (e.g. if expr is a function call, the call never occurs). This happens because the value of the operator is already determined after the first operand is evaluated.

Example

console.log(13 || "não encontrado") // 13
console.log(0  || "não encontrado") // "não encontrado"

console.log("Dri"  || "não encontrado") // "Dri"
console.log(""     || "não encontrado") // "não encontrado"

console.log(true  || "não encontrado") // true
console.log(false || "não encontrado") // "não encontrado"

console.log(undefined || "não encontrado") // "não encontrado"
console.log(null      || "não encontrado") // "não encontrado"
enter fullscreen mode

exit fullscreen mode

Leave a Comment