JavaScript Operators
JavaScript operators play a crucial role in programming, enabling developers to manipulate variables, perform calculations, and make decisions within their code. Understanding the various types of operators is fundamental to mastering JavaScript. In this article, we’ll explore the different categories of JavaScript operators with illustrative examples.
Arithmetic Operators:
Arithmetic operators are used for basic mathematical operations. They include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). Let’s look at some examples:
let a = 10;
let b = 5;
console.log(a + b); // Output: 15
console.log(a - b); // Output: 5
console.log(a * b); // Output: 50
console.log(a / b); // Output: 2
console.log(a % b); // Output: 0 (remainder of a divided by b)
Comparison Operators:
Comparison operators are used to compare values and return a Boolean result. They include equal to (==), not equal to (!=), strict equal to (===), strict not equal to (!==), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
let x = 5;
let y = '5';
console.log(x == y); // Output: true (loose equality)
console.log(x === y); // Output: false (strict equality)
console.log(x != y); // Output: false
console.log(x !== y); // Output: true
console.log(x > y); // Output: false
console.log(x < y); // Output: false
console.log(x >= y); // Output: true
console.log(x <= y); // Output: true
Logical Operators:
Logical operators are used to combine or negate boolean values. They include AND (&&), OR (||), and NOT (!).
let isSunshine = true;
let isWeekend = false;
console.log(isSunshine && isWeekend); // Output: false (AND)
console.log(isSunshine || isWeekend); // Output: true (OR)
console.log(!isSunshine); // Output: false (NOT)
Assignment Operators:
Assignment operators are used to assign values to variables. They include the basic assignment operator (=), as well as compound assignment operators like +=, -=, *=, and /=.
let num = 10;
num += 5; // Equivalent to: num = num + 5;
console.log(num); // Output: 15
Unary Operators:
Unary operators act on a single operand. Examples include the unary plus (+) and unary minus (-) operators.
let number = 7;
console.log(+number); // Output: 7
console.log(-number); // Output: -7
Conclusion:
Mastering JavaScript operators is essential for effective programming. From performing basic arithmetic to making logical decisions, operators provide the tools needed to create dynamic and functional code. By understanding and utilizing these operators, developers can write more efficient and expressive JavaScript programs.