JavaScript #10 — Numeric Variables
These JavaScript articles are written for people who are interested in coding and are meant to provide an introduction to the programming world.
You are going to learn how to define and work with numeric variables.
Numeric variables
The numeric variables can be whole numbers or decimal numbers. Let’s define a whole number and print out the value into the web browser console.
let age = 24
console.log(age)
Here it is, put it into VS Code and displayed in a web browser console.
You can define a variable with a decimal value in the same way. Just add the decimal part to the whole number. The decimal part of the number needs to be separated by a .
(a period) symbol.
let age = 24.5
console.log(age)
Transform a string into a number
It has been explained that there is a difference between a number and string (text) in the JavaScript programming language. The difference becomes visible when we want to, for example, add two numbers together, but the numbers are strings. In that case, it is needed to convert the strings into numbers, so it is possible to do the math operation.
We are going to put a new JavaScript keyword typeof
into our vocabulary. typeof
returns type of a variable. The grammar of typeof
word is the following: typeof
is followed by a variable.
<script>
let numberA = "1"
let typeOfNumberA = typeof numberA
console.log(typeOfNumberA)
</script>
Let’s open VS Code and create a new HTML file. The requirement for this exercise is to create a calculator that can sum two numbers together.
First, the program is going to use the prompt
function to get two numbers from the user. Then it is going the sum the two numbers together and print them out to the web browser console.
The tricky situation is that the prompt
function always returns a string. This means that string needs to be first converted into a number using the Number
function. If the input into the Number
function is not a number, it is going to return an undefined
value.
There are two other functions to get a number from a string:
parseInt
— extracts a whole number (integer) from a stringparseFloat
— extracts a decimal (floating point) number from a string
The difference between these two functions and the Number
function is that these two functions are extracting a number from a string, even when the string contains non-numeric values.
If the string starts with a number and ends with letters, those two functions are going to extract the value. For example, if the string is 24px, then the parseInt
is going to return 24. If the string is 3.14WhateverIsHere, then parseFloat
is going to return 3.14.
Try out parseInt
and parseFloat
in the calculator example.
Final words
Now you have an understanding of how to work with number in JavaScript. The next step is to explore more about string type.