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:
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:
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:
Modulus Operators
A common operator that stumps newcomers is called the modulus operator. Type the following, and see the result:
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:
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?
This works like this:
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:
Practice
Print out the following values to the console:
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:
Last updated