DEV Community

Veera Ganapathi
Veera Ganapathi

Posted on

Operator Js

What is operator?

JavaScript operators are symbols or keywords used to perform operations on values and variables. Operators are special symbols used to calculate, compare, assign, or check values.

Arithmetic Operators

Arithmetic operators perform arithmetic on numbers (literals or variables).

Operator

  1. + Addition
  2. - Subtraction
  3. * Multiplication
  4. / Division
  5. % Modulus (Remainder)
let sum = 5 + 3; // Addition
let diff = 10 - 2; // Subtraction
let p = 4 * 2; // Multiplication
let q = 8 / 2; // Division
let a = 8 % 2; // Modulus
console.log(sum, diff, p, q, a);

Output:
8
8
8
4
0
Enter fullscreen mode Exit fullscreen mode

Assignment Operator

Assignment operators assign values to variables.

let x = 10;

x += 5;  // 15
x -= 3;  // 12
x *= 2;  // 24
x /= 4;  // 6
x %= 5;  // 1
Enter fullscreen mode Exit fullscreen mode

Comparison Operators

Comparison operators are used to compare two values. Comparison operators always return true or false.

5 == "5"   // true (loose equality)
5 === "5"  // false (strict equality)

5 != "5"   // false
5 !== "5"  // true

5 > 3      // true
5 < 3      // false
5 >= 5     // true
5 <= 4     // false
Enter fullscreen mode Exit fullscreen mode

Logical Operators

Logical operators are mainly used to perform the logical operations that determine the equality or difference between the values.

let a = true, b = false;
console.log(a && b); // Logical AND
console.log(a || b); // Logical OR
Enter fullscreen mode Exit fullscreen mode

&& returns true if both operands are true.
|| returns true if at least one operand is true.
! negates the boolean value.

Increment Operator (++)

The increment operator increases the value of a variable by 1.

type

  1. - Pre-Increment (++a)
  2. - Post-Increment (a++)

1. Pre-Increment (++a)

The value is increased first, then used in the expression.

let a = 5;

console.log(++a); // 6
console.log(a);   // 6

Enter fullscreen mode Exit fullscreen mode

2. Post-Increment (a++)

The current value is used first, then increased by 1.

let a = 5;

console.log(a++); // 5
console.log(a);   // 6
Enter fullscreen mode Exit fullscreen mode

Decrement (--) Operators

The decrement operator decreases the value of a variable by 1.

type

  1. Pre-Decrement (--a)
  2. Post-Decrement (a--)

1. Pre-Decrement (--a)

The value is decreased first, then used in the expression.

let a = 5;

console.log(--a); // 4
console.log(a);   // 4
Enter fullscreen mode Exit fullscreen mode

2.Post-Decrement (a--)

The current value is used first, then decreased by 1.

let a = 5;

console.log(a--); // 5
console.log(a);   // 4
Enter fullscreen mode Exit fullscreen mode

Top comments (0)