numbers

Like any other programming language, numbers are a key part of programming in JavaScript. In this module we'll simply get you started with some basics on numbers.

File Location

You should be located in the following file:

   javascript-library
        └── 0-PreWork
            └── 1-HTML-Basics
            └── 2-CSS-Basics
            └── 3-JavaScript-Basics
                01-numbers.js       <----You will be working in this file in this module.

Numbers versus Ints

If you are coming from another language like C# or Java, you might have heard numbers referred to as ints or integers. In JavaScript, we refer to them as numbers.

Printing Numbers

Let's start by printing a few numbers to our console window. Remember F8 or fn + F8 will run the JavaScript code for you:

console.log(1);
console.log(1 + 1);
console.log(1.1);
console.log(1.1 * 1.1);

Notice that we are not only printing numbers, but executing some math operations as well.

Basic Operators

Just like in basic arithmetic, there are some basic operators that you need to know. These are simple enough that we can show one single example for each one:

console.log(5 + 5);
console.log(6 - 6);
console.log(7 * 7);
console.log(8 / 8);

Modulus Operators

A common operator that stumps newcomers is called the modulus operator. Type the following, and see the result:

console.log(10 % 5); // Result = 0 
console.log(10 % 4); // Result = 2
console.log(10 % 9); // Result = 1

Why do we get such odd numbers? Surely, this is not division, multiplication, subtraction, or addition, right?

No, not at all.

Division is the closest thing, as the result of these operations is the remainder:

Here's how this goes in simple math:

10 / 5 = 2 with a remainder of 0.
10 / 4 = 2 with a remainder of 2.
10 / 9 = 1 with a remainder of 1.

Hence, the modulus operator yields a remainder.

Shorthand Operators

Another difficult one for beginners is the shorthand operator. Consider the following:

What would y equal at the end of the operation?

var y = 5;
y = y + 1;

This works like this:

var y = 5;
y = 5 + 1; //6
y = y + 1; //7

The value of y is now equal to 7, meaning the value of y will change over time. We'll talk more about this as we get into variables.

Shorthand Operators

Shorthand operators look like this:

var x = 5;
x += 1;  // Same as saying x = x + 1
console.log(x); //6

Practice

Print out the following values to the console:

var z = 10;
console.log(z);
z+=1;
console.log(z);

var a = 20;
a-=1;

var b = 25;
b*=2;

var c = 50;
c/=2;

Shorthand Operators

Age Problem

In your head, figure out the age when we log it. Then, type in the code and see if you were right:

var age = 40;
age += 1;
age -= 20;
age *= 20;
console.log(age);

Last updated