-
Notifications
You must be signed in to change notification settings - Fork 8
2.5 Data types
A variable in JavaScript can contain any data. A variable can at one moment be a string and later receive a numeric value:
// no error
let message = "hello";
message = 123456;
Programming languages that allow such things are called “dynamically typed”, meaning that there are data types, but variables are not bound to any of them.
There are seven basic data types in JavaScript. Here we’ll study the basics, and in the next chapters we’ll talk about each of them in detail.
let n = 123;
n = 12.345;
The number type serves both for integer and floating point numbers.
There are many operations for numbers, e.g. multiplication *, division /, addition +, subtraction - and so on.
Besides regular numbers, there are so-called “special numeric values” which also belong to that type: Infinity, -Infinity and NaN.
-
Infinityrepresents the mathematical Infinity ∞. It is a special value that’s greater than any number. We can get it as a result of division by zero:alert( 1 / 0 ); // InfinityOr just mention it in the code directly:
alert( Infinity ); // Infinity -
NaNrepresents a computational error. It is a result of an incorrect or an undefined mathematical operation, for instance:alert( "not a number" / 2 ); // NaN, such division is erroneousNaNis sticky. Any further operation onNaNwould giveNaN:alert( "not a number" / 2 + 5 ); // NaNSo, if there’s NaN somewhere in a mathematical expression, it propagates to the whole result.
Doing maths is safe in JavaScript. We can do anything: divide by zero, treat non-numeric strings as numbers, etc.
The script will never stop with a fatal error (“die”). At worst we’ll get NaN as the result.
Special numeric values formally belong to the “number” type. Of course they are not numbers in a common sense of this word.
We’ll see more about working with numbers in the chapter Numbers.