Data structures and types
Data types
The latest ECMAScript standard defines eight data types:
-
Seven data types that are primitives:
- Boolean.
trueandfalse. - null. A special keyword denoting a null value. (Because JavaScript is case-sensitive,
nullis not the same asNull,NULL, or any other variant.) - undefined. A top-level property whose value is not defined.
- Number. An integer or floating point number. For example:
42or3.14159. - BigInt. An integer with arbitrary precision. For example:
9007199254740992n. - String. A sequence of characters that represent a text value. For example:
"Howdy". - Symbol. A data type whose instances are unique and immutable.
- Boolean.
-
and Object
Although these data types are relatively few, they enable you to perform useful operations with your applications. Functions are the other fundamental elements of the language. While functions are technically a kind of object, you can think of objects as named containers for values, and functions as procedures that your script can perform.
Data type conversion
JavaScript is a dynamically typed language. This means you don't have to specify the data type of a variable when you declare it. It also means that data types are automatically converted as-needed during script execution.
So, for example, you could define a variable as follows:
let answer = 42;
And later, you could assign the same variable a string value, for example:
answer = "Thanks for all the fish!";
Because JavaScript is dynamically typed, this assignment does not cause an error message.
Numbers and the '+' operator
In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:
x = "The answer is " + 42; // "The answer is 42"
y = 42 + " is the answer"; // "42 is the answer"
z = "37" + 7; // "377"
With all other operators, JavaScript does not convert numeric values to strings. For example:
"37" - 7; // 30
"37" * 7; // 259Converting strings to numbers
In the case that a value representing a number is in memory as a string, there are methods for conversion.
parseInt only returns whole numbers, so its use is diminished for decimals.
Note:
Additionally, a best practice for parseInt is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.
parseInt("101", 2); // 5
An alternative method of retrieving a number from a string is with the + (unary plus) operator. This implicitly performs number conversion, which is the same process as the Number() function.
"1.1" + "1.1"; // '1.11.1'
(+"1.1") + (+"1.1"); // 2.2
// Note: the parentheses are added for clarity, not required.