JavaScript Basics #5: Operators

JavaScript Basics #5: Operators
Jan Zavrel
Jan Zavrel Follow June 21, 2021
Share:

You probably remember operators from your math class, so this topic should be pretty familiar.

JavaScript has several built-in arithmetic operators, that allow us to perform calculations on numbers. Here’s the list of these operators including the symbols:

  1. Add: +
  2. Subtract: -
  3. Multiply: *
  4. Divide: /
  5. Remainder: %

Open your JavaScript console in the browser and type the code below, then hit Enter:

console.log(1 + 2); // Prints 3  
console.log(3 - 1); // Prints 2  
console.log(5 * 3); // Prints 15  
console.log(9 / 3); // Prints 3

JavaScript operators

Since we didn’t use the quotes inside the parentheses, the computer evaluated the expression and printed the result. If we wanted to print the characters 3 + 4, we would wrap them in quotes and computer would print them as a string.

The remainder operator (also known as modulo), returns the number that remains after the division of numbers as many times as they evenly can: 11 % 3 equals 2 because 3 fits into 11 three times, leaving 2 as the remainder:

console.log(11 % 3); // Prints 2  
console.log(12 % 3); // Prints 0

String Concatenation

We can use the + operator to append one string to another. This process is called concatenation and works like this:

 console.log('I love ' + 'to code.');

Go ahead and put it to your console to see the results:

Console output

The computer will join the strings exactly as you write them so make sure to include a space at the end of the first string, otherwise they will be lumped together!

Alternatively, you could use a middle space like in the example below, but that’s too much of work:

console.log('middle' + ' ' + 'space');  

By the way, you can always clean the content of the console by clicking that fancy button up there:

Clear the content of the console

Follow me on Medium, Twitter, Facebook and YouTube.

Share:
Jan Zavrel
Written by

Jan Zavrel Follow

Developer, Author, Teacher, Evernote Certified Consultant.