Operators in JavaScript

Introduction Link to heading

Operators are symbols or keywords used to perform actions on one or more values (operands) in JavaScript.

Types of operators Link to heading

  • Binary operators: They operate on two operands:

    • Arithmetic: +, -, *, /, %
    • Relational: <, >, <=, >=, ==, ===
    • Logical: &&, ||, !
    • Concatenation: +

Examples Link to heading

  • Arithmetic:
3 + 2; // Sum: 5
50 - 10; // Subtraction: 40
10 \* 20; // Multiplication: 200
20/2; // Division: 10
20% 2; // Rest: 0
  • Relational:
3 == "3"; // Value equality: true
3 === "3"; // Equality of value and type: false
5 < 3; // Less than: false
5 > 3; // Greater than: true
5 <= 6; // Less than or equal to: true
5 >= 6; // Greater than or equal to: false
  • Logical:
true && true; // Both are true: true
true || false; // At least one is true: true
!false; // Negation: true
  • Concatenation:
"Hello " + "World"; // String concatenation: "Hello World"
  • Unary operators: They operate on a single operand.

    • Negation: !
    • Increment/Decrement: ++, --

Examples: Link to heading

  • Denial:
!false; // Negation: true
  • Increment/Decrement:
var a = 1;
a++; // Increase to 2
age--; // Decrease age by 1

Advanced operators Link to heading

  • Ternary operator:
var age = 18;
var message = age >= 18 ? "adult" : "Minor";
console.log(message); // "adult"
  • Short Circuit Operator:
var a = 1;
var b = 2;

// B is only evaluated if a is truthy
a && b; // true

// b is evaluated even if a is falsy
a || b; // 2

Keep learning about operators to write more expressive and efficient JavaScript code!

<< Truthy and falsy values in JavaScript Arrays in JavaScript >>