Understanding and using operators in JavaScript
Operators in JavaScript are symbols that are used to perform operations on operands. They are essential for performing calculations, comparing values, and more.
These operators are used to perform mathematical operations:
let a = 10, b = 5;
console.log(a + b); // Addition: 15
console.log(a - b); // Subtraction: 5
console.log(a * b); // Multiplication: 50
console.log(a / b); // Division: 2
console.log(a % b); // Modulus: 0
console.log(a ** b); // Exponentiation: 100000
These operators are used to compare values:
console.log(a == b); // Equal to: false
console.log(a != b); // Not equal to: true
console.log(a > b); // Greater than: true
console.log(a < b); // Less than: false
console.log(a >= b); // Greater than or equal to: true
console.log(a <= b); // Less than or equal to: false
These operators are used with Boolean values:
let x = true, y = false;
console.log(x && y); // Logical AND: false
console.log(x || y); // Logical OR: true
console.log(!x); // Logical NOT: false
These operators are used to assign values to variables:
let c = 10;
c += 5; // c is now 15
c -= 3; // c is now 12
c *= 2; // c is now 24
c /= 4; // c is now 6
This operator is used as a shortcut for the if statement:
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // Outputs: "Adult"
Understanding and correctly using these operators is crucial for effective JavaScript programming. They allow you to perform calculations, make decisions, and control the flow of your program.