JavaScript(JS) Operators
What is an Operator?
In JavaScript, an operator is a special symbol or keyword that performs an operation on one or more values (operands) and returns a result. JavaScript supports a wide variety of operators, including:
Arithmetic operators: perform mathematical operations on numeric operands. Examples include
+
(addition),-
(subtraction),*
(multiplication),/
(division), and%
(modulo).Comparison operators: compare two operands and return a Boolean value (
true
orfalse
). Examples include==
(equality),!=
(inequality),>
(greater than),<
(less than),>=
(greater than or equal to), and<=
(less than or equal to).Logical operators: combine two or more Boolean values and return a Boolean result. Examples include
&&
(logical AND),||
(logical OR), and!
(logical NOT).Assignment operators: assign a value to a variable. Examples include
=
(assignment),+=
(add and assign),-=
(subtract and assign),*=
(multiply and assign),/=
(divide and assign), and%=
(modulo and assign).Unary operators: operate on a single operand. Examples include
++
(increment),--
(decrement),+
(unary plus),-
(unary minus), and!
(logical NOT).Conditional (ternary) operator: provide a shorthand way of writing conditional expressions. The syntax of the conditional operator is
condition ? exprIfTrue : exprIfFalse
. For example,x > 10 ? "greater than 10" : "less than or equal to 10"
.
There are also many other operators in JavaScript, including bitwise operators, string operators, and others.
JavaScript Operator Types
JavaScript has several types of operators that perform different operations on operands. Here are the main types of operators in JavaScript:
Arithmetic Operators: These operators perform mathematical operations on numeric values. The most common arithmetic operators in JavaScript include addition
+
, subtraction-
, multiplication*
, division/
, and modulo%
.Assignment Operators: These operators assign a value to a variable. The most common assignment operator in JavaScript is
=
. Other examples include+=
,-=
,*=
,/=
, and%=
.Comparison Operators: These operators compare two values and return a Boolean value. The most common comparison operators in JavaScript include
==
(equality),!=
(inequality),>
(greater than),<
(less than),>=
(greater than or equal to), and<=
(less than or equal to).Logical Operators: These operators are used to combine two or more Boolean values and return a Boolean result. The most common logical operators in JavaScript include
&&
(logical AND),||
(logical OR), and!
(logical NOT).Bitwise Operators: These operators perform bitwise operations on values. The most common bitwise operators in JavaScript include
&
(AND),|
(OR),^
(XOR),<<
(left shift), and>>
(right shift).Unary Operators: These operators perform operations on a single operand. The most common unary operators in JavaScript include
++
(increment),--
(decrement),+
(unary plus),-
(unary minus), and!
(logical NOT).Conditional (ternary) Operator: This operator is a shorthand way of writing conditional expressions. The syntax of the conditional operator is
condition ? exprIfTrue : exprIfFalse
.String Operators: These operators are used to concatenate strings. The most common string operator in JavaScript is
+
.Type Operators: These operators are used to determine the type of a value. The most common type operator in JavaScript is
typeof
.Comma Operator: This operator is used to separate multiple expressions in a single statement.
JavaScript Assignment Operators
JavaScript provides several assignment operators that allow you to assign a value to a variable and perform an arithmetic operation in a single step. Here are some of the most commonly used assignment operators in JavaScript:
=
(simple assignment): This operator assigns a value to a variable. For example,x = 10
assigns the value 10 to the variablex
.+=
(addition assignment): This operator adds a value to a variable and assigns the result to the variable. For example,x += 5
is equivalent tox = x + 5
.-=
(subtraction assignment): This operator subtracts a value from a variable and assigns the result to the variable. For example,x -= 5
is equivalent tox = x - 5
.*=
(multiplication assignment): This operator multiplies a variable by a value and assigns the result to the variable. For example,x *= 5
is equivalent tox = x * 5
./=
(division assignment): This operator divides a variable by a value and assigns the result to the variable. For example,x /= 5
is equivalent tox = x / 5
.%=
(remainder assignment): This operator divides a variable by a value and assigns the remainder to the variable. For example,x %= 5
is equivalent tox = x % 5
.
These assignment operators can be combined with arithmetic operators to perform more complex operations. For example, x += y * z
multiplies the values of y
and z
and adds the result to the value of x
.
JavaScript Arithmetic Operators
JavaScript provides several arithmetic operators that perform mathematical operations on numeric values. Here are the most commonly used arithmetic operators in JavaScript:
+
(addition): This operator adds two or more numeric values. For example,3 + 5
returns8
.-
(subtraction): This operator subtracts one numeric value from another. For example,8 - 3
returns5
.*
(multiplication): This operator multiplies two or more numeric values. For example,3 * 5
returns15
./
(division): This operator divides one numeric value by another. For example,15 / 3
returns5
.%
(modulo): This operator returns the remainder after dividing one numeric value by another. For example,15 % 4
returns3
.++
(increment): This operator adds 1 to a numeric value. For example,let x = 5; x++;
setsx
to6
.--
(decrement): This operator subtracts 1 from a numeric value. For example,let x = 5; x--;
setsx
to4
.
Arithmetic operators can be used with variables or with literal values. For example, let x = 5; let y = x + 3;
sets y
to 8
. You can also use parentheses to group operations and specify the order of evaluation. For example, let z = (5 + 3) * 2;
sets z
to 16
.
JavaScript Comparison Operators
JavaScript provides several comparison operators that allow you to compare values and return a boolean value (true
or false
). Here are the most commonly used comparison operators in JavaScript:
==
(equality): This operator compares two values for equality, but performs type coercion if necessary. For example,5 == '5'
returnstrue
.===
(strict equality): This operator compares two values for equality without performing type coercion. For example,5 === '5'
returnsfalse
.!=
(inequality): This operator compares two values for inequality, but performs type coercion if necessary. For example,5 != '6'
returnstrue
.!==
(strict inequality): This operator compares two values for inequality without performing type coercion. For example,5 !== '6'
returnstrue
.<
(less than): This operator compares two values to determine if the left operand is less than the right operand. For example,3 < 5
returnstrue
.>
(greater than): This operator compares two values to determine if the left operand is greater than the right operand. For example,5 > 3
returnstrue
.<=
(less than or equal to): This operator compares two values to determine if the left operand is less than or equal to the right operand. For example,3 <= 3
returnstrue
.>=
(greater than or equal to): This operator compares two values to determine if the left operand is greater than or equal to the right operand. For example,5 >= 5
returnstrue
.
Comparison operators can be used with variables or with literal values. For example, let x = 5; let y = 3; x > y
returns true
. You can also use comparison operators with logical operators to create more complex expressions. For example, (x > y) && (y > z)
returns true
if x
is greater than y
and y
is greater than z
.
JavaScript Logical Operators
JavaScript provides three logical operators that allow you to combine boolean values and return a boolean result:
&&
(logical AND): This operator returnstrue
if both operands are true. For example,true && false
returnsfalse
.||
(logical OR): This operator returnstrue
if at least one operand is true. For example,true || false
returnstrue
.!
(logical NOT): This operator negates a boolean value. For example,!true
returnsfalse
.
Logical operators are often used in conditional statements and loops to control program flow based on the values of boolean expressions. For example, you can use &&
to execute code only if two conditions are true, like this:
let age = 25; let hasDriverLicense = true; if (age >= 18 && hasDriverLicense) { console.log("You can drive!"); } else { console.log("You cannot drive."); }
In this example, the code inside the if
block will only execute if the age
variable is greater than or equal to 18 and the hasDriverLicense
variable is true. If either of these conditions is false, the code inside the else
block will execute instead.
Logical operators can also be used with non-boolean values, such as numbers or strings. In these cases, JavaScript will implicitly convert the non-boolean value to a boolean value before evaluating the expression. Any value that is "truthy" (i.e., not false
, 0
, null
, undefined
, NaN
, or an empty string) is considered true
in a boolean context.
JavaScript Bitwise Operators
JavaScript provides several bitwise operators that allow you to manipulate the binary representation of numbers at the bit level. These operators perform operations on the individual bits of the operands, rather than treating them as whole numbers. Here are the bitwise operators available in JavaScript:
&
(AND): This operator performs a bitwise AND operation on the two operands. It returns a number where each bit is set to 1 only if both corresponding bits of the operands are 1. For example,0b1010 & 0b1100
returns0b1000
.|
(OR): This operator performs a bitwise OR operation on the two operands. It returns a number where each bit is set to 1 if either corresponding bit of the operands is 1. For example,0b1010 | 0b1100
returns0b1110
.^
(XOR): This operator performs a bitwise XOR operation on the two operands. It returns a number where each bit is set to 1 if the corresponding bits of the operands are different. For example,0b1010 ^ 0b1100
returns0b0110
.~
(NOT): This operator performs a bitwise NOT operation on a single operand. It returns a number where each bit is inverted (i.e., 0 becomes 1 and 1 becomes 0). For example,~0b1010
returns0b0101
.<<
(left shift): This operator shifts the bits of the left operand to the left by the number of bits specified by the right operand. For example,0b1010 << 2
returns0b101000
.>>
(right shift): This operator shifts the bits of the left operand to the right by the number of bits specified by the right operand. For positive numbers, it fills the leftmost bits with 0. For negative numbers, it fills the leftmost bits with 1. For example,0b1010 >> 2
returns0b0010
.>>>
(unsigned right shift): This operator is similar to the>>
operator, but it always fills the leftmost bits with 0. For example,0b1010 >>> 2
returns0b0010
.
Bitwise operators are often used in low-level programming, such as network programming, device drivers, and cryptography. They can also be used in other contexts, such as generating random numbers or manipulating graphics data.
JavaScript Spread Operator(ES6)
The spread operator, introduced in ECMAScript 6 (ES6), is denoted by three dots (...
) and is used to spread the contents of an array or an object into another array or object. It allows us to create a new array or object by concatenating or merging the contents of existing arrays or objects. Here are some examples of using the spread operator in JavaScript:
- Spread an array into another array:
const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5, 6]; console.log(arr2); // [1, 2, 3, 4, 5, 6]
Here, the spread operator is used to spread the elements of arr1
into arr2
. This creates a new array arr2
that contains all the elements of arr1
, as well as the additional elements 4, 5, and 6.
- Concatenate multiple arrays:
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const arr3 = [7, 8, 9]; const arr4 = [...arr1, ...arr2, ...arr3]; console.log(arr4); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Here, the spread operator is used to concatenate the elements of arr1
, arr2
, and arr3
into a new array arr4
.
- Merge two objects:
const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const obj3 = { ...obj1, ...obj2 }; console.log(obj3); // { a: 1, b: 2, c: 3, d: 4 }
Here, the spread operator is used to merge the properties of obj1
and obj2
into a new object obj3
.
- Pass arguments to a function:
function sum(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; const result = sum(...numbers); console.log(result); // 6
Here, the spread operator is used to pass the contents of the numbers
array as arguments to the sum
function.
The spread operator provides a convenient way to work with arrays and objects in JavaScript. It can simplify code and make it more readable by avoiding the need for manual iteration or concatenation.
JavaScript Ternary Operator
The ternary operator in JavaScript is a concise way of writing an if-else
statement. It is denoted by the ?
and :
symbols, and has the following syntax:
condition ? expression1 : expression2
Here, condition
is the condition to be evaluated, and expression1
and expression2
are the expressions to be executed depending on whether the condition is true or false.
If condition
is true, expression1
is executed; otherwise, expression2
is executed. The value of the entire expression is the value of the executed expression.
Here are some examples of using the ternary operator in JavaScript:
const x = 5; const y = x > 3 ? "greater than 3" : "less than or equal to 3"; console.log(y); // "greater than 3"
In this example, the ternary operator is used to check if x
is greater than 3. Since x
is 5, which is greater than 3, the value of y
is set to "greater than 3"
.
const age = 20; const isAdult = age >= 18 ? true : false; console.log(isAdult); // true
In this example, the ternary operator is used to check if age
is greater than or equal to 18. Since age
is 20, which is greater than 18, the value of isAdult
is set to true
.
const num = 6; const message = num % 2 === 0 ? "even" : "odd"; console.log(message); // "even"
In this example, the ternary operator is used to check if num
is even or odd. Since num
is even (i.e., its remainder when divided by 2 is 0), the value of message
is set to "even"
.
The ternary operator is a useful tool for writing concise and readable code in JavaScript, especially when the if-else
statement would otherwise be simple and straightforward.