DEV Community

Cover image for JavaScript: Back to Basics with Operators

Posted on • Updated on

JavaScript: Back to Basics with Operators

I’m in the process of making a career change into Web Development and learning JavaScript has been a journey and an adventure at the same time. As with anything new, mastery only comes once the basics have been conquered. A refresher from time to time never hurts either.

For anyone with a non-technical background I think it’s important to review the basics of operators. Operators are the symbols used to make basic mathematical calculations (+, =, -, *, /).

Math operators seem basic enough, right? Math rules indicate multiplication and division are to take place before addition and subtraction. An easy way to remember the rules of multiplication are with a great acronym such as PEMDAS, “Please Excuse My Dear Aunt Sally”.

Parenthesis | Exponents | Multiplication | Division | Addition | Subtraction

For a bit of trivia, speakers of British English know a different acronym for remembering the order of operations “BODMAS”.

Brackets | Orders | Division | Multiplication | Addition | Subtraction

The first time I heard this was a few months ago from a classmate. If I did learn this in school it’s buried in my memory somewhere. If this is old news for you, great. If this is new for you, please continue to pass the knowledge forward and awaken someone else’s rusty brain!

Why is this relevant?

Let’s say a client has a program that needs to figure out how much an item will cost after tax.

itemPrice = 100;
taxRate = .10;  //10% tax rate

//Without PEMDAS the tax rate results in $0.10 in tax on the item. 
itemPrice * 1 + taxRate;

However, if using PEMDAS, you need to ensure the tax rate is calculated first:

itemPrice * (1 + taxRate);

Changing the order of operation by adding the parenthesis results in a rate of $9.90 on one item. That’s a big difference!

In JavaScript the details matter. The difference between a colon and semi-colon matter. And when calculating a function, a loop or a palindrome, the order of commas, brackets, and mathematical operators matter.

Top comments (0)