Logical Operators Explained in JavaScript

Logical Operators Explained in JavaScript

Learn logical operators in JavaScript under 10 minutes
Ferenc Almasi β€’ Last updated 2024 March 11 β€’ Read time 9 min read
Learn how to use logical operators in JavaScript to connect and evaluate multiple expressions.
  • twitter
  • facebook
JavaScript

This lesson is a preview from our interactive course

Say that we want to check two things at a time. We want to check if a number is greater than 10, but less than 100. How would we do that? That is where logical operators come into place. Let’s see what kind of logical operators we have in JavaScript.


Logical AND

First, we have the logical AND operator. As in the imaginary situation above, it can be used exactly to combine multiple comparisons together. If all comparisons are true, then the statement is true as well. Let’s see what it would look like in terms of code:

Copied to clipboard! Playground
const x = 50;

x > 10 && x < 100;

// Or inside an if statement
if (x > 10 && x < 100) {

}
Using the logical AND operator to combine multiple comparisons together

To use the logical AND, we need to use two ampersands next to each other: &&. This means, that we only want the code to run inside the if statement if x is greater than 10, but less than 100.

Combining multiple comparisons together will create a boolean. If all statements are true, then the output will be true as well. If just one of the statements is false, then the output will be false too. Here is the result table for the logical AND:

ExpressionOutput
true && truetrue
true && falsefalse
false && truefalse
false && falsefalse

Note that only two true values will produce a true output. In every other case, it'll be evaluated as false. We can also combine as many statements together as we would like. We may also see this for variables when we try to define a boolean flag:

Copied to clipboard! Playground
const x = 50;
const isTrue = x
    && x > 10
    && x < 100
    && x !== 49;

console.log(isTrue);
We can use as many logical operators as needed Execute code

Take note that for readability, it's best if we break multiple comparisons into new lines, each one starting with the logical AND operator. If you have too many conditions, it's also recommended to use multiple variables instead of one.


Logical OR

What happens if we only want one statement to be true, but not all? That’s when we need to use the logical OR operator. If one of the operands is evaluated to true when using logical OR, then the expression itself will also be evaluated to true. To use logical OR, we need to use two pipes like so:

Copied to clipboard! Playground
const x = 10;

x > 10 || x < 100;

// Or inside an if statement
if (x > 10 || x < 100) {

}
Use double pipes to use the logical OR operator

This means that even though x is not greater than 10, the expressions will still be evaluated to true because the second part is true. Let’s see how the result table looks like for the logical OR operator:

ExpressionOutput
true && truetrue
true && falsetrue
false && truetrue
false && falsefalse

Note that when using logical OR, we'll only get a false value if all operands are false. We can also combine different logical operators, so we can have the following:

Copied to clipboard! Playground
const x = 10;
const isTrue = x
    && x > 10
    || x < 100
    && x !== 49;

console.log(isTrue);
We can combine different logical operators Execute code

The logical OR operator is also commonly used during variable assignments to provide fallback values. Take the following as an example:

Copied to clipboard!
const uploadedFileName = null;
const fileName = uploadedFileName || 'unnamed';

console.log(fileName);
Use the logical OR operator to provide fallback values Execute code

Here we say that the fileName should match the uploaded file's name. In case it's not provided (just like in the example above), then use a hard-coded string as the filename: "unnamed". We can chain this with multiple logical ORs, which will go from left to right until it finds a truthy value:

Copied to clipboard! Playground
const uploadedFileName = null;
const defaultFileName = 'default';
const fileName = uploadedFileName || defaultFileName || 'unnamed';

console.log(fileName);
Using multiple fallbacks are also possible Execute code

Nullish Coalescing

There is also an operator in JavaScript called the nullish coalescing operator that works in a similar way to logical OR. It can be used during variable assignments, just like the above, but this time, it's denoted with two question marks:

Copied to clipboard! Playground
const foo = null ?? 'Foo Fighters';
const age = 0 ?? 42;

// console.log(foo);
console.log(age);
Run the example and uncomment `foo` to see its value Execute code

Using the nullish coalescing operator, we can return the left-hand side of the operand if it's falsy, but not null or undefined. This means that for foo, it'll return the string (the right-hand side of the operand), but for the age, it'll return 0 (the left-hand side of the operand).

This can be used to only filter null and undefined values. It's useful if we still want to work with "valid" falsy values such as false, or 0.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Logical NOT

Lastly, we have the logical NOT operator. It's for negating values. This can be achieved by using an exclamation mark in front of a value. We have already seen this when we briefly touched it in the conditions and loops lesson:

Copied to clipboard!
!true;
This reads as β€œnot true”

We can also prefix entire expressions with it as well, by wrapping the expression into parentheses:

Copied to clipboard!
const x = 50;
const expression = !(x > 10 && x < 100);

console.log(expression)

We have also talked about double negation before. This is negating the negated value into its original state, while also converting it to a boolean in the process:

Copied to clipboard! Playground
// Copy the code to the console to see its value
!!''

// Try to double negate the following values too:
// !!false
// !!null
// !![]
Double negation can be used by prefixing a value with two exclamation marks Execute code

The result table for logical NOT is much simpler since we can only have two options:

ExpressionOutput
!truefalse
!falsetrue

Ternary

These are all the logical operators in JavaScript that we need to know about. There is also a conditional operator we need to cover, called a ternary operator. It's used for conditionally assigning a value to a variable in the following way:

Copied to clipboard!
const age = 21;
const eligible = age > 21 ? 'yes' : 'no';

console.log(eligible);
Use ? and : to create a ternary operator Execute code

So what does this mean exactly? It means that eligible should have the value of β€œyes”, in case age is greater than 21. If it's less than 21, it'll have the value of β€œno”. We can also simply assign a comparison to a variable to create a boolean flag. So in the above example, if we only need a true or false value for the eligible, we can simply say the following:

Copied to clipboard!
const age = 21;
const eligible = age > 21;

console.log(eligible);
eligible will be a boolean value, either true or false Execute code

If we need a somewhat more elaborate condition and we still want to use a ternary, we can wrap the condition into parentheses to make use of both a logical and the ternary operator:

Copied to clipboard!
const age = 21;
const eligible = (age > 21 && age < 60) ? 'yes' : 'no';

console.log(eligible);
We can use multiple conditions by wrapping them together into parentheses Execute code

Make sure you don’t overdo writing everything in one line, otherwise your code will quickly become unreadable. Only use ternary for simple conditions. If you need more elaborate logic, use an if or switch statement.


Short Circuit Evaluation

There's one last thing we haven't touched on in this lesson. Short-circuit evaluation, or short-circuiting for brevity, is a technique that uses logical operators to simplify code, make it easier to understand, and can even help you avoid running into type errors in some cases. We can use logical AND and logical OR operators to create short circuits. Take the following as an example:

Copied to clipboard! Playground
const useLogs = true;

// Short circuit with logical AND
useLogs && console.log('Logs are enabled');

// The above is equivalent to:
if (useLogs) {
    console.log('Logs are enabled');
}
How to execute code using the logical AND operator

We can see that using a logical AND shortens our code, and with its help, we can avoid using an if statement. Both expressions will achieve the same result. We can also use a ternary operator to introduce an else branch in the following way:

Copied to clipboard! Playground
const useLogs = true;

// Using ternary for an else branch
useLogs ? console.log('Logs are enabled') : console.log('Logs are disabled');

// The above can be refactored to:
console.log(useLogs ? 'Logs are enabled' : 'Logs are disabled');

// The above is equivalent to:
if (useLogs) {
    console.log('Logs are enabled');
} else {
    console.log('Logs are disabled');
}
How to use ternary to introduce an else branch

If the useLogs variable is true, it'll execute the first console.log statement; otherwise, it'll execute the second. Note that we can use a single console.log statement by moving the variable inside the parentheses. Prefer this solution to reduce code complexity.

We have already seen how the logical OR can be used for short circuits as well during variable assignments:

Copied to clipboard! Playground
const uploadedFileName = null;
const defaultFileName = 'default';

// Short circuit with logical OR
const fileName = uploadedFileName || defaultFileName || 'unnamed';

// The above is equivalent to:
if (uploadedFileName) {
    fileName = uploadedFileName;
} else if (defaultFileName) {
    fileName = defaultFileName;
} else {
    fileName = 'unnamed';
}
Using logical OR for short circuits

We can see that using a logical OR operator creates much shorter and simpler code as opposed to using a list of if-else statements. It's readable, less prone to bugs, and easier to test and maintain.

Note that you should only use short circuits for simple expressions. More complex expressions can remain verbose for improved readability.


Test Your Skills!

To reinforce your knowledge and test your skills, run the following example to execute the tests, then combine the highlighted variables in a way that produces the expected values.

Copied to clipboard! Playground
import { expect, it } from 'vitest';

// Test #1:
it('Combine the variables so that it produces "true"', () => {
    const a = 1;
    const b = true;
    const c = false;

    // Replace the question marks with the right operator
    const result = a ?? b ?? c;

    expect(result).toBe(true);
});

// Test #2:
it('Combine the variables so that it produces "false"', () => {
    const a = false;
    const b = true;

    // Replace the question marks with the right operator
    const result = !a ?? !b;

    expect(result).toBe(false);
});

// Test #3:
it('Combine the variables so that it produces "1"', () => {
    const a = true;
    const b = 1;
    const c = false;

    // Replace the question marks with the right operator
    const result = a ?? b ?? !c;

    expect(result).toBe(1);
});
Replace the question marks with the correct operators Execute code
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.