Data types

rishi-g
8 min readJul 24, 2023

In JavaScript, every value has a type. The most common types are strings and numbers.
There are eight basic data types in JavaScript:

  • Number
  • BigInt
  • String
  • Boolean
  • Null
  • Undefined
  • Object
  • Symbol

Variables can hold any type of data.
For example, a variable can hold a string value at one point and then hold a number value later on.
In the upcoming chapters, we will discuss each of these data types in detail.

// no error
let message = "hello";
message = 123456;

In programming languages that allow variables to hold any type of data, such as JavaScript, the language is said to be “dynamically typed”. While there are still data types, variables are not bound to any specific type. This means that a variable can hold a string value at one point and a number value at another point, without any errors being thrown.

Number

let n = 123;
n = 12.345;

The number type in JavaScript represents both integer and floating point numbers.

It supports many operations, including multiplication , division /, addition +, subtraction -, and others.

In addition to regular numbers, there are also “special numeric values” that belong to this data type: Infinity, -Infinity, and NaN.

Infinity represents mathematical infinity (∞) and is a special value that is greater than any number.
It can be obtained as a result of division by zero:

console.log(1 / 0); // Infinity

NaN (Not a Number) is a special numeric value that indicates an unrepresentable value. It is a result of an incorrect or an undefined mathematical operation.
For example:

console.log("not a number" / 2); // NaN

In JavaScript, the number type is dynamic, which allows variables to hold both integer and floating point numbers. Thus, a variable can hold the value 123 at one point, and 12.345 at another point, without any errors being thrown.

NaN is sticky. Any further mathematical operation on NaN returns NaN:

alert( NaN + 1 ); // NaN
alert( 3 * NaN ); // NaN
alert( "not a number" / 2 - 1 ); // NaN

• So, if there’s a NaN somewhere in a mathematical expression, it propagates to the whole result (there’s only one exception to that: NaN ** 0 is 1).

Mathematical operations are safe:
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 the common sense of this word. We’ll see more about working with numbers in the chapter Numbers.

BIGINT

In JavaScript, the “number” type can’t safely represent integer values larger than (2⁵³-1) (that’s 9007199254740991), or less than -(2⁵³-1) for negatives.

To be precise, the “number” type can store larger integers (up to 1.7976931348623157 * 10³⁰⁸), but outside of the safe integer range ±(2⁵³-1) there’ll be a precision error because not all digits fit into the fixed 64-bit storage. So an “approximate” value may be stored.

For example, these two numbers (right above the safe range) are the same:

console.log(9007199254740991 + 1); // 9007199254740992
console.log(9007199254740991 + 2); // 9007199254740992

So, all odd integers greater than (2⁵³-1) can’t be stored at all in the “number” type. For most purposes, the ±(2⁵³-1) range is sufficient, but sometimes the entire range of really big integers is needed, such as for cryptography or microsecond-precision timestamps.

The BigInt type was recently added to the language to represent integers of arbitrary length.
A BigInt value is created by appending n to the end of an integer:

// the "n" at the end means it's a BigInt
const bigInt = 1234567890123456789012345678901234567890n;

Since BigInt numbers are rarely needed, they are covered in a separate chapter. Check it out when such big numbers are required.

Compatibility issues:
Right now, BigInt is supported in Firefox, Chrome, Edge, and Safari, but not in Internet Explorer. To check which versions of a browser are supported, refer to the MDN BigInt compatibility table.

String

A string in JavaScript must be surrounded by quotes.

let str = "Hello";
let str2 = 'Single quotes are ok too';
let phrase = `can embed another ${str}`;

In JavaScript, there are 3 types of quotes.

  • Double quotes: “Hello”.
  • Single quotes: ‘Hello’.
  • Backticks: Hello.

Double and single quotes are “simple” quotes. There’s practically 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 in 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 don’t have this embedding functionality!

alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)

There is no character type.
In contrast to certain programming languages like C and Java, JavaScript does not have a dedicated “character” type for individual characters. Instead, JavaScript only has a single type known as “string.” A string in JavaScript can be empty, contain a single character, or consist of multiple characters. Therefore, in JavaScript, individual characters are represented as strings.

Boolean (logical type)

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”.

Typically, booleans are used to represent yes/no or true/false values.
For example:

let nameFieldChecked = true; // Indicates that the name field is checked (yes).
let ageFieldChecked = false; // Indicates that the age field is not checked (no).

Booleans are also the result of comparison operations, as shown in the following example:

let isGreater = 4 > 1;
alert(isGreater); // true (the comparison result is "yes")

The “null” value

The special null value does not belong to any of the types 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 represents “nothing”, “empty” or “value unknown”. The code above states that age is unknown.

The “undefined” value

The special value undefined also 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 undefined:

let age;
alert(age); // shows "undefined"

Technically, it is possible to explicitly assign undefined to a variable:

let age = 100;
// change the value to undefined
age = undefined;
alert(age); // "undefined"

…But we don’t recommend doing that. Normally, one uses null to assign an “empty” or “unknown” value to a variable, while undefined is reserved as a default initial value for unassigned things.

Objects and Symbols

In JavaScript, the object type is distinct and special compared to other types known as “primitives.” Primitives include types like strings, numbers, booleans, etc., and they can only hold a single value at a time.

On the other hand, objects are utilized to store collections of data and represent more complex entities. However, to delve into objects in detail, we will explore them later in the chapter called “Objects,” after we have gained a deeper understanding of primitives.

Additionally, there is another type called “symbol,” which is used to create unique identifiers for objects. We mention it here for the sake of completeness, but we will postpone the details about symbols until we cover objects in greater depth.

In summary, JavaScript treats objects differently from primitive types, and we’ll explore objects and symbols in detail in upcoming sections to fully grasp their significance and usage.

The typeof operator

The typeof operator in JavaScript allows us to determine the type of the operand it is applied to. It is particularly useful when we need to handle different types of values differently or when we want to quickly check the type of a value.

Here are some examples of using the typeof operator and the corresponding results:

typeof undefined // "undefined"
typeof 0 // "number"
typeof 10n // "bigint"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object" (1)
typeof null // "object" (2)
typeof alert // "function" (3)

Let’s provide further explanations for the last three lines:

  1. The result of typeof Math is "object." Math is a built-in object in JavaScript that provides mathematical operations. Although we'll explore Math more in the chapter on Numbers, here it serves as an example of an object.
  2. The result of typeof null is "object." This is a well-known mistake in the typeof operator, which has persisted since the early days of JavaScript for compatibility reasons. In reality, null is not an object; it is a special value with its own distinct type. Despite this error, the behaviour of typeof null remains unchanged.
  3. The result of typeof alert is "function." In JavaScript, functions are objects and belong to the object type. However, typeof treats functions differently and returns "function" for them. Although this behaviour is technically not accurate, it has been retained for practical convenience, considering the historical evolution of JavaScript.

In summary, the typeof operator enables us to determine the type of a value in JavaScript, but there are some peculiarities, like the incorrect classification of null and the special handling of functions as “function” type.

The typeof(x) syntax
You may also come across another syntax: typeof(x). It’s the same as typeof x.
To put it clear:
typeof is an operator, not a function. The parentheses here aren’t a part of typeof. It’s the kind of parentheses used for mathematical grouping.
Usually, such parentheses contain a mathematical expression, such as
(2 + 2), but here they contain only one argument (x). Syntactically, they allow to avoid a space between the typeof operator and its argument, and some people like it.Some people prefer typeof(x), although the typeof x syntax is much more common.

Summary

In JavaScript, there are 8 basic data types, categorized into two groups:
Seven primitive data types:

  1. number: Represents numbers of any kind, including integers and floating-point numbers. Integers are limited by ±(2^53-1).
  2. bigint: Used for representing integer numbers of arbitrary length.
  3. string: Represents sequences of characters. A string can be empty or contain one or more characters. There's no separate type for single characters.
  4. boolean: Represents true or false values.
  5. null: Represents unknown values and is a standalone type with only one possible value: null.
  6. undefined: Represents unassigned values and is a standalone type with only one possible value: undefined.
  7. symbol: Used to create unique identifiers.

One non-primitive data type:
8. object: Represents more complex data structures, such as collections of data and entities.
The typeof operator is used to determine the type of a variable's value. It is usually written as typeof x, but typeof(x) is also valid. It returns a string indicating the name of the type, for example, "string", "number", "boolean", etc.
However, there is a quirk in the behaviour of typeof null, where it incorrectly returns "object" instead of "null." This behaviour is a long-standing error in the language that has been preserved for compatibility reasons.
In summary, JavaScript has 8 data types: 7 primitive (number, bigint, string, boolean, null, undefined, symbol) and 1 non-primitive (object), and the typeof operator is used to determine the type of a variable's value.

--

--