Understanding Operators in JavaScript

You are currently viewing Understanding Operators in JavaScript
Operators in JavaScript

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:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Bitwise Operators
  6. String Operators
  7. Conditional (Ternary) Operator
  8. Comma Operator
  9. Unary Operators
  10. 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 //?
[]==[] //?
[]===[] //?
{}=={}//?
{}==={} //?
  1. 0 == false: This is true because the == operator performs type coercion. 0 is considered equivalent to false in a loose comparison.
  2. 0 === false: This is false because the === operator checks for both value and type equality. 0 (a number) and false (a boolean) are of different types.
  3. 1 == "1": This is true because the == operator coerces the string "1" to a number, making the comparison between 1 and 1.
  4. 1 === "1": This is false because === checks for strict equality (both type and value). 1 (a number) is not the same type as "1" (a string).
  5. null == undefined: This is true because null and undefined are considered equal in a loose comparison (==), though they are not strictly equal.
  6. null === undefined: This is false because === requires both the type and value to be the same. null and undefined are different types.
  7. '0' == false: This is true because '0' (a string) is coerced into a number 0, which is equal to false in a loose comparison. In detail, the string '0' is converted to the number 0, which is then compared to false (which is also treated as 0 in this context).
  8. '0' === false: This is false because '0' is a string and false is a boolean. The === operator does not perform type coercion.
  9. NaN == NaN: This is false because NaN is not equal to any value, including itself. This is a unique feature of NaN.
  10. NaN === NaN: This is also false for the same reason as above—NaN is not strictly equal to itself.
  11. [] == []: This is false because both [] are different instances of arrays, so they do not refer to the same object in memory.
  12. [] === []: This is false for the same reason as above; they are different array instances.
  13. {} == {}: This is false for similar reasons as the array example. The two object literals are different instances and do not refer to the same object.
  14. {} === {}: This is false 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

  1. 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' returns true, while 5 === '5' returns false.
  2. 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" and typeof "Hello" returns "string".
  3. 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".
  4. 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 removes property from obj. If the operation is successful, it returns true.
  5. 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.
  6. 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, and false if the value is falsy.
    • !!true is same as !(!true), so output of !!true is true
You can share it on

Leave a Reply