JavaScript arithmetic operators

 Lesson 7: JavaScript arithmetic operators



Before we begin let's understand that in JavaScript the variables are case sensitive.

This means myCar is different than myCAR. Just a great thing to remember.

Just like in math, JavaScript supports various operators. It also has some special ones to do stuff. Let's explore.

Add numbers using the + operator.

var x = 5 + 10; //This will hold the value 15 in variable x.

If you are confused, revisit the lesson on comments and assignment operator. We will start throwing bit's of code in.

To subtract numbers we use the - operator.

var x = 15 - 5; //This will hold the value 10 in variable x.

To multiply numbers you use * operator.

var x = 5 * 5;

To divide numbers you use the / operator.

var x = 12 / 2;

You might have not see this. But we have a increment operator in JavaScript. It is represented by ++. It adds one to the number. These also eliminate the need of equal sign or simple assignment operator.

For instance lets consider a scenario where you want to add one to a specific number. You normally would do this:

x = x + 1

But, using increment operator, you can do it just by going...

x++;

Just like the increment operator, we have a decrement operator which subtracts one from the variable. You would use it instead of x = x - 1.

x--;

We also have an operator to get the remainder of division. We use the % for that. It is called remainder operator. Not modulus operator. Ask me why.

var x = 13 % 2;

Tell us in the comment below what the reminder is for this. How about 1 % 5;

We can also do exponents using **

var x = 2 ** 2;

Tell us what the value will be in comments again. We will shortly learn how to print stuff. Hang on. :)

[sc name="editor" ]



Post a Comment

0 Comments

React