JavaScript Operators: Understanding Logical OR and Nullish Coalescing

Programming languages such as JavaScript are important and adaptable for web development. JavaScript has nothing to do with Java, despite its name. In 1997, the European Computer Manufacturers Association (ECMA) standardized it as ECMAScript.

JavaScript is mainly used in client-side scripting, which generates dynamic and interactive web pages by running the script inside web browsers. Prototypal inheritance, which enables objects to inherit properties from other objects, and dynamic typing, which permits variables to change types, are some of its important features. 

JavaScript has uses outside of web development. It is used to develop mobile apps using frameworks like React Native and server-side programming with Node.js. Because of its extensive browser support and adaptability, JavaScript is a fundamental component of contemporary web development.

You might also be interested in JavaScript for Beginners

Exploring JavaScript’s Logical OR Operator (||) and Nullish coalescing operator(??)

The OR operator || is frequently used to handle default values. However, the less well-known nullish coalescing operator also exists, which gives a default value as well. Despite their similarities, the two differ in a few significant ways.

The OR operator is denoted by || symbol. It returns the first truthy value. If all expressions are evaluated to falsy value, the final expression is returned. Thus, even in cases where both expressions are false, the OR operator will return the second one.

Logical OR Operator

Nullish coalescing is denoted by double question mark (??).

In Nullish coalescing operator, if the left operand of the nullish coalescing(??) operator is null or undefined, it returns the operand on the right side of the logical operator; otherwise, it returns the operand on the left side.

Nullish coalescing operator

In summary, the difference between falsy value and null/undefined value is what sets the two operators apart. When an empty string, 0, false, NaN, or any other false value occurs, the logical or (||) operator selects the right operand. The nullish coalescing operator (??) only takes the right operand when the left side is set to null or undefined. Nevertheless, we can think of the?? operator as a subset of the ||.

Also, you can read: Conditionals in Javascript