Working with numbers

Testing for numbers with isNaN, using the increment and decrement operators, and performing arithmetic with correct operator precedence.

Learning Goals

At the end of this Tutorial, you will be able to:

  • Declare numeric variables in JavaScript.
  • Use typeof and IsNaN() to test that a variable contains a number which can be used in calculations.
  • Perform addition, subtraction, multiplication, and division on numeric variables.

There is no exercise file for this Tutorial.

Introducing numbers in JavaScript

Unlike other programming languages, JavaScript only has one number data type. This can store integers (positive or negative whole numbers) or floats (floating-point numbers with a decimal point).

About the increment and decrement operators

In programming, the word 'increment' means 'make larger by one' and its converse of 'decrement' means 'make smaller by one'. You have met only one type of assignment operator so far, an example of which is shown below.

myvar = 42;

As you can see, it has two terms, one on each side of the equals (=) sign. Below are examples of the increment and decrement operators. These contain only a single term and do not require an equals sign.

// This has the same effect as writing firstNumber = firstNumber + 1
firstNumber++;

// This has the same effect as writing firstNumber = firstNumber - 1 */
secondNumber--;

These operators work only with numeric variables and are really just a convenient shorthand notation.

Assigning numbers to variables

To assign a number to a variable, do not wrap the value in single or double quotes.

const myVar1 =  1234; // JavaScript treats myVar1 as a number
const myVar2 = "1234"; // JavaScript treats myVar2 as a string
const myVar3 = '1234'; // JavaScript treats myVar3 as a string

JavaScript decides which type of variable you want to create by the way that you first assign a value to it.

  • When you enclose the assigned value within quotes, JavaScript gives the variable a data type of string.
  • When you omit the quotes, JavaScript gives the variable a data type of number.

Here are two values that JavaScript will accept as valid numbers.

let Temperature = -6.3456 // Valid number 
let errorRare = .2727 // Valid number 

And here are two values that are not valid numbers in JavaScript.

let userIncome = 34,000; // Error. Contains a comma 
let product ID = 645w29; // Error. Contains a letter character 

In fact, they are not even valid variable assignments because JavaScript cannot understand what type of data type you want to create. Each line will throw an error.

The typof operator

If you are unsure about a variable’s data type, you can use the typeof operator on the variable as shown below.

let someVar;
// declare empty variable 
console.log(`Data type of someVar: ${typeof someVar}`);
// returns undefined  
someVar = "12";
console.log(`Data type of someVar: ${typeof someVar}`);
// returns string 
someVar = 12;
console.log(`Data type of someVar: ${typeof someVar}`);
// returns number 
someVar = "12";
console.log(`Data type of someVar: ${typeof someVar}`);
// returns string 

If the variable contains a number, typeof returns the string "number".

Testing for numbers with isNaN(n)

To test that a variable contains a number, another option is to use the global variable isNaN(n). NaN stands for 'Not a Number'. See below.

const stringVar = "Some text";
// declare string variable 
console.log(`Is this not a number ("Some text"): ${isNaN(stringVar)}`);
// returns true  
const numVar = 42;			
console.log(`Is this not a number ("42"): ${isNaN(numVar)}`);
// returns false  

Automatic variable type conversion is a powerful feature of JavaScript. But its very power can result in scripting errors or in scripts that produce unexpected results.

To check that a variable contains a number before using that variable in a calculation, you could test it in either of two ways as follows.

const varPossibleNumber = 2;
if (typeof varPossibleNumber === 'number') {
  // safe to continue with calculation
}
if (!isNaN(varPossibleNumber)) {
  // also safe to continue with calculation
}

Numbers that are never used in calculations can be correctly assigned to strings. For example, users’ telephone numbers. You will never want to divide a telephone number by two or deduct 10% from such a number.

let userTelNo = "088 123 456678"; // number as string

But never assign a number to a string variable if you intend using that number in a calculation.

Arithmetic operations

You can perform arithmetic with numeric variables using the arithmetic operators set out in the table below.

Operator

Operator Key Used

Description

x + y

The plus key

Adds the value of x and the value of y.

x - y

The dash key

Subtracts the value of y from the value of x.

x * y

The asterisk key

Multiplies the value of x by the value of y.

x / y

The forward slash key

Divides the value of x by the value of y.

See the simple examples below.

const firstNum = 12;
const secondNum = 8;
console.log(`Addition (12+8): ${12 + 8}`); // returns 20
console.log(`Subtraction (12-8): ${12 - 8}`); // returns 4
console.log(`Multiplication (12*8): ${12 * 8}`); // returns 96  
console.log(`Division (12/8): ${12 / 8}`); // returns 1.5

Operator precedence

JavaScript follows the rules of arithmetic when working with numeric variables and numbers:

  • Division first, followed by multiplication, then addition and finally subtraction.

For example, the following series of statements gives a result of 11 because JavaScript first multiplies 2 by 3 (resulting in 6) and then adds 5.

console.log(`5 + 2 * 3: ${5 + 2 * 3}`); // returns 11 

You can force JavaScript to perform calculations in a particular order by using parentheses ().

For example, the following calculation gives a result of 21. JavaScript first adds 5 and 2, because they are within (). And only then multiplies that result by 3 to give 21.

console.log(`(5 + 2) * 3: ${(5 + 2) * 3}`); // returns 21 

For example,

function convertToFahrenheit(celsius) {
   varFahrenheit = ((9/5) * celsius) + 32;
   console.log(`${celsius} Celsius:  = ${varFahrenheit} Fahrenheit`);
}

convertToFahrenheit(20);

Increment and decrement operators

JavaScript supports increment ++ and decrement -- prefix operators that increase or reduce the numerical value of a variable by one. They cannot be applied to literal values; only to numeric variables.

See the sample code below.

let myNum1 = 7;
let myNum2 = 24; 	
console.log(`myNum1 is 7`); 
console.log(`Increment operator (++myNum1) is ${++myNum1}`);
// returns 8
console.log(`myNum2 is 24`); 
console.log(`Decrement operator (--myNum2) is ${--myNum2}`);
// returns 23