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 five primitive data types in JavaScript. Here we’ll study the basics.
Number
data type represents integer and real(or floating point numnber) number both.
let n = 123; n = 12.345;
Infinity represents 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 or just mention it in the code directly:
alert( 1 / 0 ); // Infinity alert( Infinity ); // Infinity
NaN
represents 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 erroneous
NaN
is sticky. Any further operation on NaN
would give NaN
:
alert( "not a number" / 2 + 5 ); // NaN
So, 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 like Infinity
and NaN
formally belong to the “number” type. Of course they are not numbers in a common sense of this word.
A string in JavaScript must be quoted.
let str = "Hello"; let str2 = 'Single quotes are ok too'; let phrase = `can embed ${str}`;
In JavaScript, there are 3 types of quotes.
"Hello"
.'Hello'
.`Hello`
.Double and single quotes are “simple” quotes. There’s no difference between them in JavaScript.
Backticks are “extended functionality” quotes. They allow us to embed variables and expressions into a string by wrapping them in ${…}
, for example:
let name = "John"; // embed a variable alert( `Hello, ${name}!` ); // Hello, John! // embed an expression alert( `the result is ${1 + 2}` ); // the result is 3
The expression inside ${…}
is evaluated and the result becomes a part of the string. We can put anything there: a variable like name
or an arithmetical expression like 1 + 2
or something more complex.
Please note that this can only be done in backticks. Other quotes do not allow such embedding!
alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)
In some languages, there is a special “character” type for a single character. For example, in the C
language and in Java
it is char
. In JavaScript, there is no such type. There’s only one type: string
. A string may consist of only one character or many of them.
Another advantage of using backticks is that they allow a string to span multiple lines:
let guestList = `Guests: * John * Pete * Mary `; alert(guestList); // a list of guests, multiple lines
If we try to use single or double quotes in the same way, there will be an error:
let guestList = "Guests: // Error: Unexpected token ILLEGAL * John";
The boolean type has only two values: true
and false
.
This type is commonly used to store yes/no values: true means “yes, correct”, and false means “no, incorrect”.
let nameFieldChecked = true; // yes, name field is checked let ageFieldChecked = false; // no, age field is not checked
Boolean values also come as a result of comparisons:
let isGreater = 4 > 1; alert( isGreater ); // true (the comparison result is "yes")
The special null
value does not belong to any type of those described above. It forms a separate type of its own, which contains only the null
value:
let age = null;
In JavaScript null
is not a “reference to a non-existing object” or a “null pointer” like in some other languages.
It’s just a special value which has the sense of “nothing”, “empty” or “value unknown”.
The code above states that the age is unknown or empty for some reason.
The special value undefined
stands apart. It makes a type of its own, just like null
. The meaning of undefined
is “value is not assigned”.
If a variable is declared, but not assigned, then its value is exactly undefined
:
let x; alert(x); // shows "undefined"
Technically, it is possible to assign undefined
to any variable:
let x = 123; x = undefined; alert(x); // "undefined"
…But it’s not recommended to do that. Normally, we use null
to write an “empty” or an “unknown” value into the variable, and undefined
is only used for checks, to see if the variable is assigned or similar.
The typeof
operator returns the type of the argument. It’s useful when we want to process values of different types differently, or just want to make a quick check.
It supports two forms of syntax:
typeof x
.typeof(x)
.In other words, it works both with parentheses or without them. The result is the same. The call to typeof x
returns a string with the type name:
typeof undefined // "undefined" typeof 0 // "number" typeof true // "boolean" typeof "foo" // "string" typeof Symbol("id") // "symbol" typeof Math // "object" (1) typeof null // "object" (2) typeof alert // "function" (3)
The result of typeof null
is "object". That’s wrong. It is an officially recognized error in typeof, kept for compatibility. Of course, null
is not an object. It is a special value with a separate type of its own. So, again, that’s an error in the language.
Most of the time, operators and functions automatically convert a value to the right type. That’s called “Implicit type conversion”. For example alert
function automatically converts any value to string and display the alert. Mathematical operations convert values to numbers. There is a lots of scinario where automatic conversion happens to the target type. But it's hard to remember all of them. So when you are not sure if a value will be converted to the right type, you can explicitily convert the value to the taget type.
String(value);
For example -
var i = 39, flag = false; i=String(i); console.log(typeof i); // string var b = String(flag); console.log(typeof b); // string
String conversion is mostly obvious. A false
becomes "false"
, null
becomes "null"
etc.
Number(value)
let str = "123"; alert(typeof str); // string let num = Number(str); // becomes a number 123 alert(typeof num); // number
If the string is not a valid number, the result of such conversion is NaN
, for instance:
let age = Number("an arbitrary string instead of a number"); alert(age); // NaN, conversion failed
The followings are few rules for converting to number type -
undefined
becomes NaN
null
becomes 0true
becomes 1 and false
becomes 0NaN
.alert( Number(" 123 ") ); // 123 alert( Number("123z") ); // NaN (error reading a number at "z") alert( Number(true) ); // 1 alert( Number(false) ); // 0
Almost all mathematical operations convert values to numbers. With a notable exception of the addition +. If one of the added values is a string, then another one is also converted to a string.
alert( 1 + '2' ); // '12' (string to the right) alert( '1' + 2 ); // '12' (string to the left)
That only happens when one of the arguments is a string. Otherwise, values are converted to numbers.
Boolean(value)
Here is the rules for converting to Boolean type -
null
, undefined and NaN become false
.true
.alert( Boolean(1) ); // true alert( Boolean(0) ); // false alert( Boolean("hello") ); // true alert( Boolean("") ); // false
Some languages (namely PHP) treat "0" as false. But in JavaScript a non-empty string is always true.
alert( Boolean("0") ); // true alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
These two function converts string value to Integer and Float type respectively and returns it.
parseInt(stringValue, radix); parseFloat(stringValue, radix);
Here, radix
is an integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. By default it is 10
, so most of the time we do not need to use the second argument as we most of the time deal only with decimal number system.
It is very powerful then the function Number(value)
. If your string starts with number and ends with string, then this function extract the digits from the string and returns it.
Here are some example -
parseInt("30"); // 30 parseInt("30santanu"); // 30 parseInt("s30antanu"); // NaN parseInt("0") // 0 parseInt("") // NaN parseInt(false) // NaN parseInt(undefined) // NaN parseInt(null) // NaN parseInt(Infinity) // NaN parseInt(NaN) // NaN
parseFloat()
works the same way, except it returns the float value.