Numbers in JavaScript In-Depth

A large part of a programmer’s life will be spent using numbers. Luckily for us, the computer does most of the mental calculations. In this blog post, I will give an easy introduction to numbers in JavaScript and an in-depth look at how numbers work.

Using Numbers in JavaScript

In order to use a number in JavaScript, all we have to do is “initialize” a number. In JavaScript this simply means, put a number inside a variable like this:

let dogs = 4;

By using the equal sign, we simply place a number inside a variable for storage and safe keeping. What’s the point of programming if you can’t store data, right?

Integer vs. Float in JavaScript

Another unique (and awesome) aspect of JavaScript is that numbers are “one size fits all”. You can place whole number (also known as a integer!), a decimal number, and very LARGE numbers without having to know the difference.

let dogs = 4; //Whole number (aka "integers")
let cats = 6.4; //Decimal number (aka "floating point numbers")
let bird = -4555556.23424 //Negative number
let color = 0xFF; //Hexadecimal values

In most programming languages, you must clearly define numbers as integer, float, and/or large numbers. But in JavaScript, it is really anything goes and this is very convenient. This “anything goes attitude” comes at a price and that is most developers have no idea the difference between a integer and float. Just understand the difference between an integer/float and you will be OK in a professional environment.

Operators

But what programming language would be complete, without the ability to change numbers? The world is constantly changing and so are numbers, so we need operators to change them.

Luckily operators (and %99 of math in programming) should be simple to understand with basic math skills.

let total = 4 + 26;
let divide = total / 2;
let multiply = 2*3;
let subtract = 50 – 25;
let modulus = 5 % 2; // A modulus is simply the remainder of division
let pemdas = (1 * 2) / 2

Note: A “modulus” is a fancy word for remainder. The remainder is the amount left over after you have divided the number. 5 / 2 = a modulus of 1.

Programming languages also follow the rule of “Please Excuse My Dear Aunt Sally”. Meaning that the order of operations are determined by the following order:

  • Parenthesis
  • Exponents
  • Multiply
  • Divide
  • Add
  • Subtract

Most of the time, it is easy to understand this operation by just realizing that parenthesis can force the order of calculations, so that you can know for sure the values are not being calculated out of order.

Incrementing and Decrementing

Another very common task in software development is incrementing/decrementing numbers

Leave a Reply

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