by Sai gowtham

How to use JavaScript Logical or (||) operator

In JavaScript, the logical or(||) operator is used to evaluate the expressions from left to right side.

 expression 1 || expression 2 (short circuit evaluated)

It returns the first expression, if the value can be converted to true otherwise, it returns the second expression.

The second expression is short circuit evaluated it means the second expression is executed or evaluated only if the first expression evaluates to false.

Let’s see an example:

console.log( 1 || 2 )  // 1

In the above example, the output is 1 because 1 is a truthy value.

console.log( 0 || 10) // 10

Here it returns 10 because 0 is a falsy value.

More examples

console.log(false || true ) // true

console.log(false || false) // false

console.log( " " || "hello") // "hello"

console.log(" " || 0 ) // 0

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course