Understanding operators is crucial for anyone looking to master JavaScript. In this blog, we will explore the various types of operators in JavaScript, provide examples for each, and highlight their practical usage.
What are the types of Operators in JavaScript?
JavaScript operators can be broadly classified into several categories:
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- String Operators
- Conditional (Ternary) Operator
- Comma Operator
- Unary Operators
- Relational Operators
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division.
- + (Addition): Adds two values.
- – (Subtraction): Subtracts the second value from the first.
- * (Multiplication): Multiplies two values.
- / (Division): Divides the first value by the second.
- % (Modulus): Returns the remainder of division.
- ** (Exponentiation): Raises the first value to the power of the second.
- ++(Increment): Increases the value by one.
- — (Decrement): Decreases the value by one.
let a = 10;
let b = 5;
console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2
console.log(a % b); // 0
a++;
console.log(a); // 11
b--;
console.log(b); // 4
let power = 2 ** 3;
console.log(power); // 8
2. Assignment Operators
Assignment operators assign values to variables. They can also perform operations and assign the result simultaneously.
- = (Assignment)
- += (Addition Assignment)
- -= (Subtraction Assignment)
- *= (Multiplication Assignment)
- /= (Division Assignment)
- %= (Modulus Assignment)
let x = 10;
x += 5; // x = x + 5
console.log(x); // 15
x *= 2; // x = x * 2
console.log(x); // 30
x -= 5;
console.log(x); // x = 25
x /= 5;
console.log(x); // x = 5
x %= 3;
console.log(x); // x = 2
x **= 2;
console.log(x); // x = 4
3. Comparison Operators
Comparison operators are used to compare two values, resulting in a Boolean value (true
or false
).
- == (Equal to)
- === (Strict equal to)
- != (Not equal to)
- !== (Strict not equal to)
- > (Greater than)
- < (Less than)
- >= (Greater than or equal to)
- <= (Less than or equal to)
let a = 10;
let b = '10';
console.log(a == b); // true
console.log(a === b); // false
console.log(a != b); // false
console.log(a !== b); // true
console.log(a > 5); // true
console.log(a < 5); // false
console.log(a >= 5); // true
console.log(a <= 7); // true
4. Logical Operators
Logical operators are used to perform logical operations on Boolean values.
- && (Logical AND) Returns true if both operands are true.
- || (Logical OR): Returns true if at least one operand is true.
- ! (Logical NOT): Returns true if the operand is false, and vice versa.
- ?? (Logical Nullish Coalescing): Returns the right operand when the left operand is null or undefined.
let a = true;
let b = false;
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false
const nullValue = null;
let x= nullValue ?? 'default';
console.log(x); // 'default'
5. Bitwise operators
Bitwise operators in JavaScript operate on the binary representations of numbers. They perform operations on the individual bits of binary numbers.
- & (AND)
- | (OR)
- ^ (XOR)
- ~ (NOT)
- << (Left shift)
>>
(Right shift)>>>
(Zero-fill right shift)
Bitwise AND (&)
The Bitwise AND operator (&
) compares each bit of two numbers and returns a new number whose bits are set to 1 if both corresponding bits of the operands are 1, otherwise the bits are set to 0.
let a = 5; // In binary: 0101
let b = 3; // In binary: 0011
let result = a & b; // Binary result: 0001 (1 in decimal)
console.log(result); // Output: 1
Bitwise OR(|
)
The Bitwise OR operator (|
) compares each bit of two numbers and returns a new number whose bits are set to 1 if at least one of the corresponding bits of the operands is 1.
let a = 5; // In binary: 0101
let b = 3; // In binary: 0011
let result = a | b; // Binary result: 0111 (7 in decimal)
console.log(result); // Output: 7
Bitwise XOR (^
)
The Bitwise XOR operator (^
) compares each bit of two numbers and returns a new number whose bits are set to 1 if exactly one of the corresponding bits of the operands is 1.
let a = 5; // In binary: 0101
let b = 3; // In binary: 0011
let result = a ^ b; // Binary result: 0110 (6 in decimal)
console.log(result); // Output: 6
Bitwise NOT (~
)
The Bitwise NOT operator (~
) inverts all the bits of its operand. It returns a number with all bits flipped: 1 becomes 0, and 0 becomes 1.
let a = 5; // In binary: 0000 0101
let result = ~a; // Binary result: 1111 1010 (in decimal: -6)
console.log(result); // Output: -6
Bitwise Left Shift (<<
)
The Bitwise Left Shift operator (<<
) shifts the bits of the first operand to the left by the number of positions specified by the second operand. New bits on the right are filled with zeros.
let a = 5; // In binary: 0000 0101
let result = a << 1; // Binary result: 0000 1010 (10 in decimal)
console.log(result); // Output: 10
Bitwise Right Shift (>>
)
The Bitwise Right Shift operator (>>
) shifts the bits of the first operand to the right by the number of positions specified by the second operand. The sign bit (leftmost bit) is used to fill the new bits on the left.
let a = 5; // In binary: 0000 0101
let result = a >> 1; // Binary result: 0000 0010 (2 in decimal)
console.log(result); // Output: 2
Bitwise Unsigned Right Shift (>>>
)
The Bitwise Unsigned Right Shift operator (>>>
) shifts the bits of the first operand to the right by the number of positions specified by the second operand. Unlike the signed right shift, it fills new bits on the left with zeros regardless of the sign of the original number.
let a = -5; // In binary (32-bit): 1111 1111 1111 1111 1111 1111 1111 1011
let result = a >>> 1; // Binary result: 0111 1111 1111 1111 1111 1111 1111 1101 (2147483645 in decimal)
console.log(result); // Output: 2147483645
6. String Operators
JavaScript includes the +
operator, which can be used to concatenate (join) strings.
- (Concatenation)
- += (Concatenation assignment)
let greeting = "Hello";
let name = "World";
console.log(greeting + " " + name); // Hello World
greeting += " Everyone";
console.log(greeting); // Hello Everyone
7. Conditional (Ternary) Operator
The ternary operator is a shorthand for an if-else
statement and is used to evaluate a condition.
let age = 18;
let canVote = (age >= 18) ? 'Yes' : 'No'; // 'Yes'
8. Comma Operator
The comma operator allows multiple expressions to be evaluated in a single statement, returning the last evaluated expression.
let a = 1;
let b = (a++, a + 5);
console.log(b); // 7
9. Unary Operators
Unary operators work with a single operand and can perform various operations like negation, type checking, etc.
- +(Unary plus): Converts the operand to a number.
- -(Unary negation): Negates the operand.
- ++ (Increment): Increases the value by one.
- — (Decreases): Decreases the value by one.
- ! (Logical NOT): Inverts the Boolean value.
let num = +true; // 1
let neg = -10; // -10
let count = 5;
count++; // 6
count--; //5
let truth = true;
let falsity = !truth; // false
10. Relational Operators
Relational operators are used to check the relationship between two operands, like whether one is in another or not.
- ‘in’ (Property in object)
- ‘instanceof’ (Instance of a class)
let car = { make: "Toyota", model: "Camry" };
console.log("make" in car); // true
let date = new Date();
console.log(date instanceof Date); // true
Can we use Operators in Expressions?
Absolutely! Operators are integral components of expressions in JavaScript. Expressions are combinations of values, variables, operators, and functions that are evaluated to produce a value. Operators are used within expressions to perform various operations.
To know more about the Expressions, Click here.
What is the purpose of double tilde operator?
The double tilde (~~
) operator in JavaScript is a shorthand technique often used to convert a number to an integer. It’s a compact and efficient way to perform the same operation as Math.floor()
, but with a few differences in behavior.
console.log(~~4.9); // Outputs: 4
console.log(~~-4.9); // Outputs: -4
console.log(~~0.123); // Outputs: 0
console.log(~~-0.123); // Outputs: 0
Understanding Equality and Type Coercion
0 == false //?
0 === false //?
1 == "1" //?
1 === "1" //?
null == undefined //?
null === undefined //?
'0' == false //?
'0' === false //?
NaN == NaN //?
NaN === NaN //?
[]==[] //?
[]===[] //?
{}=={}//?
{}==={} //?
0 == false
: This istrue
because the==
operator performs type coercion.0
is considered equivalent tofalse
in a loose comparison.0 === false
: This isfalse
because the===
operator checks for both value and type equality.0
(a number) andfalse
(a boolean) are of different types.1 == "1"
: This istrue
because the==
operator coerces the string"1"
to a number, making the comparison between1
and1
.1 === "1"
: This isfalse
because===
checks for strict equality (both type and value).1
(a number) is not the same type as"1"
(a string).null == undefined
: This istrue
becausenull
andundefined
are considered equal in a loose comparison (==
), though they are not strictly equal.null === undefined
: This isfalse
because===
requires both the type and value to be the same.null
andundefined
are different types.'0' == false
: This istrue
because'0'
(a string) is coerced into a number0
, which is equal tofalse
in a loose comparison. In detail, the string'0'
is converted to the number0
, which is then compared tofalse
(which is also treated as0
in this context).'0' === false
: This isfalse
because'0'
is a string andfalse
is a boolean. The===
operator does not perform type coercion.NaN == NaN
: This isfalse
becauseNaN
is not equal to any value, including itself. This is a unique feature ofNaN
.NaN === NaN
: This is alsofalse
for the same reason as above—NaN
is not strictly equal to itself.[] == []
: This isfalse
because both[]
are different instances of arrays, so they do not refer to the same object in memory.[] === []
: This isfalse
for the same reason as above; they are different array instances.{} == {}
: This isfalse
for similar reasons as the array example. The two object literals are different instances and do not refer to the same object.{} === {}
: This isfalse
for the same reason; different instances of objects.
A key takeaway here is the distinction between ==
(loose equality) and ===
(strict equality). The ==
operator performs type coercion and can lead to unexpected results, whereas ===
ensures both type and value are identical, making it generally safer for comparisons.
Interview Questions and Answers
- Q: What is the difference between
==
and===
in JavaScript?- A: The
==
operator checks for equality after performing type coercion, whereas===
checks for both value and type equality without coercion. For example,5 == '5'
returnstrue
, while5 === '5'
returnsfalse
.
- A: The
- Q: How does the
typeof
operator work in JavaScript?- A: The
typeof
operator returns a string indicating the type of the operand. For example,typeof 42
returns"number"
andtypeof "Hello"
returns"string"
.
- A: The
- Q: Can you explain how the ternary operator works with an example?
- A: The ternary operator is a shorthand for an
if-else
statement. It takes a condition followed by two expressions: if the condition is true, the first expression is returned; otherwise, the second expression is returned. For example,(5 > 3) ? 'Yes' : 'No'
returns"Yes"
.
- A: The ternary operator is a shorthand for an
- Q: What does the
delete
operator do in JavaScript?- A: The
delete
operator is used to remove a property from an object. For example,delete obj.property
removesproperty
fromobj
. If the operation is successful, it returnstrue
.
- A: The
- Q: What are bitwise operators and where are they used?
- A: Bitwise operators perform operations on binary numbers. They are often used in low-level programming, such as setting flags in a bitmask or performing quick calculations by manipulating individual bits.
- Q: What is the purpose of double exclamation(!!)?
- A: By applying the exclamation mark twice, you first negate the value, then negate it again. This effectively converts the value to a boolean. The result will be
true
if the value is truthy, andfalse
if the value is falsy. - !!true is same as !(!true), so output of !!true is true
- A: By applying the exclamation mark twice, you first negate the value, then negate it again. This effectively converts the value to a boolean. The result will be