Operators (Part 1)

Go back to JavaScript Index

There are a lot of different operators used in programming. We will take a look at some of them here.

Assignment operators

As shown in the examples on the previous page, assignment operators are used to assign a value.

As it is said that repetition promotes understanding, let's have another look at how to use an assignment operator to assign a value to a variable named currentNumOfRainyDays:

let currentNumOfRainyDays = 24;
1.0 | Declaring a variable and assigning a value to it

If we wish to increment the value of the variable by 1, there are a number of ways to do so:

+ 1

We can increment the value by 1, simply by adding one to the current value:

currentNumOfRainyDays = currentNumOfRainyDays + 1;
1.1 | Incrementing the value by 1 using + 1

Be aware that you have to declare the value and assign a value to it as we did in example 1.0 before we can increment the value this way.

+=

Another way to increment the value is by using the assignment operator +=:

currentNumOfRainyDays += 1;
1.2 | Icrementing the value by 1 using +=

The + sign indicates that we take the current value of the variable and then adds whatever comes after the = sign.

Assignment

Use console.log() to 1: log the value just after the variable has been declared and 2: to log the value right after the value of the variable has been changed.

-=

If we want to decrement the value, we can use -= instead:

let numOfDaysUntilWeekend = 2;
numOfDaysUntilWeekend -= 1;
1.3 | Decrementing the value using -=

Arithmetic Operators

Arithmetic is the study of numbers, and in connection with JavaScript the traditional arithmetic operations like addition, subtraction, multiplication and division are put into play using the signs:

  • +
  • -
  • *
  • /
  • %

In addition, there are the signs ++ (incrementation) and -- (decrementation). We will get back to those later on.

Examples of use

let r = 15;
let s = 5;
let t = r + s;
let u = r - s;
let v = t / u;
let x = r * v;
let y = s % v;
1.4 | The use of arithmetic operators

Mental arithmetic

What is the value t, u, v, x and y?

String concatenation

When we wish to concatenate to strings, we can use the + sign as well:

console.log("Hello " + "- what's your name?");
1.5 | String concatenation

The same thing applies, if the strings are stored in variables:

let greeting = "Hello ";
let question = "- what's your name?";
console.log(greeting + question);
1.6 | String concatenation with values

String interpolation

Introduced in ES2015, string interpolation is done using template literals:

let name = prompt("What's your name?");
console.log(`Well, hello there ${name} !`);
1.7 | String interpolation

Notice 1: the use of backticks instead of normal quotation marks, and 2: that the name of the variable is wrapped in ${ }.

Next up

In the next lesson, we will have a look at the use of conditional statements in JavaScript.

Next up: Conditional Statements