DEV Community

Raja B
Raja B

Posted on

JavaScript operators

JavaScript operators are symbols that perform actions on values and variables. The main types are arithmetic, assignment, comparison, logical, bitwise, string, ternary, and special operators.

Arithmetic operators:

These are used for math operations

- +  Addition: 5 + 2 = 7

- - Subtraction: 5 - 2 = 3

- * Multiplication: 5 * 2 = 10

- / Division: 5 / 2 = 2.5

- % Modulus: gives the remainder, 5 % 2 = 1

- ** Exponentiation: 5 ** 2 = 25
Enter fullscreen mode Exit fullscreen mode

Assignment operators:

These assign or update values in variables

- = assign

- += add and assign

- -= subtract and assign

- *= multiply and assign

- /= divide and assign

- %= remainder and assign
Enter fullscreen mode Exit fullscreen mode
Example:

let x = 10;
x += 5; // x becomes 15  but "x=x+5"
Enter fullscreen mode Exit fullscreen mode

Comparison operators:

These compare two values and return true or false

- == equal to

- === equal value and equal type

- != not equal

- !== not equal value or type

- > greater than

- < less than

- >= greater than or equal to

- <= less than or equal to
Enter fullscreen mode Exit fullscreen mode
Example:

console.log(5 === "5"); // false
console.log(5 == "5");  // true
Enter fullscreen mode Exit fullscreen mode

Logical operators:

These are used in conditions

- && logical AND

- || logical OR

- ! logical NOT

- ?? nullish coalescing, gives the right value only 
when the left side is null or undefined (TBD)
Enter fullscreen mode Exit fullscreen mode

Bitwise operators:

These work on binary bits of numbers

- & bitwise AND

- | bitwise OR

- ^ bitwise XOR (TBD)

- ~ bitwise NOT  (TBD)

- << left shift  (TBD)

- >> signed right shif  (TBD)

- >>> unsigned right shift  (TBD)
Enter fullscreen mode Exit fullscreen mode

String and ternary operators:

JavaScript also has operators for text and short conditional logic

- + can join strings: "Hello" + " World"

- ?: ternary operator: condition ? value1 : value2 (TBD)

Enter fullscreen mode Exit fullscreen mode
Example:

let result = marks >= 40 ? "Pass" : "Fail"; 
Enter fullscreen mode Exit fullscreen mode

Special operators:(TBD)

These are useful in different situations

  • typeof checks the type of a value

  • instanceof checks whether an object is an instance of a class or constructor

  • delete removes a property from an object

  • in checks whether a property exists in an object

  • ?. optional chaining, safely accesses nested values

  • ... spread operator, expands arrays or objects.

Top comments (0)