Javascript Operators

Javascript Operators

JavaScript operators are symbols or keywords that perform operations on values (operands). Here’s an explanation of some commonly used types of operators in JavaScript, along with examples:


1. Arithmetic Operators

Used to perform mathematical operations.

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 7 3
* Multiplication 4 * 2 8
/ Division 9 / 3 3
% Modulus (remainder) 10 % 3 1
** Exponentiation (ES6) 2 ** 3 8

2. Comparison Operators

Used to compare values and return a Boolean (true or false).

Operator Description Example Result
== Equal to (type conversion) '5' == 5 true
=== Strict equal to '5' === 5 false
!= Not equal to '5' != 5 false
!== Strict not equal to '5' !== 5 true
> Greater than 7 > 3 true
< Less than 4 < 2 false
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 3 <= 6 true

3. Logical Operators

Used to combine multiple conditions.

Operator Description Example Result
&& Logical AND (5 > 3) && (7 > 6) true
|| Logical OR (5 > 3) || (7 > 6) true
! Logical NOT !(5 > 3) false

4. Assignment Operators

Used to assign values to variables.

Operator Description Example Result
= Assignment x = 5 x = 5
+= Add and assign x += 3 x = x + 3
-= Subtract and assign x -= 2 x = x - 2
*= Multiply and assign x *= 2 x = x * 2
/= Divide and assign x /= 3 x = x / 3

5. Bitwise Operators

Operate at the binary level.

Operator Description Example Result
& AND 5 & 1 1
| OR 5 | 3 7
^ XOR 5 ^ 1 4
~ NOT ~5 -6
<< Left shift 5 << 1 10
>> Right shift 5 >> 1 2

6. Ternary Operator

A shorthand for if-else statements.

Syntax:
condition ? expression_if_true : expression_if_false

Example:

  const age = 20;
  const canVote = (age >= 18) ? "Yes" : "No";
  console.log(canVote); // Output: "Yes"

7. Type Operators

Check or manipulate the type of a variable.

Operator Description Example Result
typeof Returns the data type typeof 42 "number"
instanceof Checks instance of an object [] instanceof Array true

8. Spread and Rest Operators (ES6)

Used to expand or gather elements.

Spread:

  const numbers = [1, 2, 3];
  console.log(...numbers); // Output: 1 2 3

Rest:

  function sum(...args) {
  return args.reduce((total, num) => total + num, 0);
  }
  console.log(sum(1, 2, 3)); // Output: 6

Previous Next