2.6 Operator Precedence in JavaScript: Order of Operations

17 min read
137
Updated: November 21, 2023

In the previous tutorial, we explored “Basic Operators.” Now, in this tutorial, “Operator Precedence in JavaScript,” we’ll delve into the order in which JavaScript executes different operators. Understanding operator precedence is crucial for writing efficient and accurate code.

Operator Precedence

Example 1

Let's begin by considering a simple example:

const currentYear = 2037;
const ageAmit = currentYear - 1989;
const ageAaradhya = currentYear - 2018;

console.log(currentYear - 1989 > currentYear - 2018); // true

At the end of the "Basic Operators" tutorial, I raised a question regarding the sequence of execution in the expression '(currentYear - 1989 > currentYear - 2018)'. Specifically, why do the two subtractions occur before the greater-than (>) comparison operator? In essence, I was curious about why this expression behaves as it does because it does indeed yield the expected result. The value 'currentYear - 1989' clearly exceeds 'currentYear - 2018'.

This behavior is a result of JavaScript's well-defined operator precedence, which dictates the order in which operators are processed. To better understand this, we can refer to a helpful operator precedence table to see how all the different operators are prioritized.

Let's start by exploring the Mozilla Developer Network (MDN) for information on operator precedence. MDN, short for Mozilla Developer Network, is a widely recognized and heavily used documentation resource that we'll refer to frequently in this tutorial. One particular section we'll focus on is the one found at developer.mozilla.org. This site is a valuable resource for learning about JavaScript.

For our current task, we're interested in locating a specific table. You can find this table at the following URL: Operator Precedence Table.

In this table, you'll notice that various operators are listed along with their corresponding precedence levels. Grouping operations using parentheses (()) has the highest precedence, marked with a value of 21. Following that, you'll see the familiar operators such as plus (+), minus (-), plus plus (++), and minus minus (--), all of which share a precedence value of 14. The table also includes other operators, some of which you may not be familiar with yet, but it does include the typeof operator, which we've already encountered.

You'll find the exponentiation (**) operator, along with various other mathematical operators and comparison operators, all with their respective precedence values. Additionally, there are different equality operators and a variety of other operators in this comprehensive table. It's a handy reference for all JavaScript operators.

However, let's not limit our discussion to this specific example. We should delve deeper into understanding how operator precedence works in practice.

It's crucial to know that calculations like "currentYear - 1989" and "currentYear - 2018" are performed before the comparison. Let's refer back to the table to see this in action. The "greater than" (>) operator has a lower precedence value of 9, whereas subtraction (-) has a precedence of 11. What's important to note here is that you don't necessarily need to memorize the specific precedence values. In fact, nobody does. What matters more is having a general understanding of which operators are evaluated first.

Typically, all mathematical operators are evaluated before comparison operators. This approach makes logical sense. With this knowledge, we can explain why the comparison we have in this specific example functions as expected.

In the table, you'll also find information about which operators are executed from left to right and which are executed from right to left. For example, the exponentiation (**) operator is executed from right to left, while most operators, especially the mathematical ones, are evaluated from left to right. As an example, let's consider a calculation like 36 minus 18 minus 9, which should be indeed 9.

console.log(36 - 18 - 9); // 9

We do indeed get 9. However, if the evaluation were from right to left, it would be 9 minus 18 minus 36, resulting in something entirely different. This demonstrates the significance of left-to-right operation in this context.

On the other hand, assignment provides a clear illustration of right-to-left execution. It occupies the lowest position in the precedence table, indicated as number 2.

Now, let me offer a practical example to highlight the importance of this. Consider the declaration of two variables, x and y, which is a new concept. We can simultaneously define two variables as follows:

let x, y;

In one line, we've declared two empty values, so currently, both will hold the value "undefined." Furthermore, we can simplify the expression 36 minus 18 minus 9, which equals 9, and assign it to both x and y. The output will be 9, making x and y both equal to 9:

x = y = 36 - 18 - 9; // Output: x = y = 9

Let's examine these values in the console and predict the outcome.

console.log(x, y); // 9 9

Both x and y have the same result, which is 9. Now, let's break down what's happening.

When JavaScript encounters the line x = y = 36 - 18 - 9;, it begins by considering the operators present. The subtraction operators have the highest precedence (level 11), so they are evaluated first, moving from left to right.

Here's the step-by-step calculation:

  1. 36 - 18 equals 18.
  2. Then, subtracting 9 from the result, you get 9.

So, essentially, the code becomes x = y = 9. Since the equal operators are the only ones left, they are executed from right to left, as per the precedence table.

  1. First, 9 is assigned to y.
  2. Then, the value of y, which is now 9, is assigned to x.

As a result, both x and y end up being 9.

This may seem a bit confusing, but it's essential to evaluate right-to-left. If it were evaluated from left to right, it wouldn't work correctly. For instance, if it were x = y = 9 executed from left to right, x would be equal to y, and y would be undefined at that point since it was declared as an empty variable.

In general, JavaScript follows the order of operations: parentheses, exponentiation, multiplication and division, and then addition and subtraction.

Example 2

To understand the concept of operator precedence, let's begin with the highest-precedence operation, which is grouping using parentheses (). Parentheses work similarly to mathematics, where operations within them are executed first, as you may recall from your school days.

This concept is often referred to as the order of operations, known as PEMDAS (which stands for Parentheses, Exponents, Multiplication, Division, Addition, and Subtraction). An illustrative example involves calculating the average of two values, like the ages of Amit and Aaradhya.

First, let's log their ages to the console:

console.log(ageAmit, ageAaradhya); // 48 19

Now, if we want to calculate their average age, we add their ages together and then divide by 2 (since there are only two values):

const avgAge = (ageAmit + ageAaradhya) / 2;

Considering operator precedence, grouping with parentheses () takes precedence over division /. In our precedence table, grouping has a precedence of 18, while division is at 12. Therefore, what occurs first is that ageAmit and ageAaradhya are added together inside the parentheses, and then the result is divided by 2. In essence, everything enclosed in the parentheses is evaluated first, followed by the division operation.

FAQs on Operator Precedence in JavaScript

Learning is a dynamic process, and it's completely normal to encounter questions and uncertainties along your learning journey. To support you in navigating this path, we've compiled a set of Frequently Asked Questions (FAQs) related to Operator Precedence in JavaScript. Whether you have doubts or require clarification on precedence usage, you'll likely discover the answers within the following FAQs. Feel free to explore and enhance your comprehension of Operator Precedence.

OPERATOR PRECEDENCE CODE CHALLENGE: Calculate Savings

You're tasked with helping people track their savings over time. You'll write code to calculate and display their savings.

Here's what you need to do:

  1. Create variables for initialSavings, monthlyIncome, expenses, and months. Initialize these variables with appropriate values.
  2. Calculate the monthly savings, which is the difference between monthlyIncome and expenses.
  3. Calculate the total savings at the end of the specified number of months. Use a loop to accumulate the savings each month. The formula to calculate total savings is: totalSavings = initialSavings + (monthlySavings * months).
  4. Log the totalSavings to the console.

BONUS Challenge:

  1. Determine if the individual has saved a significant amount. Create a boolean variable significantSavings and set it to true if totalSavings is greater than or equal to a certain amount (you choose). Log the value of significantSavings to the console.

Test Data:

Here are some sample values for your variables:

  • initialSavings: $2000
  • monthlyIncome: $3500
  • expenses: $1200
  • months: 12

Your code should work with these values and display both the total savings and whether the savings are significant based on the bonus challenge.

Great work, learners! Now it's your turn to tackle this coding challenge. Write the code to solve the problem described above and submit it in the comment box below. We're excited to see your solutions!

Avatar for Amit

Amit (16)

Hello! I'm Amit Kumar, a passionate teacher specializing in web development and digital marketing. With several years of experience in the industry, I am dedicated to sharing my knowledge and expertise to empower aspiring learners like you.

Teaching Philosophy:

I believe in creating a dynamic and engaging learning environment where students can thrive. My teaching approach focuses on hands-on experience, practical applications, and real-world examples. I strive to make complex concepts understandable and enjoyable, ensuring that you not only grasp the fundamentals but also develop the skills necessary to excel in web development and digital marketing.

Web Development Expertise:

As a web development instructor, I am well-versed in HTML, CSS, JavaScript, and various frameworks such as React and Angular. I will guide you through the process of building responsive and user-friendly websites, exploring topics like front-end development, back-end integration, database management, and more. Together, we will delve into the latest trends and best practices in web development, equipping you with the tools to create stunning online experiences.

Digital Marketing Mastery:

In the rapidly evolving digital landscape, digital marketing is crucial for businesses to thrive. Through my digital marketing courses, I will help you navigate the intricacies of search engine optimization (SEO), social media marketing, content strategy, email marketing, and analytics. Gain insights into effective marketing techniques, harness the power of data-driven decision-making, and learn how to craft compelling campaigns that drive results.

Passion for Teaching:

Teaching is not just a profession for me; it's my passion. I find great joy in witnessing my students grow and succeed. I am committed to fostering a supportive learning community where questions are encouraged, ideas are shared, and challenges are overcome together. I am here to guide you every step of the way and provide the necessary resources for your personal and professional development.

Join me on this exciting journey of learning and discovery. Let's unlock your potential in web development and digital marketing together. Enroll in my courses today and embark on a transformative educational experience that will propel your career forward.
Start Learning Today!

ALSO READ:  1.3 Understanding the role of JavaScript in web development
5 1 vote
Article Rating
Subscribe
Notify of

guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Scroll to Top