What is an Operator?
In programming, an operator is a special symbol or keyword that performs an operation on one or more operands (values or variables).
Operators are used to manipulate data, perform calculations, compare values, and more.
Think of them as the tools that help you work with data in your code.
JavaScript Operators
JavaScript, like many programming languages, has various types of operators. Here are the most common categories:
- Arithmetic Operators: Perform mathematical calculations.
- Assignment Operators: Assign values to variables.
- Comparison Operators: Compare two values and return a boolean (true or false).
- Logical Operators: Combine multiple conditions.
- String Operators: Concatenate (combine) strings.
- Unary Operators: Operate on a single operand.
- Ternary Operator: A shorthand for an
if-elsestatement.
10 Examples of JavaScript Operators
Addition (+)
let a = 5; let b = 10; let sum = a + b; // sum is 15Subtraction (-)
let difference = b - a; // difference is 5Multiplication (*)
let product = a * b; // product is 50Division (/)
let quotient = b / a; // quotient is 2Modulus (%): Returns the remainder of a division.
let remainder = b % a; // remainder is 0Assignment (=)
let x = 20; // x is assigned the value 20Equality (==): Compares two values for equality, after converting their types if necessary.
let isEqual = (a == '5'); // isEqual is trueStrict Equality (===): Compares two values for equality without converting their types.
let isStrictEqual = (a === '5'); // isStrictEqual is falseLogical AND (&&): Returns true if both conditions are true.
let result = (a > 0 && b > 0); // result is trueTernary Operator (condition ? expr1 : expr2): A shorthand for
if-else.let max = (a > b) ? a : b; // max is 10
These examples give a basic overview of how operators work in JavaScript.
Operators are essential for performing tasks in your code, whether it's doing math, making decisions, or combining conditions.