JavaScript Operators

JavaScript Operators

Understand how JavaScript operators work with real-world explanations.

In JavaScript, an operator is a special symbol or keyword that performs an operation on one or more values, known as operands. Operators form the foundation of JavaScript programming and are essential for performing calculations, evaluating conditions, manipulating data, and controlling the flow of execution in an application.

Whether you are writing simple scripts or developing complex, large-scale web applications, JavaScript operators enable you to write clean, efficient, and expressive code. A solid understanding of operators is critical for every JavaScript developer, from beginners learning the basics to professionals building production-ready systems.

Types of JavaScript Operators

JavaScript provides a rich set of operators that allow developers to perform different types of operations efficiently. Understanding these operator categories will help you write more readable, maintainable, and performant JavaScript code.

  • Arithmetic Operators – Used to perform mathematical operations such as addition, subtraction, multiplication, division, and modulus.
  • Assignment Operators – Used to assign values to variables, including shorthand and compound assignments like +=, -=, and *=.
  • Comparison Operators – Used to compare two values and return a boolean result (true or false) based on the comparison.
  • Logical Operators – Used to combine multiple conditions and control program logic using operators such as &&, ||, and !.
  • Bitwise Operators – Perform operations on binary representations of numbers and are typically used in low-level programming and performance-critical scenarios.
  • Ternary Operator – A concise conditional operator that allows you to write simple if-else logic in a single expression.
  • String Operators – Primarily used to concatenate or combine strings, most commonly using the + operator.
  • Typeof Operator – Used to determine the data type of a variable or value at runtime, which is helpful for debugging and type checking.
  • Spread and Rest Operator – Used to expand arrays or objects into individual elements (spread syntax) and to collect multiple function arguments into a single array (rest syntax), improving flexibility and code readability.

Arithmetic Operators in JavaScript

In JavaScript, arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. These operators work primarily with numeric values and are fundamental to building calculations, counters, formulas, and core program logic.

Operator Description Example
+ Adds two numeric values 10 + 2 // 12
- Subtracts one value from another 10 - 2 // 8
* Multiplies two values 5 * 2 // 10
/ Divides one value by another 10 / 2 // 5
% Returns the remainder of a division 5 % 2 // 1
++ Increases a numeric value by one ++3 // 4
-- Decreases a numeric value by one --3 // 2

Example: Using Arithmetic Operators in JavaScript

JavaScript Example

// Arithmetic Operators Example
const add = 6 + 4;      // Addition
const sub = 10 - 3;     // Subtraction
const mul = 5 * 4;      // Multiplication
const div = 20 / 5;     // Division
const mod = 9 % 2;      // Modulus

console.log(add, sub, mul, div, mod);
        
Try it Yourself »

In this example, arithmetic operators are used to perform standard mathematical calculations in JavaScript. The computed results are displayed in the browser console using console.log(). Arithmetic operators are commonly used in real-world applications such as counters, pricing calculations, form validation, and financial or statistical logic.

Assignment Operators in JavaScript

Assignment operators in JavaScript are used to assign values to variables. In addition to simple assignment, these operators can combine arithmetic operations (such as addition, subtraction, or multiplication) with assignment in a single statement. This makes the code more concise, readable, and efficient.

Operator Description Example
= Assigns the value of the right-hand expression to the variable on the left a = b + c
+= Adds the right operand to the variable and assigns the result a += b // a = a + b
-= Subtracts the right operand from the variable and assigns the result a -= b // a = a - b
*= Multiplies the variable by the right operand and assigns the result a *= b // a = a * b
/= Divides the variable by the right operand and assigns the result a /= b // a = a / b
%= Calculates the remainder and assigns it to the variable a %= b // a = a % b

Example: Using Assignment Operators in JavaScript

JavaScript Example

// Assignment Operators Example
let a = 20;

a += 2;   // a becomes 22
a *= 3;   // a becomes 66

console.log(a);
        
Try it Yourself »

In this example, the = operator assigns an initial value to the variable. The += operator increases the value, while *= multiplies it and stores the updated result back in the same variable. Assignment operators are commonly used in loops, counters, calculations, and real-world application logic.

Comparison Operators in JavaScript

Comparison operators in JavaScript are used to compare two values and return a Boolean result (true or false). These operators play a crucial role in decision-making and are commonly used in conditional statements such as if, else, and loops.

Operator Description Example
== Compares two values for equality after type conversion (loose comparison) 2 == 2 // true
!= Checks whether two values are not equal (type conversion allowed) 2 != 3 // true
> Determines whether the left value is greater than the right value 3 > 4 // false
< Determines whether the left value is less than the right value 4 < 5 // true
>= Checks whether the left value is greater than or equal to the right value 3 >= 3 // true
<= Checks whether the left value is less than or equal to the right value 3 <= 2 // false
=== Compares both value and data type for equality (strict comparison) 2 === "2" // false
!== Checks whether the value or data type is different (strict inequality) 2 !== "2" // true

Example: Using Comparison Operators in JavaScript

JavaScript Example

// Comparison Operators Example
let a = 3;
let b = 5;

let result = a < b;

console.log(result);
        
Try it Yourself »

In this example, the less-than operator (<) compares the values of a and b. Since 3 is less than 5, the expression evaluates to true, which is then printed to the console. Comparison operators like these are essential for implementing conditions and control flow in JavaScript applications.

Logical Operators in JavaScript

Logical operators in JavaScript are used to evaluate and combine Boolean expressions. They allow you to work with multiple conditions at the same time and are essential for controlling program flow. Logical operators are widely used in conditional statements such as if, else, and loops to make decisions based on dynamic conditions.

Operator Description Example
&& Returns true if all conditions evaluate to true (a > 0 && b > 0)
|| Returns true if at least one condition evaluates to true (a > 0 || b > 0)
! Negates a Boolean value by reversing its logical state !isLoggedIn

Example: Using Logical Operators in JavaScript

JavaScript Example

// Logical Operators Example
const p = true;
const q = false;

console.log(p && q); // false
console.log(p || q); // true
console.log(!p);     // false
        
Try it Yourself »

In this example, the logical AND operator (&&) returns false because both conditions are not true. The logical OR operator (||) returns true because at least one condition evaluates to true. The logical NOT operator (!) inverts the Boolean value, turning true into false and vice versa. Logical operators like these are fundamental for implementing complex conditions and decision-making logic in JavaScript applications.

Bitwise Operators in JavaScript

Bitwise operators in JavaScript are used to perform operations on the binary (bit-level) representation of numbers. Internally, JavaScript converts numbers to 32-bit signed integers before applying these operations. Bitwise operators are primarily used in low-level programming, performance optimization, data manipulation, and advanced mathematical or algorithmic tasks.

Operator Description Example
& Performs a bitwise AND operation on corresponding bits 5 & 3 // 1
| Performs a bitwise OR operation on corresponding bits 5 | 3 // 7
^ Performs a bitwise XOR operation (sets the bit if values differ) 5 ^ 3 // 6
~ Inverts all bits (bitwise NOT operator) ~5 // -6
<< Shifts bits to the left by a specified number of positions 5 << 1 // 10
>> Shifts bits to the right while preserving the sign bit -10 >> 1 // -5
>>> Performs a zero-fill right shift (fills left bits with zeros) -10 >>> 1 // 2147483643

Example: Using Bitwise Operators in JavaScript

JavaScript Example

// Bitwise Operators Example
console.log(3 & 1);
        
Try it Yourself »

In this example, both numbers are first converted into their binary representations. The number 3 becomes 011, and 1 becomes 001. When the bitwise AND operator (&) is applied, only the bits that are 1 in both values remain set. The result is 001, which equals 1 in decimal form.

Ternary Operator in JavaScript

The ternary operator in JavaScript is a concise way to write conditional logic in a single expression. It takes three operands and is therefore also known as the conditional operator. The ternary operator evaluates a condition and returns one of two values, depending on whether the condition is true or false.

Syntax:
condition ? expression1 : expression2
Part Description
condition A Boolean expression that is evaluated first
expression1 The value returned if the condition evaluates to true
expression2 The value returned if the condition evaluates to false

Example: Using the Ternary Operator in JavaScript

JavaScript Example

// Ternary Operator Example
const age = 10;
const status = age >= 18 ? "Adult" : "Minor";
console.log(status);
        
Try it Yourself »

In this example, the condition age >= 18 is evaluated first. Because the value of age is 10, the condition evaluates to false. As a result, the second expression ("Minor") is returned and printed to the console. The ternary operator is especially useful for simple conditional assignments where a full if-else statement would be unnecessary.

String Operators in JavaScript

String operators in JavaScript are used to work with text-based values. They allow developers to combine, append, and dynamically build strings. JavaScript primarily uses the + operator to perform string concatenation, making it easy to construct readable messages and formatted output.

Example:
"Hello" + " World" // "Hello World"
Operator Description Example
+ Concatenates two or more strings into a single string "Hello" + " World" // "Hello World"
+= Appends a string to an existing string variable and assigns the updated value back to the same variable text += " JS"; // "Hello JS"

Example: JavaScript String Operators

JavaScript Example

// String Operators Example
let greeting = "Hello";
greeting += " JavaScript";

console.log(greeting);
        
Try it Yourself »

The + operator combines multiple strings into one, a process known as string concatenation. The += operator provides a shorthand way to append additional text to an existing string variable. These operators are widely used for generating dynamic content, formatting output, and constructing user-facing messages in JavaScript applications.

Type Operators in JavaScript

Type operators in JavaScript are used to identify the data type of a value or to determine whether an object was created from a specific class or constructor. These operators play a critical role in type checking, data validation, debugging, and writing reliable conditional logic in modern JavaScript applications.

Operator Description Example
typeof Returns the data type of a variable or value as a string, such as "string", "number", "boolean", or "object" typeof "Hello" // "string"
instanceof Checks whether an object belongs to a specific class or constructor by examining its prototype chain arr instanceof Array // true

Example: JavaScript Type Operators

JavaScript Example

// Type Operators Example
let text = "JavaScript";
let number = 100;
let list = [1, 2, 3];

console.log(typeof text);       // "string"
console.log(typeof number);     // "number"
console.log(list instanceof Array); // true
        
Try it Yourself »

The typeof operator is used to identify the primitive type of a value at runtime. It is commonly used to ensure that variables contain the expected data type before performing operations on them.

The instanceof operator, on the other hand, checks whether an object was created using a particular constructor or class. This is especially useful when working with arrays, objects, classes, and custom data structures, helping developers write safer and more predictable JavaScript code.

Spread & Rest Operators in JavaScript

The spread and rest operators were introduced in ES6 (ECMAScript 2015) to make JavaScript code more concise, readable, and maintainable. Both operators use the same syntax (...), but their behavior depends on the context in which they are used. They are widely used when working with arrays, objects, and function parameters.

Operator Purpose Usage Example
Spread (...) Expands an array or object into individual elements or properties let copy = [...arr];
Rest (...) Collects multiple values into a single array function sum(...nums) { }

Spread Operator (...)

The spread operator is used to expand an iterable (such as an array or object) into individual values. It is commonly used to copy arrays, merge arrays or objects, and pass multiple values as function arguments. The spread operator helps prevent unintended changes by creating a shallow copy instead of modifying the original data.

Example: Using the Spread Operator

JavaScript Example

// Spread Operator Example
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];

console.log(newArr);
        
Try it Yourself »

In this example, the spread operator expands the elements of arr into a new array. This approach ensures that the original array remains unchanged, making the code safer and easier to maintain.

Rest Operator (...)

The rest operator is used to gather multiple values into a single array. It is most commonly used in function parameters when the number of arguments passed to a function is unknown or flexible. This makes functions more adaptable and easier to reuse.

Example: Using the Rest Operator

JavaScript Example

// Rest Operator Example
function sum(...nums) {
    return nums.reduce((total, value) => total + value, 0);
}

console.log(sum(10, 20, 30));
        
Try it Yourself »

In this example, the rest operator collects all the values passed to the function into the nums array. The reduce() method then processes the array and calculates the total sum. This pattern is commonly used in real-world JavaScript applications such as calculators, analytics tools, and data processing utilities.