...

/

04 - Operators & Variables

04 - Operators & Variables

Using JavaScript Operators & Variables

Setup

We learned about variables and math operations that we could be using in JavaScript at the beginning of this course. In this chapter, we will put that knowledge to use.

Let’s first create a couple of shapes to have something to work with. Using the ellipse and rect functions let’s create a shape that roughly resembles a cart.

Looking at our rough drawing, I am not entirely happy with its position. I now wish that we drew it more to the right-hand side. Moving the shape now will mean that we would need to increase the value of the x position argument of each of the shape functions.

Let’s assume that we want to add 150 to all these numbers that specify the x position. We can try to do the math in our head and type the result in there but luckily we can do math operations easily with JavaScript. Instead of typing the result of addition, we can just type out the operation needed, and JavaScript will do the calculation for us.

The same thing works with other operators as well; we can do subtraction, multiplication or division in a similar manner.

One thing that we need to keep in mind with operators is the order of operations. You might already know this from your math classes, but some operators take precedence over others. For example, if we wanted to add 2 to a number and then multiply it by 4, we might be tempted to write something like this:

Press + to interact
console.log(10 + 2 * 4);

But in this operation multiplication will happen before addition. 2 will get multiplied with 4 before being added to 10, so this above operation will yield 18 instead of the expected value 48.

To be able to control the order of operations we can use parentheses. For example, we can write the top equation like this:

Press + to interact
var x = (10 + 2) * 4;
console.log(x);

Anything inside parentheses will be evaluated before other operations. In the order of operations, parentheses come first, then the multiplication and division, and then addition and subtraction.

Variables

To be able to evaluate expressions like this will make our job easier in doing calculations. But I think the real problem here, in this example, is the need to type the same number at all these three different spots. This is very repetitive and laborious. This is an instance where usage of a variable would be useful.

Whenever we need a value, and we need to use ...

Access this course and 1200+ top-rated courses and projects.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy