Operators and expressions are fundamental components of JavaScript that allow developers to perform various operations on data and variables.
Understanding how to use operators and create expressions is essential for writing high-quality and efficient JavaScript code.
This detailed explanation will focus on providing quality information about operators and expressions in JavaScript.
Operators in JavaScript
Operators are symbols or keywords that perform specific operations on one or more values, known as operands. JavaScript supports various operators, including arithmetic, comparison, logical, assignment, and more.
Arithmetic Operators
Arithmetic operators perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus.
let a = 5;
let b = 2;
let sum = a + b; // Addition: 5 + 2 = 7
let difference = a - b;// Subtraction: 5 - 2 = 3
let product = a * b; // Multiplication: 5 * 2 = 10
let quotient = a / b; // Division: 5 / 2 = 2.5
let remainder = a % b; // Modulus: 5 % 2 = 1
Comparison Operators
Comparison operators are used to compare values and return a boolean result (true or false) based on the comparison.
let x = 10;
let y = 5;
let isEqual = x === y; // Strict equality: false
let isNotEqual = x !== y; // Strict inequality: true
let isGreater = x > y; // Greater than: true
let isLess = x < y; // Less than: false
let isGreaterOrEqual = x >= y; // Greater than or equal: true
let isLessOrEqual = x <= y; // Less than or equal: false
Logical Operators
Logical operators are used to combine or negate boolean values.
let isTrue = true;
let isFalse = false;
let logicalAnd = isTrue && isFalse; // Logical AND: false
let logicalOr = isTrue || isFalse; // Logical OR: true
let logicalNot = !isTrue; // Logical NOT: false
Assignment Operators
Assignment operators are used to assign values to variables.
let num = 10;
let name = 'John';
num += 5; // Equivalent to num = num + 5;
name += ' Doe'; // Equivalent to name = name + ' Doe';
Expressions in JavaScript
An expression is a combination of values, variables, and operators that can be evaluated to produce a result. Expressions can be simple or complex, playing a vital role in calculating and making decisions in JavaScript.
Simple Expressions
Simple expressions consist of single values or variables.
let age = 25;
let name = 'John Doe';
Complex Expressions
Complex expressions involve multiple operators and operands.
let x = 10;
let y = 5;
let result = (x * y) + (y - 2); // 10 * 5 + (5 - 2) = 53
Conditional Expressions (Ternary Operator)
The ternary operator is a concise way to write conditional expressions.
let isEven = (x % 2 === 0) ? true : false;
Function Expressions
Functions can be used within expressions and assigned to variables.
let add = function(a, b) {
return a + b;
};
let sum = add(5, 3); // 5 + 3 = 8