Premium Javascript Course

JavaScript Operators

Operators are symbols or keywords in JavaScript that allow you to perform operations on variables and values. JavaScript provides a variety of operators for performing different operations.

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations on numbers:

Example:


let x = 10;
let y = 5;
let sum = x + y; // 15
let difference = x - y; // 5
let product = x * y; // 50
let quotient = x / y; // 2
let remainder = x % y; // 0
let increment = ++x; // 11
let decrement = --y; // 4
        

2. Comparison Operators

Comparison operators are used to compare two values and return a boolean result (true or false).

Example:


let a = 10;
let b = 5;
console.log(a > b); // true
console.log(a === 10); // true
console.log(b !== 10); // true
        

3. Logical Operators

Logical operators are used to combine or negate boolean values:

Example:


let isAdult = true;
let hasTicket = false;
console.log(isAdult && hasTicket); // false
console.log(isAdult || hasTicket); // true
console.log(!isAdult); // false
        

4. Assignment Operators

Assignment operators are used to assign values to variables:

Example:


let num = 5;
num += 3; // 8
num -= 2; // 6
num *= 2; // 12
num /= 3; // 4
num %= 3; // 1
        

5. Unary Operators

Unary operators operate on a single operand:

Example:


let count = 5;
count++; // 6
count--; // 5

console.log(typeof count); // number

let obj = { name: "Alice", age: 25 };
delete obj.age; // Deletes the "age" property
console.log(obj); // { name: "Alice" }
        

6. Ternary Operator

The ternary operator is a shorthand way to perform a conditional check:


let age = 18;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
        

7. Typeof Operator

Use the typeof operator to check the type of a variable:


let str = "Hello";
console.log(typeof str); // Output: string

let num = 10;
console.log(typeof num); // Output: number
        

Conclusion

Operators are essential building blocks in JavaScript that allow you to perform operations on data. Understanding and using the right operators will help you write efficient, concise, and readable code. Make sure you are comfortable with the various types of operators to handle all types of tasks in JavaScript.