JavaScript Operators - Arithmetic, Comparison, and Logical
Operators in JavaScript allow you to perform operations on data, make comparisons, and control the flow of your code. In this guide, we'll explore three essential types of operators: Arithmetic, Comparison, and Logical operators.
Arithmetic Operators
Arithmetic operators are used for mathematical calculations. Here are some common arithmetic operators:
let x = 10;
let y = 5;
let addition = x + y;
let subtraction = x - y;
let multiplication = x * y;
let division = x / y;
let modulus = x % y;
console.log("Addition: " + addition);
console.log("Subtraction: " + subtraction);
console.log("Multiplication: " + multiplication);
console.log("Division: " + division);
console.log("Modulus: " + modulus);
Comparison Operators
Comparison operators are used to compare values and return true or false. Here are some common comparison operators:
let a = 10;
let b = 5;
let isEqual = a === b; // Strict equality
let isNotEqual = a !== b; // Strict inequality
let isGreaterThan = a > b;
let isLessThan = a < b;
let isGreaterOrEqual = a >= b;
let isLessOrEqual = a <= b;
console.log("Equal: " + isEqual);
console.log("Not Equal: " + isNotEqual);
console.log("Greater Than: " + isGreaterThan);
console.log("Less Than: " + isLessThan);
console.log("Greater or Equal: " + isGreaterOrEqual);
console.log("Less or Equal: " + isLessOrEqual);
Logical Operators
Logical operators are used to perform logical operations and combine multiple conditions. Here are some common logical operators:
let hasPermission = true;
let isVerified = true;
let canAccessResource = hasPermission && isVerified; // Logical AND
let canEditResource = hasPermission || isVerified; // Logical OR
let cannotEditResource = !canEditResource; // Logical NOT
console.log("Can Access Resource: " + canAccessResource);
console.log("Can Edit Resource: " + canEditResource);
console.log("Cannot Edit Resource: " + cannotEditResource);
Conclusion
JavaScript operators are vital for performing various tasks in your code, such as mathematical calculations, comparisons, and logical operations. Understanding how these operators work is crucial for writing effective and efficient JavaScript programs.
Happy coding!