Datatypes

Types in JavaScript

JavaScript is dynamically-typed and weakly-typed language, meaning you do not need to declare a variable's type in advance, you can reassign a variable to any type, and implicit type conversion occurs automatically when possible.

let x; // no value assigned; by default undefined
x = 10; // x is now 10, a number
x = "hello"; // x is now "hello", a string
x = true; // x is now true, a boolean

The following page has some of the datatypes in JavaScript.

Number

The Number datatype in JavaScript is a primitive datatype that represents, surprise surprise, a number. Unlike many other languages, JavaScript does not explicitly differentiate between integers and floats and any such value just has the type Number.

Some examples of Numbers are 0, 1, -1.32, and Infinity. Infinity is a special value used by JavaScript to indicate an infinite value, such as the result of dividing anything by 0.

JavaScript numbers can be formatted in scientific notation as follows:

let x = 23e3; // x is 23 times 10^3
let y = 4e-5; // y is 4 times 10^-5

Boolean

The boolean datatype in JavaScript is another primitive datatype that can take on one of two values: true or false. These values are useful in any code involving predicates.

String

The String datatype in JavaScript is a compound datatype that is essentially any text enclosed in quotation marks (double or single are both fine, as long as the start and end quotation marks match).

let str = "Hello world!";

Strings are immutable, which means that any function that takes in a string does not change its value; it instead returns a new string.

A particular character in a string can be accessed using square brackets ([]) wrapped around a number representing the position of the character, called the index. The first character is said to be at index 0. There are other ways to access a particular character in a string which will be discussed later.

let str = "H0LA";
console.log(str[1]); // will print out "0"

The length of a string can be found using the .length property:

let str = "orbital";
str.length; // returns 7

Array

The Array datatype in JavaScript is compound mutable datatype that represents an ordered collection of values. The values can be of any type, and values of different types can be assigned to the same array without an issue. An array is declared by separating the values with commas (,) and enclosing the list with square brackets []. As with strings, you can get the length of the array with the .length property, and access a particular value with square bracket indices. Arrays can also be nested if need be.

let arr = [1, -2, 3, true, "random string here", ["another array", 4]];
arr[0]; // returns 1
arr[4]; // returns "random string here"
arr[5]; // returns ["another array", 3]
arr[5][1]; // returns 4
arr.length; // returns 6

As you saw above, indexes can be chained in the case of nested arrays.

Objects

An Object in JavaScript refers to a container variable that contains many values. By this definition, an array is an object. In JavaScript, objects are declared and assigned using JavaScript Object Notation, or JSON. You can imagine an object as a set of key-value pairs.

let myObj = {firstName: "Prakamya", lastName: "Singh", year: 1, isComputingStudent: true};

As you can see, the key-value pairs are separated by commas (,), enclosed by curly braces ({}) and the pairs are formatted as key: value. Note that the key does not have to be enclosed in quotation marks as long as it has no spaces, operators(+, = etc.) and other reserved characters or keywords.

To access a value assigned to a key (formally called a property in JS) you can either use square brackets ([]) or dot notation:

myObj["firstName"]; // returns "Prakamya"
myObj.firstName; // also returns "Prakamya"

Note that with dot notation, you do not need quotation marks whereas with square bracket notation you do need quotation marks.

Some other primitive values

undefined

In JavaScript, undefined is a primitive value that is returned by functions or expressions that have no return value as mentioned in the previous section. It is also a default value that is assigned by JavaScript to a variable that has been declared without assignment. For instance,

let x;

will assign undefined to x until a different value is assigned later on.

undefined can also be assigned to a variable, strangely enough.

null

This is another primitive value that can be assigned to variables or returned by functions or expressions. It is used to represent an empty, non-existent value rather than as a flag to indicate no return value.

Treat null like a "nothing here" symbol and undefined as a "nothing here yet" symbol.

NaN

This primitive value stands for "Not a Number" and is used by JavaScript to indicate that the result of an expression or function is not a number. One way to get this is to divide a number by a string that does not have numeric digits. While most languages would throw an error or exception of some kind in such situations, JavaScript instead handles it by returning NaN to indicate that the expression was erroneous.

How to determine the type of a value/variable

There are two methods to determine the type of a variable in JavaScript. The first method is more common, and involves using the typeof function which takes in any value as an argument and returns a string with the data type.

// Let's declare some variables first
let num = 10;
let otherNum = 9.9;
let str = "some string";
let bool = true;
let arr = [1, false, "hello"];
let obj = {car: "Puma", licensePlate: "SLG2034B", topSpeed: 120};

// Now let's check their data types using the typeof function.
typeof(num); // returns "number"
typeof(otherNum); // still returns "number"
typeof(str); // returns "string"
typeof(bool); // returns "boolean"
typeof(obj); // returns "object"
typeof(arr); // returns "object", not "array"

As you'll notice, typeof returns "object" when you pass in an array, even though they are essentially different. So the second way is to use the instanceof keyword. Here's how it works:

// assume we have our same variables as before
arr instanceof Array; // returns true
arr instanceof Object; // still returns true
obj instanceof Object; // returns true
obj instanceof Array; // returns false

Now we can differentiate between objects and arrays. But the instanceof keyword has its own issues:

// assume we have our same variables as before
num instanceof Number; // returns false
str instanceof String; // returns false
bool instanceof Boolean; // returns false

Whelp, 10 isn't a number apparently. Thanks instanceof.

Moral of the story: Based on what you are trying to achieve, make sure you use the right technique to determine a variable's type. For instance, if I had to validate some input to make sure it is a number, I would use the typeof operator and check if it outputs "number". But if I had to instead check if my input is an array specifically, I would need to use the instanceof keyword as above.

typeof(undefined) returns "undefined"

typeof(null) returns "object"

typeof(NaN) returns "number"

Next steps

Next, we'll take a look at operations and some operators in JavaScript, along with what datatypes can be used with them.

Last updated