JavaScript Operators Tutorial

What are the Operators?

  1. Operators are symbols or keywords used to perform operations on values or variables in JavaScript.
  2. They are categorized into various types, including arithmetic, assignment, comparison, logical, and more.
  3. Understanding and using operators is crucial for manipulating data and controlling the flow of your JavaScript code.

Arithmetic Operators

  1. Used for mathematical operations.
  2. +: Addition
  3. -: Subtraction
  4. *: Multiplication
  5. /: Division
  6. %: Remainder
  7. ++: Increment (increases by 1)
  8. --: Decrement (decreases by 1)
  9. **: Exponentiation (power)
let x = 10;
let y = 5;
let addition = x + y;
let subtraction = x - y;
let multiplication = x * y;
let division = x / y;

Assignment Operators

  1. Assign values to variables.
  2. =: Assigns a value to a variable (e.g., const x = 5;).
  3. +=: Adds a value to the existing value of a variable (e.g., a += 5;).
  4. -=: Subtracts a value from the existing value (e.g., a -= 2;).
  5. *=: Multiplies the existing value (e.g., a *= 3;).
  6. /=: Divides the existing value (e.g., a /= 2;).
  7. %=: Computes the remainder (e.g., a %= 2;).
  8. **=: Raises to the power (e.g., a **= 2;).
let a = 10;
a += 5; // a is now 15
a -= 3; // a is now 12
a *= 2 // a is now 24
b = 2;
b **= 2; // b is now 4

Comparison Operators

  1. Compare values and return a boolean (true or false).
let isEqual = x === y; // false
let isGreaterThan = x > y; // true
    

Logical Operators

  1. Combine and manipulate boolean values.
let isTrue = true;
let isFalse = false;
let andOperator = isTrue && isFalse; // false
let orOperator = isTrue || isFalse; // true
let notOperator = !(isTrue || isFalse) // false
    

Unary Operators

  1. Perform operations on a single operand. Either Increment or Decrement
let num = 5;
num++; // Increment by 1, num is now 6
num--; // Decrement by 1, num is now 5
    

Bitwise Operators

  1. Manipulate binary representations of values.
let a = 5; // Binary: 101
let b = 3; // Binary: 011
let bitwiseAnd = a & b; // Result: 001 (1 in decimal)
    

Ternary Operator

  1. A concise way to write conditional statements.
  2. This will understand once we know the conditional statements. So, don't worry if you not figure it out.
let age = 20;
let canVote = (age >= 18) ? console.log('Yes') : 'No';
    

String Operators

  1. The + operator is used to concatenate the strings.
let greeting = 'Hello, ';
let name = 'John';
let message = greeting + name; // 'Hello, John'
    

Type Operators

  1. Check the type of a value.
typeof 42; // 'number'
let name = "Jack";
console.log(typeof(name)) // 'string'

Spread Operator

  1. Used to split array or object elements.
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5]; // [1, 2, 3, 4, 5]