0% found this document useful (0 votes)
335 views

JavaScript Operators

The document provides an overview of various JavaScript operators, including arithmetic, assignment, comparison, logical, and more. Each operator type is explained with examples demonstrating their usage and functionality. Additionally, it covers advanced operators like the optional chaining operator and BigInt operators, highlighting their significance in JavaScript programming.

Uploaded by

Maya Lee
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
335 views

JavaScript Operators

The document provides an overview of various JavaScript operators, including arithmetic, assignment, comparison, logical, and more. Each operator type is explained with examples demonstrating their usage and functionality. Additionally, it covers advanced operators like the optional chaining operator and BigInt operators, highlighting their significance in JavaScript programming.

Uploaded by

Maya Lee
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

JavaScript Operators

Operators are used to assign values, compare values, perform arithmetic


operations, and more.

There are different types of JavaScript operators:

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Conditional Operators
 Type Operators

JavaScript Arithmetic Operators


 Arithmetic operators are used to perform arithmetic between variables
and/or values.
 Given that y = 5, the table below explains the arithmetic operators:

Oper Name Example Results

+ Addition x=y+2 y=5, x=7

- Subtraction x=y-2 y=5, x=3

* Multiplication x=y*2 y=5, x=10

** Exponentiation x=y**2 y=5, x=25


ES2016
/ Division x=y/2 y=5, x=2.5

% Remainder x=y%2 y=5, x=1

++ Pre increment x = ++y y=6, x=6

++ Post increment x = y++ y=6, x=5

-- Pre decrement x = --y y=4, x=4

-- Post decrement x = y-- y=4, x=5

JavaScript Assignment Operators


Assignment operators are used to assign values to JavaScript variables.

Given that x = 10 and y = 5, the table below explains the assignment


operators:

Oper Example Same As Result

= x=y x=y x=5


+= x += y x=x+y x = 15

-= x -= y x=x-y x=5

*= x *= y x=x*y x = 50

/= x /= y x=x/y x=2

%= x %= y x=x%y x=0

: x: 45 size.x = 45 x = 45

For a tutorial about assignment operators, read our JavaScript Assignment


Tutorial.

ADVERTISEMENT

JavaScript String Operators


The + operator, and the += operator can also be used to concatenate (add)
strings.

Given that t1 = "Good ", t2 = "Morning", and t3 = "", the table below
explains the operators:
Oper Example t1 t2 t3

+ t3 = t1 + t2 "Good " "Morning" "Good


Morning"

+= t1 += t2 "Good Morning" "Morning"

Comparison Operators
Comparison operators are used in logical statements to determine equality
or difference between variables or values.

Given that x = 5, the table below explains the comparison operators:

Oper Name Comparing Returns

== equal to x == 8 false

== equal to x == 5 true

=== equal value and type x === "5" false

=== equal value and type x === 5 true


!= not equal x != 8 true

!== not equal value or type x !== "5" true

!== not equal value or type x !== 5 false

> greater than x>8 false

< less than x<8 true

>= greater or equal to x >= 8 false

<= less or equal to x <= 8 true

For a tutorial about comparison operators, read our JavaScript Comparisons


Tutorial.

Conditional (Ternary) Operator


The conditional operator assigns a value to a variable based on a condition.
Syntax Example

(condition) ? x : y (z < 18) ? x : y

Logical Operators
Logical operators are used to determine the logic between variables or
values.

Given that x = 6 and y = 3, the table below explains the logical operators:

Oper Name Example

&& AND (x < 10 && y > 1) is true

|| OR (x === 5 || y === 5) is false

! NOT !(x === y) is true

The Nullish Coalescing Operator (??)


The ?? operator returns the first argument if it is
not nullish (null or undefined).
Otherwise it returns the second argument.

Example
let name = null;
let text = "missing";
let result = name ?? text;

The Optional Chaining Operator (?.)


The ?. operator returns undefined if an object
is undefined or null (instead of throwing an error).

Example
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
// Ask for car name:
document.getElementById("demo").innerHTML = car?.name;

JavaScript Bitwise Operators


Bit operators work on 32 bits numbers. Any numeric operand in the
operation is converted into a 32 bit number. The result is converted back to a
JavaScript number.

Oper Name Example Same as Result Decimal

& AND x=5&1 0101 & 0001 0001 1

| OR x=5|1 0101 | 0001 0101 5

~ NOT x=~5 ~0101 1010 10


^ XOR x=5^1 0101 ^ 0001 0100 4

<< Left shift x = 5 << 1 0101 << 1 1010 10

>> Right shift x = 5 >> 1 0101 >> 1 0010 2

>>> Unsigned right x = 5 >>> 1 0101 >>> 1 0010 2

Note
The table above uses 4 bits unsigned number. Since JavaScript uses 32-bit
signed numbers, ~ 5 will not return 10. It will return -6.

~00000000000000000000000000000101 (~5)
will return
11111111111111111111111111111010 (-6)

The typeof Operator


The typeof operator returns the type of a variable, object, function or
expression:

Example
typeof "John" // Returns string
typeof 3.14 // Returns number

Please observe:

 The data type of NaN is number


 The data type of an array is object
 The data type of a date is object
 The data type of null is object
 The data type of an undefined variable is undefined

Example
typeof "John"
typeof 3.14
typeof NaN
typeof false
typeof [1, 2, 3, 4]
typeof {name:'John', age:34}
typeof new Date()
typeof function () {}
typeof myCar
typeof null

Note
You cannot use typeof to define if a JavaScript object is an array or a date.

Both array and date return object as type.

The delete Operator


The delete operator deletes a property from an object:

Example
const person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
delete person.age;

The delete operator deletes both the value of the property and the property
itself.
After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no


effect on variables or functions.

Note
The delete operator should not be used on the properties of any predefined
JavaScript objects (Array, Boolean, Date, Function, Math, Number, RegExp,
and String).

This can crash your application.

The Spread (...) Operator


The ... operator expands an iterable into more elements:

Example
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];

const year = [...q1, ...q2, ...q3, ...q4];

The ... operator can be used to expand an iterable into more arguments for
function calls:

Example
const numbers = [23,55,21,87,56];
let maxValue = Math.max(...numbers);

The in Operator
The in operator returns true if a property is in an object, otherwise false:

Object Example
const person = {firstName:"John", lastName:"Doe", age:50};
("firstName" in person);
("age" in person);

Note
You cannot use in to check for array content like ("Volvo" in cars).

Array properties can only be index (0,1,2,3...) and length.

See the examples below.

Examples
const cars = ["Saab", "Volvo", "BMW"];
("Saab" in cars);

const cars = ["Saab", "Volvo", "BMW"];


(0 in cars);
(1 in cars);
(4 in cars);
("length" in cars);

Predefined Objects
("PI" in Math);
("NaN" in Number);
("length" in String);

The instance of Operator


The instanceof operator returns true if an object is an instance of a
specified object:
Example
const cars = ["Saab", "Volvo", "BMW"];

(cars instanceof Array) // Returns true


(cars instanceof Object) // Returns true
(cars instanceof String) // Returns false
(cars instanceof Number) // Returns false

The void Operator


The void operator evaluates an expression and returns undefined. This
operator is often used to obtain the undefined primitive value, using
"void(0)" (useful when evaluating an expression without using the return
value).

Example
<a href="javascript:void(0);">
Useless link
</a>

<a href="javascript:void(document.body.style.backgroundColor='red');">
Click me to change the background color of body to red
</a>

JavaScript operators are symbols or keywords used to perform


operations on values and variables. They are the building blocks of
JavaScript expressions and can manipulate data in various ways.
JavaScript Operators

There are various operators supported by JavaScript.


1. JavaScript Arithmetic Operators
Arithmetic Operators perform mathematical calculations like addition,
subtraction, multiplication, etc.
const sum = 5 + 3; // Addition
const diff = 10 - 2; // Subtraction
const p = 4 * 2; // Multiplication
const q = 8 / 2; // Division
console.log(sum, diff, p, q);

Output
8 8 8 4

 + adds two numbers.


 – subtracts the second number from the first.
 * multiplies two numbers.
 / divides the first number by the second.
2. JavaScript Assignment Operators
Assignment operators are used to assign values to variables. They can
also perform operations like addition or multiplication before assigning
the value.
let n = 10;
n += 5;
n *= 2;
console.log(n);

Output
30

 = assigns a value to a variable.


 += adds and assigns the result to the variable.
 *= multiplies and assigns the result to the variable.
3. JavaScript Comparison Operators
Comparison operators compare two values and return a boolean (true
or false). They are useful for making decisions in conditional
statements.
console.log(10 > 5);
console.log(10 === "10");

Output
true
false

 > checks if the left value is greater than the right.


 === checks for strict equality (both type and value).
 Other operators include <, <=, >=, and !==.
4. JavaScript Logical Operators
Comparison operators are mainly used to perform the logical
operations that determine the equality or difference between the
values.
const a = true, b = false;
console.log(a && b); // Logical AND
console.log(a || b); // Logical OR

Output
false
true

 && returns true if both operands are true.


 || returns true if at least one operand is true.
 ! negates the boolean value.
5. JavaScript Bitwise Operators
Bitwise operators perform operations on binary representations of
numbers.
const res = 5 & 1; // Bitwise AND
console.log(res);

Output
1

 & performs a bitwise AND.


 | performs a bitwise OR.
 ^ performs a bitwise XOR.
 ~ performs a bitwise NOT.
6. JavaScript Ternary Operator
The ternary operator is a shorthand for conditional statements. It takes
three operands.
const age = 18;
const status = age >= 18 ? "Adult" : "Minor";
console.log(status);

Output
Adult

condition ? expression1 : expression2 evaluates expression1 if the


condition is true, otherwise evaluates expression2.
7. JavaScript Comma Operator
Comma Operator (,) mainly evaluates its operands from left to right
sequentially and returns the value of the rightmost operand.
let n1, n2
const res = (n1 = 1, n2 = 2, n1 + n2);
console.log(res);

Output
3

 Each expression is evaluated from left to right.


 The final result of the expression is the rightmost value.
8. JavaScript Unary Operators
Unary operators operate on a single operand (e.g., increment,
decrement).
let x = 5;
console.log(++x); // Pre-increment
console.log(x--); // Post-decrement (Output: 6, then x becomes 5)

Output
6
6

 ++ increments the value by 1.


 — decrements the value by 1.
 typeof returns the type of a variable.
9. JavaScript Relational Operators
JavaScript Relational operators are used to compare its operands
and determine the relationship between them. They return a Boolean
value (true or false) based on the comparison result.
const obj = { length: 10 };
console.log("length" in obj);
console.log([] instanceof Array);

Output
true
true

 in checks if a property exists in an object.


 instanceof checks if an object is an instance of a constructor.
10. JavaScript BigInt Operators
BigInt operators allow calculations with numbers beyond the safe
integer range.
const big1 = 123456789012345678901234567890n;
const big2 = 987654321098765432109876543210n;
console.log(big1 + big2);

Output
1111111110111111111011111111100n

 Operations like addition, subtraction, and multiplication work with


BigInt.
 Use n suffix to denote BigInt literals.
11. JavaScript String Operators
JavaScript String Operators include concatenation (+) and
concatenation assignment (+=), used to join strings or combine strings
with other data types.
const s = "Hello" + " " + "World";
console.log(s);

Output
Hello World

 + concatenates strings.
 += appends to an existing string.
12. JavaScript Chaining Operator (?.)
The optional chaining operator allows safe access to deeply nested
properties without throwing errors if the property doesn’t exist.
const obj = { name: "Aman", address: { city: "Delhi" } };
console.log(obj.address?.city);
console.log(obj.contact?.phone);

Output
Delhi
undefined

 ?. safely accesses a property or method.


 Returns undefined if the property doesn’t exist.

You might also like