Learn JavaScript Operators – Logical, Comparison, Ternary, and More JS Operators With Examples

Operators are one of the fundamental building blocks of any programming language, and JavaScript is no exception. An operator allows you to perform actions on operands, which can be values or variables. JavaScript supports a wide variety of operators that enable you to perform arithmetic, comparisons, logical operations, assignments, and more.

In this in-depth guide, we‘ll explore the 7 main categories of operators in JavaScript:

  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Ternary operator
  6. typeof operator
  7. Bitwise operators

We‘ll dive into each category, explaining the syntax and usage of each operator with code examples. By the end of this article, you‘ll have a solid understanding of how to wield JavaScript‘s operators effectively in your own code. Let‘s get started!

1. Arithmetic Operators

Arithmetic operators allow you to perform mathematical calculations on numeric operands. JavaScript supports the following arithmetic operators:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Remainder (%)
  • Exponentiation (**)
  • Increment (++)
  • Decrement (–)

Here are examples of each operator in action:

let x = 10;
let y = 3;

console.log(x + y);  // 13
console.log(x - y);  // 7
console.log(x * y);  // 30
console.log(x / y);  // 3.33333333
console.log(x % y);  // 1
console.log(x ** y); // 1000

console.log(++x);    // 11 
console.log(--y);    // 2

The addition operator (+) also doubles as a concatenation operator when one of the operands is a string:

let greeting = "Hello";
let name = "John";

console.log(greeting + " " + name); // "Hello John"

It‘s important to keep in mind the order of operations when using multiple arithmetic operators in a single expression. JavaScript follows the PEMDAS rule: Parentheses, Exponents, Multiplication and Division (from left to right), Addition and Subtraction (from left to right).

console.log(3 + 4 * 5); // 23
console.log((3 + 4) * 5); // 35

2. Assignment Operators

Assignment operators allow you to assign values to variables. The most basic assignment operator is the equals sign (=), but JavaScript also provides several combination assignment operators for common operations:

  • Assignment (=)
  • Addition assignment (+=)
  • Subtraction assignment (-=)
  • Multiplication assignment (*=)
  • Division assignment (/=)
  • Remainder assignment (%=)
  • Exponentiation assignment (**=)

Here‘s how they work:

let x = 10;

x += 5;  // equivalent to x = x + 5
console.log(x); // 15

x -= 3;  // equivalent to x = x - 3  
console.log(x); // 12

x *= 2;  // equivalent to x = x * 2
console.log(x); // 24

x /= 4;  // equivalent to x = x / 4
console.log(x); // 6

x %= 5;  // equivalent to x = x % 5
console.log(x); // 1

x **= 3; // equivalent to x = x ** 3
console.log(x); // 1

These combination assignment operators provide a concise way to perform an operation and assign the result back to the variable, which can make your code cleaner and more readable.

3. Comparison Operators

Comparison operators allow you to compare two values and determine the relationship between them. JavaScript supports the following comparison operators:

  • Strict equal (===)
  • Strict not equal (!==)
  • Less than (<)
  • Less than or equal (<=)
  • Greater than (>)
  • Greater than or equal (>=)

Comparison operators return a Boolean value – either true or false – depending on whether the comparison evaluates to true or not.

console.log(5 < 7);  // true
console.log(3 > 10); // false 
console.log(1 <= 1); // true
console.log(2 >= 4); // false

console.log("apple" === "apple"); // true
console.log("apple" !== "pear");  // true

You may have noticed the strict equal (===) and strict not equal (!==) operators. These operators compare both the value and the type of the operands, which helps prevent unexpected type coercion behavior:

console.log(1 == "1");  // true
console.log(1 === "1"); // false

console.log(1 != "1");  // false  
console.log(1 !== "1"); // true

In general, it‘s safer to use === and !== instead of == and != to avoid bugs caused by type coercion.

4. Logical Operators

Logical operators allow you to combine multiple conditions and determine the logical relationship between them. JavaScript has three logical operators:

  • Logical AND (&&)
  • Logical OR (||)
  • Logical NOT (!)

The && operator returns true if both operands are true, otherwise it returns false:

console.log(true && true);   // true
console.log(true && false);  // false
console.log(false && true);  // false
console.log(false && false); // false  

The || operator returns true if at least one operand is true:

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

The ! operator negates the value of its operand:

console.log(!true);  // false
console.log(!false); // true  

Logical operators are often used in conditional statements to make decisions based on multiple conditions:

let hour = 12; 
let isWeekend = true;

if(hour < 18 && !isWeekend) {
  console.log("Good day!");
} 

One thing to keep in mind is the concept of "short-circuiting". When using && and ||, JavaScript evaluates the operands from left to right and stops as soon as the result is determined:

console.log(null && undefined); // null
console.log(1 || 2 || 3); // 1  

5. Ternary Operator

The ternary operator (also called the conditional operator) is the only JavaScript operator that takes three operands. It provides a concise way to write simple if-else statements in a single line:

condition ? expression1 : expression2

If the condition evaluates to true, expression1 is executed and becomes the result. If the condition is false, expression2 is executed and becomes the result.

let age = 25;
let canDrink = age >= 21 ? "Yes" : "No";
console.log(canDrink); // "Yes"

While the ternary operator can make your code more compact, it‘s best to avoid nesting multiple ternary operators, as it can quickly become difficult to read and understand. If you find yourself with a complex ternary expression, it‘s often better to use a regular if-else statement for clarity.

6. typeof Operator

The typeof operator returns a string indicating the type of the operand. It supports the following return values: "undefined", "boolean", "number", "string", "object", "function", and "symbol".

console.log(typeof 42);           // "number"
console.log(typeof "Hello");      // "string"  
console.log(typeof true);         // "boolean"
console.log(typeof {});           // "object"
console.log(typeof []);           // "object"
console.log(typeof function(){}); // "function"
console.log(typeof undefined);    // "undefined"
console.log(typeof null);         // "object" (this is considered a bug)

The typeof operator is useful for checking the type of a variable before performing operations on it, which can help prevent errors. However, keep in mind that typeof null returns "object", which is a well-known JavaScript quirk.

7. Bitwise Operators

Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones) and perform actions on them. While they‘re not as commonly used as the other operators we‘ve covered, they can be useful for certain low-level tasks. JavaScript supports the following bitwise operators:

  • Bitwise AND (&)
  • Bitwise OR (|)
  • Bitwise XOR (^)
  • Bitwise NOT (~)
  • Left shift (<<)
  • Right shift (>>)
  • Unsigned right shift (>>>)

Here are some examples:

console.log(5 & 3);  // 1
console.log(5 | 3);  // 7
console.log(5 ^ 3);  // 6
console.log(~5);     // -6
console.log(5 << 1); // 10
console.log(5 >> 1); // 2
console.log(-5 >>> 1); // 2147483645  

Unless you‘re working with binary data or doing bit manipulation, you likely won‘t need to use bitwise operators very often in day-to-day JavaScript programming.

Conclusion

In this comprehensive guide, we‘ve explored the 7 categories of operators in JavaScript: arithmetic, assignment, comparison, logical, ternary, typeof, and bitwise. Each category serves a specific purpose and understanding how to use them is essential for writing effective JavaScript code.

Remember that operators follow a precedence order, so it‘s important to use parentheses to explicitly define the order of operations when it‘s not obvious. It‘s also critical to understand the difference between == and === to avoid unexpected type coercion issues.

As you continue your JavaScript journey, you‘ll find yourself using these operators constantly. Take the time to practice using them in different contexts and pay attention to how they behave. With a solid grasp of JavaScript‘s operators, you‘ll be able to write more concise, expressive, and error-free code. Happy coding!

Similar Posts