Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
What is (~~) "double tilde" operator in JavaScript ?
Next article icon

What does OR Operator || in a Statement in JavaScript ?

Last Updated : 19 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript is a dynamic programming language that allows developers to write complex code with ease. One of the fundamental concepts in JavaScript is the use of operators, which are symbols that perform operations on one or more values. One such operator is the || (logical OR) operator, which can be used in a variety of ways to simplify code and make it more efficient.

The || (logical OR) Operator: The || operator in JavaScript is a binary operator that is used to evaluate two or more expressions and return the first truthy expression. A truthy value is any value that is not undefined, null, false, 0, NaN, or an empty string ('').  The logical OR operator evaluates its operands in a short-circuit manner. This means that it stops evaluating as soon as it encounters the first truth value. 

When the logical OR operator || is used in a variable declaration statement, it works in the following way:

  • If the first operand (left-hand side) is truthy (i.e., has a value that is not false, 0, null, undefined, NaN, or an empty string), the operator returns the value of the first operand.
  • If the first operand is falsy (i.e., has a value that is false, 0, null, undefined, NaN, or an empty string), the operator returns the value of the second operand (right-hand side).

Syntax:

expression1 || expression2

Here, expression1  and expression2 are the two expressions that are being compared. The logical OR operator || returns the value of the first truthy expression it encounters, or the value of the last expression if both expressions are false.

Here are all the possible approaches for using the || operator in JavaScript:

1. Logical OR operation: The || operator performs a logical OR operation between two values. If either of the operands is true, the operation returns true. If both operands are false, the operation returns false. This approach is commonly used in conditional statements to check for truthy values.

Example: In this example, the || operator performs a logical OR operation between true and false. Since the first operand is true, the operation returns true. Similarly, in the second example, the operation returns false because both operands are false. In the third example, the operation returns true because at least one of the operands is true.

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

Output
true false true

2. Default value assignment: When used in a var statement, the || operator can be used to set a default value for a variable. If the variable has not been assigned a value or if its value is falsy, the operator sets the default value. This approach is commonly used to provide fallback values.

Example:  In this example, the name variable is initially assigned an empty string. When the || operator is used to set a default value, it checks if the variable has a truthy value. Since an empty string is falsy, the operator sets the default value to "Geeks for Geeks".  The name1 variable has a truthy value, so the operator does not change its value.

JavaScript
let name = "";  // Geeks for Geeks console.log(name || "Geeks for Geeks");  let name1 = "A computer science portal for geeks";  // A computer science portal for geeks console.log(name1 || "Geeks for Geeks");  

Output
Geeks for Geeks A computer science portal for geeks

3. Default function argument: The || operator can also be used to set default values for function arguments. If an argument is not provided or is falsy, the operator sets the default value. This approach is commonly used to provide default arguments for functions.

Example:  In this example, the greet function takes an argument name. When the || operator is used to set a default value, it checks if the argument has a truthy value. If the argument is not provided or is falsy, the operator sets the default value to "Geek". In the first function call, no argument is provided, so the default value is used. In the second function call, the argument "Geeks for Geeks" is provided, so the operator does not change its value.

JavaScript
function greet(name) {       name = name || "Geek";       console.log("Hello, " + name + "!"); // Hello, Geeks! }  greet(); // Hello, Geek! greet("Geeks for Geeks"); // Hello, Geeks for Geeks! 

Output
Hello, Geek! Hello, Geeks for Geeks!

4. Chaining multiple OR operations: The || operator can be chained to check for multiple values. It returns the first truthy value it finds or the last value if all values are falsy. This approach is commonly used to select a value from a list of options.

Example: In this example, the || operator is chained to check for multiple values. The operator returns the first truthy value it finds or the last value if all values are falsy. In this case, if value1 is falsy, the operator checks value2. If value2 is also falsy, it checks value3. If all three values are false, the operator returns "default".

JavaScript
const value1 = null; const value2 = undefined; const value3 = ""; const defaultValue = "default";  const result = value1 || value2 || value3 || defaultValue;  console.log(result); // Output: default 

Output
default

5. Checking for undefined values: The || operator can be used to check if a variable is undefined. If the variable is undefined, the operator returns the default value. This approach is commonly used to provide fallback values for variables that may not have been initialized.

Example: In this example, the value variable is not initialized, so it is undefined. When the || operator is used to check for undefined values, it returns the default value "default". Similarly, the array variable has four elements, but the fourth element is undefined. When the || operator is used to set a default value for the item variable, it checks the fourth element first, which is undefined. Since undefined is falsy, the operator sets the default value to "default".

JavaScript
let value; console.log(value || "default"); // default  let array = [1, 2, 3]; let item = array[3] || "default"; console.log(item); // default 

Output
default default

Next Article
What is (~~) "double tilde" operator in JavaScript ?
author
ankitjangidx
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-operators
  • JavaScript-Questions

Similar Reads

  • What is (~~) "double tilde" operator in JavaScript ?
    This is a special kind of operator in JavaScript. To understand the double tilde operator, first, we need to discuss the tilde operator or Bitwise NOT. The (~) tilde operator takes any number and inverts the binary digits, for example, if the number is (100111) after inversion it would be (011000).
    3 min read
  • What is JavaScript >>> Operator and how to use it ?
    The JavaScript >>> represents the zero-fill right shift operator. It is also called the unsigned right-bit shift operator. It comes under the category of Bitwise operators. Bitwise operators treat operands as 32-bit integer numbers and operate on their binary representation. Zero-fill right
    3 min read
  • How to use multiple ternary operators in a single statement in JavaScript ?
    In JavaScript, the ternary operator (? :) is a shorthand for if-else statements. You can use multiple ternary operators in a single statement to handle multiple conditions efficiently. This makes your code shorter, but be cautious as too many nested ternary operators can reduce code readability. Syn
    2 min read
  • What is the !! (not not) Operator in JavaScript?
    The !! (double negation) operator is a repetition of the unary logical "not" (!) operator twice. It is used to determine the truthiness of a value and convert it to a boolean (either true or false). Here’s how it works: The single ! (logical "not") inverts the truth value of a given expression:!fals
    2 min read
  • Remainder Assignment(%=) Operator in Javascript
    The Remainder Assignment Operator in javascript is represented by "%=". This operator is used to divide the value of the variable by another operand and assign the remainder to the variable which is the first operand. This can be also explained as assigning the remainder to the first operand which i
    1 min read
  • Right Shift Assignment(>>=) Operator in JavaScript
    The Right Shift Assignment Operator is represented by ">>=". This operator shifts the first operand to the right and assigns the result to the variable. It can also be explained as shifting the first operand to the right in a specified amount of bits which is the second operand integer and the
    1 min read
  • Subtraction Assignment( -=) Operator in Javascript
    The Subtraction Assignment Operator( -=) is used to subtract a value from a variable. This operator subtracts the value of the right operand from a variable and assigns the result to the variable, in other words, allows us to decrease the left variable from the right value. Syntax: a -= b We will no
    1 min read
  • How to Set Multiple Conditions in an If Statement in JavaScript?
    In JavaScript, conditional statements like if are used to execute code blocks based on certain conditions. There are situations where we might want to check multiple conditions within a single if statement. In such cases, JavaScript provides logical operators like && (AND) and || (OR) to com
    5 min read
  • How to Use AND Statement in if with JavaScript?
    In JavaScript AND (&&) logical operator is used in the 'if' statement to check for two or more conditional validities. AND logical operator in the 'if' condition returns true only when all the conditions inside the 'if' statement are TRUE. If any one condition inside the 'if' statement is FA
    2 min read
  • JavaScript Remainder Assignment(%=) Operator
    JavaScript remainder assignment operator (%=) assigns the remainder to the variable after dividing a variable by the value of the right operand. Syntax: Operator: x %= y Meaning: x = x % y Below example illustrate the Remainder assignment(%=) Operator in JavaScript: Example 1: The following example
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences