Start Coding

Topics

JavaScript Operators

JavaScript operators are essential symbols used to perform operations on variables and values. They form the backbone of JavaScript programming, enabling developers to manipulate data, compare values, and control program flow.

Types of Operators

1. Arithmetic Operators

These operators perform mathematical calculations on numeric values.

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (%)
  • Increment (++)
  • Decrement (--)

Example:


let a = 10;
let b = 5;
console.log(a + b); // Output: 15
console.log(a % b); // Output: 0
a++; // a is now 11
    

2. Comparison Operators

These operators compare two values and return a boolean result.

  • Equal to (==)
  • Strict equal to (===)
  • Not equal to (!=)
  • Strict not equal to (!==)
  • Greater than (>)
  • Less than (<)
  • Greater than or equal to (>=)
  • Less than or equal to (<=)

Example:


let x = 5;
let y = "5";
console.log(x == y);  // Output: true
console.log(x === y); // Output: false
    

3. Logical Operators

These operators are used to combine multiple conditions.

  • AND (&&)
  • OR (||)
  • NOT (!)

Example:


let isAdult = true;
let hasLicense = false;
console.log(isAdult && hasLicense); // Output: false
console.log(isAdult || hasLicense); // Output: true
    

4. Assignment Operators

These operators assign values to variables.

  • Assignment (=)
  • Addition assignment (+=)
  • Subtraction assignment (-=)
  • Multiplication assignment (*=)
  • Division assignment (/=)

Example:


let num = 10;
num += 5; // Equivalent to num = num + 5
console.log(num); // Output: 15
    

Operator Precedence

JavaScript follows a specific order when evaluating expressions with multiple operators. This order is called operator precedence. Parentheses can be used to override the default precedence.

Remember: When in doubt about operator precedence, use parentheses to explicitly define the order of operations.

Best Practices

  • Use strict equality (===) and inequality (!==) operators to avoid type coercion.
  • Be cautious when using increment (++) and decrement (--) operators in complex expressions.
  • Utilize the Logical Operators for short-circuit evaluation to improve code efficiency.
  • Consider using the nullish coalescing operator (??) when working with null or undefined values.

Related Concepts

To deepen your understanding of JavaScript operators, explore these related topics:

Mastering JavaScript operators is crucial for writing efficient and effective code. They provide the foundation for complex calculations, conditional logic, and data manipulation in your JavaScript programs.