Operators
Operators in programming act as the building blocks for performing tasks, making comparisons, and manipulating data. Imagine them as tools in a toolbox, each designed for specific actions. From basic arithmetic to complex logical evaluations, operators enable you to add, subtract, compare, assign values, and more.
Arithmetic operators in programming perform mathematical operations on variables, producing results like addition, subtraction, multiplication, division, or modulus.
-
Addition (+): It does what it says
on the tin—adds numbers together. For example, 5 + 3
equals 8. Similarly, if you concatenate two strings,
like "hello" + "world", it becomes "helloworld".
let additionResult = 5 + 3; console.log(additionResult); // Output: 8 console.log("hello"+"world"); //helloworld
-
Subtraction (-): It's for taking
away one number from another. Like 10 - 4 equals 6.
let subtractionResult = 10 - 4; console.log(subtractionResult); // Output: 6
-
Multiplication (*): This one is for
multiplying numbers together. For instance, 3 * 4
equals 12.
let multiplicationResult = 3 * 4; console.log(multiplicationResult); // Output: 12
-
Exponentiation ** (ES2016): It
raises one number to the power of another. So, 2 **
3 means 2 raised to the power of 3, which equals 8.
let exponentialResult = 2 ** 3; console.log(exponentialResult); // Output: 8
-
Division (/): It's for dividing one
number by another. For example, 15 / 3 equals 5.
let divisionResult = 15 / 3; console.log(divisionResult); // Output: 5
-
Modulus (%): It gets you the
remainder after a division. For instance, 10 % 3
would give you 1 because 3 goes into 10 three times
with a remainder of 1.
let moduloResult = 10 % 3; console.log(moduloResult); // Output: 1 (This gives the remainder when 10 is divided by 3.)
-
Increment (++) & Decrement (--): The ++ operator increments a variable
by 1, while the -- operator decrements
a variable by 1. When used as
postfix (variable++ or variable--), the
current value of the variable is used in the
expression, and then the variable is incremented or
decremented. When used as
prefix (++variable or --variable), the
variable is first incremented or decremented, and
then its new value is used in the expression.
let x = 10; let y = 20; console.log(x++ + ++y); // Output: 10 + 21 = 31 console.log(x + y--); // Output: 11 + 21 = 32 console.log(++x + y); // Output: 12 + 20 = 32
Comparison operators in programming compare two values or expressions, returning a Boolean value (true or false) based on their relationship, like equality, inequality, or relative values. Here they are:
-
Equal to (==): It checks if two
values are equal. However, it performs type
coercion, which means it might convert the types and
then compare. For instance, 5 == "5" would be true.
console.log(5 == "5"); // Output: true (Type coercion is performed)
-
Equal value and equal type (===): This compares both the value and the type. It’s
more strict than ==. For example, 5 === "5" would be
false.
console.log(5 === "5"); // Output: false (Considers both value and type)
-
Not equal to (!=): Checks if two
values are not equal. Similar to ==, it performs
type coercion. For instance, 5 != "5" would be
false.
console.log(5 != "5"); // Output: false (Type coercion is performed)
-
Not equal value or not equal type (!==):Compares both value and type, and returns true if
they're not equal. For example, 5 !== "5" would be
true.
console.log(5 !== "5"); // Output: true (Considers both value and type)
-
Greater than (>): Checks if the
left value is greater than the right one. For
instance, 10 > 5 would be true.
console.log(10 > 5); // Output: true
-
Less than (<): Checks if the left
value is less than the right one. For example, 5 <
10 would be true
console.log(5 < 10); // Output: true
-
Greater than or equal to (>=): Compares if the left value is greater than or equal
to the right one. For instance, 10 >= 10 would be
true.
console.log(10 >= 10); // Output: true
-
Less than or equal to (<=): Compares if the left value is less than or equal
to the right one. For example, 5 <= 10 would be
true.
console.log(5 <= 10); // Output: true
Assignment operators in programming assign values to variables, using various symbols like "=", "+=", "-=", "*=", "/=", etc., to perform the assignment along with an operation.
-
Assignment (=): It checks if both
conditions on its left and right are true. For
example, true && true would be true, but true &&
false would be false. If either operand is false,
the whole expression is false.
let condition = (true && true); console.log(condition); // Output: true
-
Addition assignment (+=): It adds
the right operand to the left operand and assigns
the result to the left operand. For example, x += 3;
is the same as x = x + 3;.
let x = 5; x += 3; console.log(x); // Output: 8 (Equivalent to x = x + 3)
-
Subtraction assignment (-=): It
subtracts the right operand from the left operand
and assigns the result to the left operand. For
instance, x -= 2; is the same as x = x - 2;.
let y = 10; y -= 2; console.log(y); // Output: 8 (Equivalent to y = y - 2)
-
Multiplication assignment (*=): It
multiplies the left operand by the right operand and
assigns the result to the left operand. For example,
x *= 4; is the same as x = x * 4;.
let a = 3; a *= 4; console.log(a); // Output: 12 (Equivalent to a = a * 4)
-
Division assignment (/=): It
divides the left operand by the right operand and
assigns the result to the left operand. For
instance, x /= 2; is the same as x = x / 2;.
let b = 8; b /= 2; console.log(b); // Output: 4 (Equivalent to b = b / 2)
-
Remainder assignment (%=): It
divides the left operand by the right operand and
assigns the remainder to the left operand. For
example, x %= 3; is the same as x = x % 3;.
let c = 10; c %= 3; console.log(c); // Output: 1 (Equivalent to c = c % 3)
-
Exponentiation assignment (=)** (ES2016):
It raises the left operand to the power of the right
operand and assigns the result to the left operand.
For instance, x **= 2; is the same as x = x ** 2;.
let d = 2; d **= 3; console.log(d); // Output: 8 (Equivalent to d = d ** 3)
Logical operators in programming perform logical operations on Boolean values or expressions, including AND, OR, and NOT operations, returning true or false based on the conditions. Here's the trio:
-
Logical AND (&&): It checks if
both conditions on its left and right are true. For
example, true && true would be true, but true &&
false would be false. If either operand is false,
the whole expression is false.
let condition1 = true && true; console.log(condition1); // Output: true let condition2 = true && false; console.log(condition2); // Output: false
-
Logical OR (||):It checks if at
least one of the conditions on its left or right is
true. For instance, true || false would be true, and
false || false would be false. If either operand is
true, the whole expression is true.
let condition3 = true || false; console.log(condition3); // Output: true let condition4 = false || false; console.log(condition4); // Output: false
-
Logical NOT (!): It's a unary
operator that negates the value of a condition. For
instance, !true would be false, and !false would be
true. It flips the value of the operand.
let condition5 = !true; console.log(condition5); // Output: false let condition6 = !false; console.log(condition6); // Output: true
The ternary operator in programming is a concise conditional statement that evaluates a condition and returns one of two values based on that condition, using the syntax condition ? valueIfTrue : valueIfFalse. It's a one-liner that acts as a compact if-else statement, making your code cleaner and more readable. The syntax looks like this:
condition ? exprIfTrue : exprIfFalse;
Here’s how it works: condition is evaluated first. If it's true, exprIfTrue is executed. If condition is false, exprIfFalse is executed. For example:
let age = 18;
let message = (age >= 18) ? "You can vote" : "You cannot vote";
console.log(message);
The typeof operator in JavaScript returns the data type of a variable or expression as a string, indicating whether it's a number, string, boolean, object, function, or undefined. Here are some examples of how the typeof operator can be used:
console.log(typeof 1); // 'number'
console.log(typeof 'hello'); // 'string'
console.log(typeof true); // 'boolean'
console.log(typeof {}); // 'object'
console.log(typeof []); // 'object'
console.log(typeof function() {}); // 'function'
console.log(typeof null); // 'object'
console.log(typeof undefined); // 'undefined'
console.log(typeof NaN); // 'number'
It's worth noting that typeof null returns 'object' which is considered as a bug in javascript. Another important thing is that typeof operator returns 'undefined' for variables that have been declared but have not been assigned a value.
Operator precedence in programming defines the order of operations performed by different operators, ensuring correct evaluation when multiple operators are used in a single expression. Some operators have higher precedence than others, and will be executed first.
For example, in the expression 1 + 2 * 3, the multiplication operator (*) has higher precedence than the addition operator (+), so the multiplication is done first, resulting in the expression being evaluated as 1 + (2 * 3) = 7. Here is the list of operator precedence in JavaScript, from highest to lowest:
Precedence | Operator | Description | Associativity |
---|---|---|---|
1 | ( ) | Parentheses | n/a |
2 | ! ~ + - ++ -- typeof void | Unary operators | n/a |
3 | \ * % / | Multiplicative operators | left-to-right |
4 | + - | Additive operators | left-to-right |
5 | << >> >>> | Bitwise shift operators | left-to-right |
6 | < <= > >= instanceof | Relational operators | left-to-right |
7 | == != === !== | Equality operators | left-to-right |
8 | & | Bitwise AND operator | left-to-right |
9 | ^ | Bitwise XOR operator | left-to-right |
10 | | | Bitwise OR operator | left-to-right |
11 | && | Logical AND operator | left-to-right |
12 | || | Logical OR operator | left-to-right |
13 | ? : | Conditional operator | right to left |
14 | = += -= \*= /= %= <<= >>= &= ^= |= | Assignment operators | right-to-left |
//Examples
// Parentheses have the highest precedence
let result1 = 2 * (3 + 4);
console.log(result1); // Output: 14 (Parentheses evaluated first)
// Exponentiation has higher precedence than multiplication
let result2 = 2 + 3 ** 2;
console.log(result2); // Output: 11 (Exponentiation done before addition)
// Unary operators (++ and --) have higher precedence than binary operators
let a = 5;
let b = a++ * 2;
console.log(b); // Output: 10 (Postfix increment evaluated before multiplication)
// Comparison operators have lower precedence than arithmetic operators
let result3 = 5 + 3 < 2 * 4;
console.log(result3); // Output: false (Arithmetic operations evaluated before comparison)
// Logical operators have lower precedence than comparison operators
let result4 = 5 + 3 < 2 * 4 && true;
console.log(result4); // Output: true (Comparison evaluated before logical AND)
It's worth noting that when operators have the same precedence they are evaluated left to right, this is called left-to-right associativity. In summary, operator precedence is the order in which operations are performed in an expression, it's determined by the precedence of operators, with some operators having a higher precedence than others and will be executed first.
Arithmetic Operators:
- Addition (+): Adds numbers together.
- Subtraction (-): Takes away one number from another.
- Multiplication (*): Multiplies numbers.
- Exponentiation ():** Raises one number to the power of another.
- Division (/): Divides one number by another.
- Modulus (%): Returns the remainder after division.
Comparison Operators:
- Equal to (==): Checks if two values are equal (with type coercion).
- Equal value and equal type (===): Compares both value and type.
- Not equal to (!=): Checks if two values are not equal (with type coercion).
- Not equal value or not equal type (!==): Compares both value and type.
- Greater than (>): Checks if the left value is greater than the right one.
- Less than (<): Checks if the left value is less than the right one.
- Greater than or equal to (>=): Compares if the left value is greater than or equal to the right one.
- Less than or equal to (<=): Compares if the left value is less than or equal to the right one.
Assignment Operators:
- Assignment (=): Assigns a value.
- Addition assignment (+=): Adds the right operand to the left and assigns the result.
- Subtraction assignment (-=): Subtracts the right operand from the left and assigns the result.
- Multiplication assignment (*=): Multiplies the left operand by the right and assigns the result.
- Division assignment (/=): Divides the left operand by the right and assigns the result.
- Remainder assignment (%=): Divides the left operand by the right and assigns the remainder.
- Exponentiation assignment (=):** Raises the left operand to the power of the right and assigns the result.
Logical Operators :
- Assignment (=): Assigns a value.
- Logical OR (||): Returns true if at least one condition is true.
- Logical NOT (!): Negates the value of a condition.
Ternary Operator :
- A concise way of writing conditional statements: condition ? exprIfTrue : exprIfFalse.
typeof Operator :
- Determines the type of a variable or expression.
- Returns a string indicating the type of the operand.
Operator Precedence :
- Determines the order of operations in an expression.
- Some operators have higher precedence than others and are executed first.
- What are operators in programming?
- What is operand?
- Explain arithmetic operators.
- Explain comparison operators.
- Explain assignment operators.
- Explain the difference between =, == and === operators.
- Explain logical operators.
- Explain the ternary operator.
- Explain typeof operator.
- Describe operator precedence in JavaScript. How does it determine the order in which operations are executed?