JavaScript Operators

JavaScript Operators

JavaScript operators are symbols that perform operations on operands, such as variables or values. They are used to manipulate data and perform various computations. Here are the main types of operators in JavaScript with examples:

Arithmetic Operators

  • These operators perform basic mathematical operations.
Operators Name Operators Symbol Name
Addition
–  Subtraction
Multiplication
 /  Division
Modulus (remainder after division)
** Exponentiation
javascript
  let x = 5;
  let y = 2;
  let result;

  result = x + y; // Addition
  result = x - y; // Subtraction
  result = x * y; // Multiplication
  result = x / y; // Division
  result = x % y; // Modulus (remainder after division)
  result = x ** y; // Exponentiation

Comparison Operators

  • These operators compare values and return a Boolean result.
Operators Name Operators Symbol Name
Equal to ==
Not equal to !=
Greater than >
Less than <
Greater than or equal to >=
Less than or equal to <=
javascript
  let a = 5;
  let b = 10;

  console.log(a == b); // Equal to
  console.log(a != b); // Not equal to
  console.log(a > b); // Greater than
  console.log(a < b); // Less than
  console.log(a >= b); // Greater than or equal to
  console.log(a <= b); // Less than or equal to

Logical Operators

  • These operators perform logical operations and return a Boolean result.
Operators Name Operators Symbol Name
AND &&
OR ||
NOT !
javascript
  let p = true;
  let q = false;

  console.log(p && q); // Logical AND
  console.log(p || q); // Logical OR
  console.log(!p); // Logical NOT

Assignment Operators

  • These operators assign values to variables.
javascript
 let a = 5;
  a += 3; // Equivalent to a = a + 3
  a -= 2; // Equivalent to a = a - 2
  a *= 4; // Equivalent to a = a * 4
  a /= 2; // Equivalent to a = a / 2

Unary Operators

  • Operators that work on a single operand.
Operators Name Operators Symbol Name
Unary negation (changes the sign) (–x)
Increment (++x)
Decrement (–x)
javascript
  let x = 5;
  console.log(-x); // Unary negation (changes the sign)
  console.log(++x); // Increment
  console.log(--x); // Decrement

Conditional (Ternary) Operator

  • A shorthand for an if-else statement.
javascript
  let age = 20;
  let message = (age >= 18) ? 'Adult' : 'Minor';

Bitwise Operators

  • Perform bit-level operations on integers.
Operators Name Operators Symbol Name
AND  &
OR |
XOR ^
NOT ~
 Left shift <<
Right shift >>
javascript
  let a = 5; // Binary: 0101
  let b = 3; // Binary: 0011

  console.log(a & b); // Bitwise AND (0001)
  console.log(a | b); // Bitwise OR (0111)
  console.log(a ^ b); // Bitwise XOR (0110)
  console.log(~a); // Bitwise NOT (1010)
  console.log(a << 1); // Left shift (1010)
  console.log(a >> 1); // Right shift  (0010)

Leave a Comment