πŸŽ„ Get 20% off from our JavaScript course for the holidays! πŸŽ„
Logical Operators Explained in JavaScript

Logical Operators Explained in JavaScript

Learn logical operators in JavaScirpt under 10 minutes
Ferenc Almasi β€’ 2022 March 01 β€’ Read time 7 min read
  • 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 will 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 is best if we break multiple comparisons into new lines, each one starting with the logical AND operator. If you have too many conditions, it is 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 will only get a false value if all operands are false. We can also combine different logical operators together, so we could 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 is 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 is 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 will return the string (the right-hand side of the operand), but for the age, it will 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 JavaScript Remove ads

Logical NOT

Lastly, we have the logical NOT operator. It is 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 is 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 is less than 21, it will 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.


Test Your Skills!

Combine the following 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
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended