Categories
JavaScript Basics

Highlights of JavaScript — Variables and Math Expressions

Spread the love

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Variable Naming

We can’t have variable names that start with a number, but we can have variables that have numbers in the middle.

For example, we can write:

let name1 = "james";

but not:

let 1name = "james";

There are more rules to JavaScript variable naming.

A variable name can’t have any spaces.

Variable names can only have letters, numbers, dollar signs and underscores.

Variable names can’t be a reserved JavaScript keyword, but they can contain them.

Capital letters can be used, but we must be aware that variable names are case sensitive.

So name isn’t the same as Name .

JavaScript variable names are usually camelCase. They let us form variables with multiple words and we can read them all easily.

So we can write variable names like firstName to make the 2 words in the variable name clear.

Math Expressions

Most JavaScript programs will do math. Therefore, JavaScript comes with operators for various common math operations.

For example, we can add with the + operator:

let num = 2 + 2;

To subtract, we can use the - operator:

let num = 2 - 2;

Multiplication is done with the * operator:

let num = 2 * 2;

And division is done with the / operator:

let num = 2 / 2;

There’s also the % modulus operator to find the remainder of the left operand divided by the right one.

For example, we can write:

let num = 2 % 2;

We get 0 because 2 is evenly divisible by itself.

The exponentiation operator is denoted by ** . For example, we can use it by writing:

let num =  2 ** 2;

Then we raise 2 to the 2nd power.

The ++ operator adds the variable’s value by 1 and assign it to the variable.

For example:

num++;

is the same as:

num = num + 1;

We can use the expressions with the assignment operator, but we may get results that we don’t expect.

For example, if we have:

let num = 1;
let newNum = num++;

Then newNum is 1 since the original value of num is returned.

On the other hand, if we have:

let num = 1;
let newNum = ++num;

Then newNum is 1 since the latest value of num is returned if ++ is before the num .

Likewise, JavaScript has the -- operator to subtract a variable by 1 and assign the latest value to the variable.

For example, we can write:

let num = 1;
let newNum = num--;

And we get 1 for newNum and:

let num = 1;
let newNum = --num;

then we get 0 for newNum .

How the values are returned work the same way as ++ .

Conclusion

We have to name JavaScript variables by following its rules.

Also, JavaScript comes with many operators for doing math operations.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *