1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
18

Operators in JavaScript

Updated on 09/08/2024240 Views

Operators in JavaScript are the powerhouses behind so many tasks. From the moment we started learning JS development, the simple addition symbol (+) felt incredibly powerful. As we get deeper into JS, the subtle differences between comparison operators (== vs. ===) or the way the assignment operator (=) could be combined with others keep us constantly learning.

Operators become the tools that make coding feel both logical and expressive. I will cover the various operators in JavaScript and explain how we can use them effectively in this tutorial.

What are Operators in JavaScript?

Operators are special symbols that tell JavaScript to perform specific actions or computations. The basic operators in JavaScript work by taking values (called operands) and producing a new result.

We can think of them as tools, just like a hammer drives in nails or a calculator crunches numbers, operators do different things to values. We have operators for basic math (+, -, /), comparing if things are equal (==), manipulating logic (&&, ||), and more.

There are also many special operators in JavaScript that carry out highly specialized computational functions. We will learn about all these operators in JavaScript in this guide.

Importance of Operators in JavaScript

Operators are fundamental to just about any programming language, and JavaScript is no exception. Here's why they're crucial:

  • Manipulating data: Operators let you transform data in all sorts of ways – calculating a sale price, changing the color of an element, determining if a user is old enough to access a webpage...the possibilities are endless.
  • Writing expressions: Expressions are combinations of values, variables, and operators. Operators are the glue that lets you create complex calculations or logical tests within expressions.
  • Controlling program flow: Conditional statements (like if...else) rely heavily on comparison operators to decide which code should execute. Loops use them for counting iterations. Operators are essential for making your code "smart".

Types of Operators in JavaScript

Let us discuss the different types of operators in JavaScript. I will explain different operators in JavaScript with the help of examples.

Arithmetic Operators in JavaScript

These operators let you perform fundamental math calculations within your JavaScript code. The arithmetic operators follow the usual mathematical order of precedence (often remembered as PEMDAS or BODMAS). JavaScript will attempt to convert non-numeric values to numbers when used with arithmetic operators.

Here are the arithmetic operators:

  • Addition (+) Adds two numbers together.

Example: 10 + 5 // Result: 15

  • Subtraction (-) Subtracts one number from another.

Example: 12 - 3 // Result: 9

  • Multiplication (*) Multiplies two numbers.

Example: 5 * 7 // Result: 35

  • Division (/) Divides one number by another.

Example: 25 / 5 // Result: 5

  • Modulus (%) Gives the remainder after dividing one number by another.

Example: 11 % 3 // Result: 2

  • Exponentiation (**) Raises a number to the power of another (introduced in ES2016).

Example: 2 ** 3 // Result: 8 (2 to the power of 3)

  • Increment (++) Increases a number by 1. Can be used before (pre-increment) or after (post-increment) a variable, with slightly different effects.

Example: let x = 5; y = ++x; // x is now 6, y is also 6

  • Decrement (--) Decreases a number by 1. Similar pre/post-increment behavior as ++.

Example: let x = 5; y = x--; // x is now 4, y is 5

Comparison Operators in JavaScript

These operators are used to compare two values, resulting in either true or false. They are essential for making decisions in your code.

  1. Equality:
  • Equal to (==) Evaluates if values are equal after potential type coercion (trying to convert them to the same type).

Example: `"5" == 5 // Results in true (string "5" is converted to number 5)

  • Strict Equal to (===) Evaluates if values are equal in both value and type. No type coercion is done.

Example: `"5" === 5 // Results in false (types don't match)

  1. Inequality:
  • Not Equal to (!=) The opposite of ==. Checks if values are not equal after potential type coercion.
  • Strict Not Equal to (!==) The opposite of ===. Checks for inequality in both value and type.
  1. Magnitude Comparisons:
  • Greater Than (>) Evaluates if the left operand is larger than the right operand.
  • Greater Than or Equal (>=) Evaluates if the left operand is larger than or equal to the right operand.
  • Less Than (<) Evaluates if the left operand is smaller than the right operand.
  • Less Than or Equal (<=) Evaluates if the left operand is smaller than or equal to the right operand.

I also want to mention that comparison operators default to using strict equality (===) in most cases to avoid unexpected type coercion surprises. Comparison results are used in conditional statements (if, else) and loops to control how your program runs.

Logical Operators in JavaScript

Logical operators are used to combine and manipulate Boolean (true/false) values or expressions that evaluate true/false. Logical operators are heavily used in if statements to create complex conditions.

Here are the logical operators:

  • AND (&&): Returns true if both operands are truthy. Otherwise, it returns the first falsy operand or the last value if all operands were falsy.

Example: (age >= 18 && hasLicense) // true if the person is 18+ years old and has a driving license

  • OR (||): Returns the first truthy operand. If all operands are falsy, it returns the last operand.

Example: (username === "" || password === "") // true if either username or password is empty

  • NOT (!): Reverses the logical state of its operand. If an operand is truthy, it returns false; if falsy, it returns true.

Example: !isLoggedIn // true if the user is not logged in

Note: I want to mention that && and || operate with "short-circuiting," meaning evaluation might stop early if the result is already determined from the first operand. Also, if you enjoy a more formal approach, logical operators can be summarized with truth tables.

Assignment Operators in JavaScript

The basic assignment operator (=) is the most common operator, it assigns the value on its right side to the variable on its left.

Example: let score = 10;

Assignment with shorthand: These operators combine assignment with other operations, providing a compact way to modify variables:

Addition Assignment (+=): Adds the value on the right to the existing variable and reassigns the new result.

Example: let x = 5; x += 3; // x is now 8

Subtraction Assignment (-=): Subtracts the value on the right from the existing variable and reassigns the result.

Example: let x = 10; x -= 2; // x is now 8

Multiplication Assignment (*=): Multiplies the existing variable with the value on the right and reassigns.

Example: let x = 2; x *= 5; // x is now 10

Division Assignment (/=): Divides the existing variable by the value on the right and reassigns.

Example: let x = 20; x /= 4; // x is now 5

Modulus Assignment (%=): Calculates the remainder after division and reassigns it to the existing variable.

Example: let x = 13; x %= 5; // x is now 3

Exponentiation Assignment (**=): Raises the existing variable to the power of the value on the right and reassigns.

Example: let x = 3; x **= 2; // x is now 9

I would also like to mention these shorthand forms are equivalent to longer expressions (like x = x + 3) but more concise. They are a common feature in many programming languages.

Conditional (Ternary) Operators in JavaScript

Conditional operators are great for simple conditional assignments where you want to keep your code concise.

Structure: condition ? expressionIfTrue : expressionIfFalse

How it Works:

  1. The condition is evaluated.
  2. If the condition results in a truthy value, expressionIfTrue is executed.
  3. If the condition is falsy, expressionIfFalse is executed.

Example: let age = 25; let message = (age >= 18) ? "Eligible to vote" : "Too young";

Bitwise Operators in JavaScript

Bitwise operators work directly on the binary representation of numbers. Bitwise operators are less common in everyday JavaScript and are often used for low-level programming, network protocols, or optimizations.

Here are the bitwise operators:

  • AND (&) Compares corresponding bits, result bit is 1 if both bits are 1.
  • OR (|) Result bit is 1 if either bit is 1.
  • XOR (^) Result bit is 1 if bits are different.
  • NOT (~) Inverts each bit.
  • Left Shift (<<) Shifts bits to the left.
  • Right Shift (>>) Shifts bits to the right.

Other Operators in JavaScript

Here are some other important operators in JavaScript:

  • typeof: Returns a string denoting the data type of a value.
  • delete: Removes a property from an object.
  • in: Checks if a property exists within an object or its prototype chain.
  • instanceof: Checks if an object is an instance of a particular class or constructor function.

Operators in JavaScript Precedence

Operator precedence dictates the order in which different operators are executed within an expression. This hierarchy is crucial because it directly affects the calculated outcome.

Why does it matter? Imagine a calculation like this: 10 + 5 * 2

  1. Should we add 10 + 5 first (result = 30)?
  2. Or multiply 5 * 2 first (result = 20)?

Precedence rules will determine this. It's easiest to see precedence with a table. Operators higher in the table are evaluated before those lower:

Category

Operators

Associativity

Grouping

()

Left-to-right

Member Access

. [] ?.

Left-to-right

Post Increment

++ -- (postfix)

Left-to-right

Other

new (object creation)

Right-to-left

Logical NOT

!

Right-to-left

Prefix Increment

++ -- (prefix)

Right-to-left

Arithmetic & Other

+ - (unary) ~ typeof void delete

Right-to-left

Exponentiation

**

Right-to-left

Arithmetic

* / %

Left-to-right

Arithmetic

+ -

Left-to-right

Bitwise Shift

<< >> >>>

Left-to-right

Comparison

< <= > >=

Left-to-right

Equality

== != === !==

Left-to-right

Bitwise

&

Left-to-right

Bitwise

^

Left-to-right

Logical

`

Left-to-right

Ternary

condition ? expression1 : expression2

Right-to-left

Assignment

= += -= *= /= %= **=

Right-to-left

Other

Left-to-right

Examples and Common Use Cases

We will now look at the practical applications of computational expression and operators in JavaScript through compilable programs. It is important to try these out yourself as wwell to understand the interaction between variables and operators in JavaScript. Here are some common types of operators in JavaScript with example programs.

Mathematical Calculations

Code:

// Basic arithmetic

let num1 = 15;

let num2 = 4;

console.log(num1 + num2); // Addition: Output: 19

console.log(num1 - num2); // Subtraction: Output: 11

console.log(num1 * num2); // Multiplication: Output: 60

console.log(num1 / num2); // Division: Output: 3.75

console.log(num1 % num2); // Modulus (remainder): Output: 3

// Increment/Decrement

let x = 10;

console.log(x++); // Post-increment (use x then increment): Output: 10

console.log(x); // Now x is 11

console.log(--x); // Pre-decrement (decrement then use x): Output: 10

Conditional Logic

Code:

let age = 20;

let isAdult = (age >= 18);

if (isAdult) {

console.log("Eligible to vote");

} else {

console.log("Too young to vote");

}

// Ternary Operator

let message = (age >= 21) ? "Can drink" : "Cannot drink";

console.log(message);

String Manipulation

Code:

let greeting1 = "Hello";

let greeting2 = "World";

// Concatenation

let fullGreeting = greeting1 + " " + greeting2;

console.log(fullGreeting); // Output: Hello World

// String length

console.log(fullGreeting.length); // Output: 11

Object Property Manipulation

Code:

let person = {

name: "Alice",

city: "New York",

hasPets: true

};

// Accessing properties

console.log(person.name); // Output: Alice

console.log(person["city"]); // Also works

// Modifying properties

person.city = "London";

console.log(person.city); // Output: London

// Adding properties

person.age = 30;

console.log(person);

// Deleting properties

delete person.hasPets;

console.log(person);

If you wish to master JS, you can check out upGrad’s full stack development courses.

Best Practices and Tips

Readability

  • Parentheses for clarity: Even when operator precedence would technically handle the order correctly, liberally use parentheses to make complex expressions easier to understand for both you and others.

Example: (num1 * num2) + (num3 / num4) is clearer at a glance than relying on precedence alone.

  • Spacing: Add spaces around operators to visually separate them within expressions, aiding readability.

Performance Considerations

  • Bitwise optimization: In specific cases where you're working with integers, bitwise operators can offer micro-optimizations over regular arithmetic. However, modern JavaScript engines are highly optimized, so always prioritize readability first.
  • Profiling: If performance is truly critical in a code section, use profiling tools to identify bottlenecks. Don't optimize prematurely based on assumptions about operator performance.

Common Mistakes

Here are some common mistakes we make when working with operators:

  • Precedence confusion: One of the most frequent issues! Either refresh yourself regularly on the precedence table or use parentheses to be safe.
  • Equality confusion (== vs ===): Remember === (strict equality) is generally the safer default to avoid surprises due to type coercion.
  • Ignoring short-circuit behavior: Be aware that && and || won't always evaluate every operand, this can be used for neat logic but also lead to bugs if not intended.

Additional Tips

Here are two final tips for you that I have gathered from my experience:

  • Write test cases with diverse inputs to catch unexpected behavior due to operator usage.
  • Get another pair of eyes to review, especially with complex expressions. They might spot something you overlooked!

Wrapping Up

Even though I'm comfortable with most operators now, I still sometimes find myself double-checking the nuances of a less common one, or being surprised by the results due to precedence rules.

Operators are a testament to the fact that even in the familiar parts of a language, there's always potential to refine your understanding. Plus, learning how operators might be implemented differently in other languages adds a whole new dimension of appreciation for how JavaScript works!

If you wish to learn software engineering, you can check out upGrad’s software engineering courses.

Frequently Asked Questions

1. What is the operators in JavaScript?
Operators in JavaScript are symbols that perform operations (like addition, comparison, or logical operations) on values.

2. What is type operator in JavaScript?
The typeof operator returns a string indicating the data type of a value (e.g., "number", "string", "object").

3. When to use == and === in JavaScript?

  • Use == (loose equality) for type-converting comparisons (e.g., "10" == 10).
  • Use === (strict equality) to check both value and type (e.g., "10" !== 10).

4. What is the use of or operator in JavaScript?
The OR operator (||) performs logical OR. It returns the first truthy operand, otherwise, the last value if all are falsy.

5. Why do we use operator?
We use operators to manipulate data, write expressions that evaluate to values, and control the flow of our programs.

6. What is the use of in operator?
The in operator checks if a specific property exists within an object or its prototype chain.

mukesh

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...