JavaScript Operators: Complete Guide with Examples

Learn JavaScript operators with clear examples. Understand arithmetic, assignment, comparison, logical, unary, bitwise, ternary, nullish, and optional chaining operators.

JavaScript Operators

JavaScript operators are special symbols and keywords used to perform operations on values and variables. They allow you to calculate numbers, compare values, combine conditions, assign data, work with objects, test data types, and perform many other tasks.

For example:

let a = 10;
let b = 5;

let sum = a + b;

console.log(sum); // 15

Here, + is an operator. It adds the values of a and b.

Operators are one of the most important parts of JavaScript because almost every useful program needs them. Whether you are building a calculator, validating a form, making decisions with if statements, updating variables, or working with objects, you will use operators frequently.

Why Are JavaScript Operators Important?

Operators make it possible to manipulate and evaluate data.

They are commonly used to:

  • Perform mathematical calculations
  • Assign values to variables
  • Compare values
  • Make logical decisions
  • Combine conditions
  • Increase or decrease values
  • Check data types
  • Work with objects and properties
  • Handle optional or missing values
  • Perform bit-level operations
  • Control program flow
  • Create conditional expressions

Consider this example:

let age = 20;

if (age >= 18) {
    console.log("Adult");
}

The >= operator compares age with 18. JavaScript then uses the resulting Boolean value to determine whether the condition is true.

Types of JavaScript Operators

JavaScript provides many types of operators. The major categories include:

  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Unary operators
  6. Increment and decrement operators
  7. Bitwise operators
  8. String operators
  9. Conditional or ternary operator
  10. Nullish coalescing operator
  11. Optional chaining operator
  12. Relational operators
  13. Exponentiation operator
  14. Spread and rest syntax
  15. typeof and delete operators
  16. in and instanceof operators

Some operators can belong to more than one conceptual category depending on how they are used.


Arithmetic Operators

Arithmetic operators are used to perform mathematical operations.

Addition +

The + operator adds two numbers.

let a = 10;
let b = 20;

console.log(a + b); // 30

The + operator can also concatenate strings.

let firstName = "Dibya";
let lastName = "Mendali";

console.log(firstName + " " + lastName);

Output:

Dibya Mendali

This is an important feature of JavaScript because + can perform either numeric addition or string concatenation depending on the operands.

Subtraction -

The - operator subtracts one value from another.

let a = 20;
let b = 8;

console.log(a - b); // 12

Multiplication *

The * operator multiplies values.

let price = 100;
let quantity = 3;

console.log(price * quantity); // 300

Division /

The / operator divides one value by another.

let total = 100;
let people = 4;

console.log(total / people); // 25

JavaScript uses floating-point numbers, so division does not necessarily produce an integer.

console.log(7 / 2); // 3.5

Remainder %

The % operator returns the remainder after division.

console.log(10 % 3); // 1

It is useful for checking whether a number is even or odd.

let number = 8;

console.log(number % 2 === 0); // true

Exponentiation **

The ** operator raises a number to a power.

console.log(2 ** 3); // 8

It is equivalent to raising 2 to the third power.

2 * 2 * 2


Assignment Operators

Assignment operators store values in variables.

Simple Assignment =

The = operator assigns a value.

let name = "Dibya";

It is important to understand that = does not mean “equal to” in the mathematical sense. It means “assign this value.”

Addition Assignment +=

let score = 10;

score += 5;

console.log(score); // 15

This is equivalent to:

score = score + 5;

Subtraction Assignment -=

let score = 20;

score -= 5;

console.log(score); // 15

Equivalent to:

score = score - 5;

Multiplication Assignment *=

let price = 10;

price *= 3;

console.log(price); // 30

Division Assignment /=

let amount = 100;

amount /= 4;

console.log(amount); // 25

Remainder Assignment %=

let number = 10;

number %= 3;

console.log(number); // 1

Exponentiation Assignment **=

let number = 2;

number **= 4;

console.log(number); // 16

Bitwise Assignment Operators

JavaScript also supports assignment forms of bitwise operators:

&=
|=
^=
<<=
>>=
>>>=

For example:

let x = 5;

x &= 3;

These are mainly useful in specialized programming involving binary data and low-level operations.

Logical Assignment Operators

Modern JavaScript also provides:

&&=
||=
??=

For example:

let username = "";

username ||= "Guest";

console.log(username); // Guest

The ||= operator assigns the right-hand value when the left-hand value is falsy.

Another example:

let count = 10;

count &&= 20;

console.log(count); // 20

And:

let value = null;

value ??= 100;

console.log(value); // 100


Comparison Operators

Comparison operators compare values and produce a Boolean result: true or false.

Equal ==

The == operator checks equality after allowing type conversion when necessary.

console.log(5 == "5"); // true

Although this behavior can sometimes be useful, it may also produce unexpected results.

Strict Equal ===

The === operator checks both value and type.

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

In modern JavaScript, === is generally preferred when you want predictable equality comparisons.

Not Equal !=

The != operator checks whether values are different, with type conversion possible.

console.log(5 != "6"); // true

Strict Not Equal !==

The !== operator checks whether either the value or type is different.

console.log(5 !== "5"); // true

Greater Than >

console.log(10 > 5); // true

Less Than <

console.log(3 < 8); // true

Greater Than or Equal >=

console.log(10 >= 10); // true

Less Than or Equal <=

console.log(8 <= 10); // true


== vs ===

One of the most important concepts for JavaScript beginners is the difference between loose equality and strict equality.

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

With ==, JavaScript may convert one value before comparing.

With ===, JavaScript does not perform that kind of implicit type conversion.

For predictable code, especially in larger applications, === and !== are usually the better choices.


Logical Operators

Logical operators are used to combine or manipulate Boolean expressions.

The main logical operators are:

  • && — logical AND
  • || — logical OR
  • ! — logical NOT
  • ?? — nullish coalescing

Logical AND &&

&& evaluates expressions from left to right and returns a falsy value as soon as one is found. Otherwise, it returns the last value.

let age = 25;
let hasID = true;

console.log(age >= 18 && hasID); // true

Both conditions need to be truthy for the overall condition to be truthy.

A common example:

if (age >= 18 && hasID) {
    console.log("Access allowed");
}

Logical OR ||

The || operator returns the first truthy value it encounters. If none is truthy, it returns the final value.

let username = "";

let displayName = username || "Guest";

console.log(displayName); // Guest

It is often used for fallback values, although ?? may be more appropriate when you only want to handle null and undefined.

Logical NOT !

The ! operator reverses the Boolean interpretation of a value.

let loggedIn = true;

console.log(!loggedIn); // false

Another example:

if (!loggedIn) {
    console.log("Please log in.");
}


Nullish Coalescing Operator ??

The ?? operator returns the right-hand value only when the left-hand value is null or undefined.

let username = null;

let name = username ?? "Guest";

console.log(name); // Guest

The difference between || and ?? is important.

let count = 0;

console.log(count || 10); // 10
console.log(count ?? 10); // 0

0 is falsy, so || uses 10.

But 0 is not nullish, so ?? keeps 0.

This makes ?? useful when values such as 0, false, or an empty string are valid and should not be replaced.


Conditional or Ternary Operator

The conditional operator is the only JavaScript operator that takes three operands.

Its syntax is:

condition ? valueIfTrue : valueIfFalse

Example:

let age = 20;

let status = age >= 18 ? "Adult" : "Minor";

console.log(status); // Adult

It can be a concise alternative to a simple if...else statement.

Instead of:

let message;

if (age >= 18) {
    message = "Adult";
} else {
    message = "Minor";
}

You can write:

let message = age >= 18 ? "Adult" : "Minor";

However, deeply nested ternary expressions can make code difficult to read. Use them mainly for simple decisions.


Increment Operator ++

The ++ operator increases a numeric value by one.

let count = 5;

count++;

console.log(count); // 6

There are two forms.

Post-increment

let x = 5;

let y = x++;

console.log(x); // 6
console.log(y); // 5

The original value is used first, then x is increased.

Pre-increment

let x = 5;

let y = ++x;

console.log(x); // 6
console.log(y); // 6

The value is increased first, and then the new value is used.


Decrement Operator --

The -- operator decreases a numeric value by one.

let count = 5;

count--;

console.log(count); // 4

Like ++, it has pre-decrement and post-decrement forms.

let x = 5;

console.log(x--); // 5
console.log(x);   // 4

And:

let y = 5;

console.log(--y); // 4
console.log(y);   // 4


Unary Operators

A unary operator works with a single operand.

Examples include:

typeof
delete
void
+
-
!
~

Unary Plus +

The unary + attempts to convert a value to a number.

console.log(+"10"); // 10

Another example:

let value = "25";

console.log(+value); // 25

Be careful because conversion can produce NaN.

console.log(+"hello"); // NaN

Unary Minus -

The unary - converts a value to a number and negates it.

console.log(-10); // -10
console.log(-"10"); // -10

Logical NOT !

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

Bitwise NOT ~

The ~ operator performs a bitwise NOT operation.

console.log(~5);

It is primarily used in specialized bitwise operations and can be confusing for beginners.


typeof Operator

The typeof operator returns a string describing the type of a value.

console.log(typeof 10);        // "number"
console.log(typeof "Hello");   // "string"
console.log(typeof true);      // "boolean"
console.log(typeof undefined); // "undefined"

It is frequently used when checking the type of a value.

One important JavaScript behavior is:

console.log(typeof null); // "object"

This is a long-standing JavaScript language behavior. It does not mean that null is actually an ordinary object.

For functions:

console.log(typeof function () {}); // "function"


delete Operator

The delete operator removes a property from an object.

let user = {
    name: "Dibya",
    age: 25
};

delete user.age;

console.log(user);

After deletion, the age property no longer exists on that object.

console.log("age" in user); // false

delete should not be confused with deleting variables themselves. Its most common use is removing object properties.


in Operator

The in operator checks whether a property exists in an object or along its prototype chain.

let user = {
    name: "Dibya",
    age: 25
};

console.log("name" in user); // true
console.log("email" in user); // false

It checks property existence, not whether the property’s value is truthy.

let data = {
    value: undefined
};

console.log("value" in data); // true

The property exists even though its value is undefined.


instanceof Operator

The instanceof operator checks whether an object is an instance of a particular constructor or class according to the prototype chain.

let numbers = [1, 2, 3];

console.log(numbers instanceof Array); // true

Another example:

class Person {}

let person = new Person();

console.log(person instanceof Person); // true

It is useful when working with classes and object types, but it should not be treated as a universal type-checking mechanism.


Bitwise Operators

Bitwise operators work with the binary representation of numbers.

The main bitwise operators are:

&   AND
|   OR
^   XOR
~   NOT
<<  Left shift
>>  Sign-propagating right shift
>>> Zero-fill right shift

Bitwise AND &

console.log(5 & 3); // 1

In binary:

5 = 101
3 = 011
    ---
    001

The result is 1.

Bitwise OR |

console.log(5 | 3); // 7

Bitwise XOR ^

XOR returns a bit set when the corresponding bits are different.

console.log(5 ^ 3); // 6

Bitwise NOT ~

console.log(~5); // -6

Left Shift <<

The left-shift operator moves bits to the left.

console.log(5 << 1); // 10

Right Shift >>

The right-shift operator shifts bits to the right while preserving the sign.

console.log(10 >> 1); // 5

Unsigned Right Shift >>>

The >>> operator shifts bits to the right and fills the left side with zeros.

console.log(10 >>> 1); // 5

Bitwise operators are less common in everyday web development but are useful for certain algorithms, binary data processing, flags, and performance-oriented tasks.


String Operators

JavaScript uses the + operator for string concatenation.

let first = "Hello";
let second = "World";

console.log(first + " " + second);

Output:

Hello World

The += operator can also concatenate strings.

let message = "Hello";

message += " JavaScript";

console.log(message); // Hello JavaScript

For modern code, template literals are often easier to read:

let name = "Dibya";

console.log(`Hello, ${name}!`);


Optional Chaining Operator ?.

Optional chaining allows you to safely access a property, method, or element when an earlier value may be null or undefined.

Without optional chaining:

let user = null;

console.log(user.profile.name);

This causes an error because user is null.

With optional chaining:

console.log(user?.profile?.name);

The result is:

undefined

Optional chaining can also be used with methods:

user?.login?.();

And with array or object properties:

let users = [];

console.log(users?.[0]?.name);

It is particularly useful when working with data received from APIs.


Spread Syntax ...

The spread syntax uses three dots and expands an iterable or object into individual elements or properties.

For arrays:

let first = [1, 2, 3];
let second = [...first, 4, 5];

console.log(second);

Output:

[1, 2, 3, 4, 5]

For objects:

let user = {
    name: "Dibya",
    age: 25
};

let updatedUser = {
    ...user,
    city: "Bhubaneswar"
};

Spread syntax is not technically an operator in the same sense as + or ===, but it is commonly discussed alongside JavaScript operators because of its ... syntax and behavior.


Rest Syntax ...

The same ... syntax can be used as rest syntax in function parameters, destructuring, and related contexts.

Example:

function add(...numbers) {
    return numbers.reduce((total, number) => total + number, 0);
}

console.log(add(1, 2, 3, 4)); // 10

Here, ...numbers collects multiple arguments into an array.

Spread expands values, while rest collects values.


Operator Precedence

JavaScript operators have different precedence levels. Precedence determines which operation is performed first.

For example:

let result = 10 + 5 * 2;

console.log(result); // 20

The multiplication occurs before addition.

Conceptually:

10 + (5 * 2)

not:

(10 + 5) * 2

Parentheses can be used to make the intended order explicit.

let result = (10 + 5) * 2;

console.log(result); // 30

Using parentheses can improve readability even when you already know the precedence rules.


Associativity

When operators have the same precedence, associativity determines the direction in which they are evaluated.

Many operators are left-associative.

For example:

let result = 20 - 5 - 3;

This is evaluated as:

(20 - 5) - 3

Some operators, such as assignment and exponentiation, have right-to-left associativity.

For example:

let a, b, c;

a = b = c = 10;

This works from right to left.


Short-Circuit Evaluation

JavaScript logical operators can stop evaluating as soon as the final result is known.

With &&:

false && someFunction();

If the first value is falsy, JavaScript does not need to evaluate the second operand.

With ||:

true || someFunction();

The second operand is not evaluated because the result is already known to be truthy.

This behavior is called short-circuit evaluation.

It can be useful:

let user = null;

user && console.log(user.name);

However, modern JavaScript often provides clearer alternatives such as optional chaining:

console.log(user?.name);


Truthy and Falsy Values

Logical operators rely heavily on JavaScript’s concept of truthiness.

Values that are treated as falsy include:

false
0
-0
0n
""
null
undefined
NaN

Most other values are truthy, including:

[]
{}
"0"
"false"

For example:

if ("Hello") {
    console.log("This runs");
}

An empty array is also truthy:

if ([]) {
    console.log("This also runs");
}

Understanding truthy and falsy values is essential when using &&, ||, !, ??, and conditional expressions.


Operator Examples in Real Programs

Operators become easier to understand when they are used in practical situations.

Calculating a Shopping Total

let price = 500;
let quantity = 3;

let total = price * quantity;

console.log(total); // 1500

Applying a Discount

let price = 1000;
let discount = 10;

let finalPrice = price - (price * discount / 100);

console.log(finalPrice); // 900

Checking Eligibility

let age = 21;

if (age >= 18) {
    console.log("Eligible");
} else {
    console.log("Not eligible");
}

Combining Conditions

let age = 25;
let hasPermission = true;

if (age >= 18 && hasPermission) {
    console.log("Allowed");
}

Providing a Default Value

let language;

let selectedLanguage = language ?? "English";

console.log(selectedLanguage); // English

Safely Accessing Nested Data

let response = {
    user: {
        profile: {
            name: "Dibya"
        }
    }
};

console.log(response.user?.profile?.name);


Common Mistakes With JavaScript Operators

Mistaking = for ===

Incorrect when you intend to compare:

if (age = 18) {
    // ...
}

Use:

if (age === 18) {
    // ...
}

Assignment changes a variable. Comparison checks a relationship.

Using == Without Understanding Type Conversion

console.log(0 == false); // true

This can be surprising.

Strict comparison is usually clearer:

console.log(0 === false); // false

Confusing || With ??

Consider:

let count = 0;

let value = count || 10;

The result is 10.

If 0 is a valid value, this may be incorrect.

Use:

let value = count ?? 10;

Now the result is 0.

Overusing Ternary Operators

This is difficult to read:

let result = condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4;

For complex decisions, an if...else if...else structure is often easier to understand.

Forgetting Operator Precedence

This:

let result = a + b * c;

is not the same as:

let result = (a + b) * c;

When an expression is complicated, parentheses can make your intention clearer.


JavaScript Operator Precedence: A Practical View

A simplified precedence order, from higher to lower, includes categories such as:

CategoryExamples
Grouping()
Member access., ?., []
new and function callsnew, ()
Increment/decrement++, --
Unary!, typeof, delete, unary +, unary -
Exponentiation**
Multiplication/division*, /, %
Addition/subtraction+, -
Shifts<<, >>, >>>
Relational<, >, <=, >=, in, instanceof
Equality==, !=, ===, !==
Bitwise AND&
Bitwise XOR^
Bitwise OR`
Logical AND&&
Logical OR`
Nullish coalescing??
Conditional? :
Assignment=, +=, -=, ??=, etc.
Comma,

This is only a practical overview rather than a complete specification table. When an expression is difficult to read, parentheses are usually the safest way to communicate intent.


Special Behavior of the + Operator

The + operator deserves special attention because it can perform both numeric addition and string concatenation.

For example:

console.log(10 + 20); // 30

But:

console.log("10" + 20); // "1020"

JavaScript converts the number to a string and performs concatenation.

Another example:

console.log(10 + "20" + 30); // "102030"

Once string concatenation begins, subsequent + operations can produce strings.

Parentheses can make your intention clear:

console.log(10 + (20 + 30)); // 60


Operators and Type Conversion

Some JavaScript operators can trigger implicit type conversion.

For example:

console.log("5" - 2); // 3

The string "5" is converted to a number.

But:

console.log("5" + 2); // "52"

The + operator behaves differently because it can concatenate strings.

This is one reason developers should understand JavaScript’s type coercion rules rather than relying on assumptions.


NaN and Operators

NaN means “Not-a-Number.” It represents an invalid or undefined numeric result.

For example:

console.log("hello" * 5); // NaN

An important detail is that:

NaN === NaN

is:

false

To check for NaN, use:

Number.isNaN(value);

For example:

console.log(Number.isNaN(NaN)); // true


BigInt and Operators

JavaScript also supports BigInt for integers that are larger than the safe integer range of ordinary Number values.

Example:

let bigNumber = 123456789012345678901234567890n;

console.log(bigNumber);

Many arithmetic operators work with BigInt values:

console.log(10n + 20n); // 30n

However, you generally cannot mix BigInt and Number values directly in arithmetic.

This causes an error:

10n + 20

Instead, use values of compatible types:

10n + 20n

or:

Number(10n) + 20

when conversion is appropriate.


Modern JavaScript Operators and Syntax

Modern JavaScript has introduced several useful operators and operator-like syntaxes that make code safer and shorter.

Important examples include:

?.
??
&&=
||=
??=
...

These features are especially useful when handling optional data, defaults, objects, arrays, and function arguments.

For example:

const city = user?.address?.city ?? "Unknown";

This single expression safely accesses nested properties and provides a default when the final result is nullish.


Best Practices for Using JavaScript Operators

Prefer strict equality

In most situations, use:

===
!==

instead of:

==
!=

unless you intentionally want JavaScript’s coercion behavior.

Use parentheses for clarity

Even when you know the precedence rules, parentheses can make expressions easier for other developers to understand.

let total = price + (tax * quantity);

Avoid unnecessarily complicated expressions

Instead of putting many operations into one line, break complicated calculations into meaningful variables.

Use ?? when only nullish values should trigger a fallback

let value = input ?? defaultValue;

This preserves valid falsy values such as 0 and false.

Use optional chaining for potentially missing properties

const name = user?.profile?.name;

This is usually clearer than manually checking every object level.

Be careful with implicit conversion

Expressions such as:

"10" - 5

work because JavaScript performs conversion. But relying heavily on implicit conversion can make code harder to understand.

Do not overuse bitwise operators

Bitwise operators are powerful but are rarely necessary for ordinary application code.

Keep ternary expressions simple

Use the conditional operator when it improves readability, not merely because it produces shorter code.


Quick JavaScript Operators Reference

OperatorPurposeExample
+Addition / concatenationa + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Remaindera % b
**Exponentiationa ** b
=Assignmenta = b
+=Add and assigna += b
-=Subtract and assigna -= b
*=Multiply and assigna *= b
/=Divide and assigna /= b
%=Remainder and assigna %= b
**=Exponentiate and assigna **= b
==Loose equalitya == b
===Strict equalitya === b
!=Loose inequalitya != b
!==Strict inequalitya !== b
>Greater thana > b
<Less thana < b
>=Greater than or equala >= b
<=Less than or equala <= b
&&Logical ANDa && b
``
!Logical NOT!a
??Nullish fallbacka ?? b
++Incrementa++
--Decrementa--
&Bitwise ANDa & b
``Bitwise OR
^Bitwise XORa ^ b
~Bitwise NOT~a
<<Left shifta << b
>>Right shifta >> b
>>>Unsigned right shifta >>> b
?:Conditionala ? b : c
typeofGet typetypeof a
deleteRemove propertydelete obj.a
inCheck property existence"a" in obj
instanceofCheck prototype relationshipobj instanceof Class
?.Optional chainingobj?.name

Frequently Asked Questions

What is an operator in JavaScript?

An operator is a symbol or keyword that tells JavaScript to perform an operation on one or more values.

Example:

10 + 5

Here, + is the operator.

How many types of operators are there in JavaScript?

JavaScript has many operator categories, including arithmetic, assignment, comparison, logical, unary, bitwise, conditional, relational, nullish, and optional chaining operators. Some newer syntaxes, such as spread and rest, are commonly taught alongside operators.

What is the difference between = and ===?

= assigns a value.

let x = 10;

=== compares values and types.

x === 10

What is the difference between == and ===?

== allows type coercion during comparison, while === performs strict comparison without that implicit conversion.

5 == "5"   // true
5 === "5"  // false

What does % do in JavaScript?

The % operator returns the remainder of a division.

10 % 3 // 1

What does && mean?

&& is the logical AND operator. It evaluates operands from left to right and can be used to require multiple conditions to be truthy.

What does || mean?

|| is the logical OR operator. It returns the first truthy operand, or the final operand if none is truthy.

What does ?? mean?

?? is the nullish coalescing operator. It provides a fallback only when the left side is null or undefined.

What does ?. mean?

?. is optional chaining. It allows JavaScript to safely access properties or methods when an earlier value may be null or undefined.

What is the ternary operator?

The ternary operator is JavaScript’s conditional operator:

condition ? value1 : value2

It is useful for short conditional expressions.

What is operator precedence?

Operator precedence determines which operators are evaluated first in an expression.

For example:

2 + 3 * 4

is evaluated as:

2 + (3 * 4)

because multiplication has higher precedence than addition.

Conclusion

JavaScript operators are fundamental building blocks of the language. They allow developers to calculate values, assign data, compare expressions, make decisions, manipulate objects, work with Boolean logic, handle missing data, and perform specialized operations.

The most frequently used operators include arithmetic operators such as +, -, *, /, and %; comparison operators such as ===, !==, >, and <; logical operators such as &&, ||, and !; and assignment operators such as =, +=, and -=.

Modern JavaScript also provides powerful features such as optional chaining ?., nullish coalescing ??, and logical assignment operators such as ??= and ||=. Understanding these operators helps you write code that is shorter, safer, and easier to maintain.

For beginners, the best approach is to first become comfortable with arithmetic, assignment, comparison, and logical operators. Then learn operator precedence, type coercion, optional chaining, nullish coalescing, and more specialized operators. With regular practice, JavaScript operators become natural tools for expressing almost every kind of programming logic.

Scroll to Top