Skip to content

JavaScript Data Types

Understanding data types is crucial in any programming language, including JavaScript. JavaScript is a dynamically typed language, which means you don’t have to declare the type of a variable before using it.

JavaScript has seven primitive data types:

  • String: Represents textual data (e.g., “Hello World”).
  • Number: Represents numeric values, including integers and floating-point numbers (e.g., 42, 3.14). Special numeric values include Infinity, -Infinity, and NaN (Not a Number).
  • Boolean: Represents a logical entity and can have two values: true or false.
  • Null: Represents the intentional absence of any object value. It is a primitive value, but typeof null paradoxically returns “object” (a long-standing quirk).
  • Undefined: Represents a variable that has been declared but not yet assigned a value, or a function argument not provided.
  • Symbol (ES6): Represents a unique and immutable identifier. Often used as keys for object properties to avoid name collisions.
  • BigInt (ES2020): Represents whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the Number type.

And one non-primitive (reference) type:

  • Object: Represents a collection of key-value pairs. Arrays, Functions, Dates, RegExp, etc., are all specialized types of objects.

Example of variable declarations:

let age = 30; // Number
const name = "Alice"; // String
const isActive = true; // Boolean
const userSettings = { theme: "dark" }; // Object
const scores = [90, 85, 92]; // Array (a type of Object)
let notAssigned; // Undefined
let noValue = null; // Null
const id = Symbol('uniqueId'); // Symbol
const veryLargeNumber = 9007199254740991n; // BigInt

The Concept of Data Types and Type Coercion

Section titled “The Concept of Data Types and Type Coercion”

Knowing the data type of a variable is important because operations behave differently based on types.

Consider this:

let result = 16 + "Volvo"; // What happens here?

JavaScript performs type coercion. If one operand is a string, JavaScript will try to convert the other operand to a string and concatenate them. So, result becomes "16Volvo".

JavaScript evaluates expressions from left to right. Different sequences can produce different results due to coercion:

let x = 16 + 4 + "Volvo"; // result: "20Volvo" (16+4 is 20, then 20 + "Volvo")
let y = "Volvo" + 16 + 4; // result: "Volvo164" ("Volvo"+16 is "Volvo16", then "Volvo16"+4)

To avoid unexpected behavior, it’s often best to be explicit about types or use strict equality operators (===, !==) which don’t perform type coercion. You can learn more in the comparisons chapter.

JavaScript is dynamically typed. This means a variable can hold values of different types at different times:

let x; // x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
x = { type: "Car" }; // Now x is an Object

A string is a sequence of characters. Strings can be created using single quotes ('...'), double quotes ("..."), or backticks (template literals: `...`).

const carName1 = "Volvo XC60";
const carName2 = 'Volvo XC60';
// Using quotes inside strings:
const answer1 = "It's alright";
const answer2 = 'He is called "Johnny"';
// Template Literals (ES6+) for embedded expressions and multi-line strings:
const userName = "Bob";
const greeting = `Hello, ${userName}!`; // "Hello, Bob!"
const multiLine = `This is
a multi-line
string.`;

Strings have many built-in methods for manipulation (e.g., length, toUpperCase(), slice()).

JavaScript uses a single Number type for both integers and floating-point numbers, based on the IEEE 754 standard. This means there can be precision issues with floating-point arithmetic.

const pi = 3.14; // With decimals
const count = 100; // Without decimals
// Exponential notation:
const largeNum = 1.23e6; // 1.23 * 10^6 = 1230000
const smallNum = 1.23e-4; // 1.23 * 10^-4 = 0.000123
// Special numeric values:
console.log(1 / 0); // Infinity
console.log("text" / 2); // NaN (Not a Number)

For numbers beyond the safe integer limit (±(253-1)), use BigInt.

Booleans represent truth values and can only be true or false.

const isDataValid = true;
const isLoggedIn = false;
if (isLoggedIn) {
console.log("User is logged in.");
} else {
console.log("User is not logged in.");
}

Booleans are fundamental for conditional logic and control flow.

Arrays are ordered collections of values. They are created using square brackets [].

const cars = ["Saab", "Volvo", "BMW"];
const mixedArray = [1, "apple", true, { city: "New York" }];

Array elements are accessed by their index (0-based): cars[0] is “Saab”. Arrays have many powerful built-in methods (e.g., push(), pop(), map(), filter(), reduce()).

Objects are unordered collections of key-value pairs (properties). They are created using curly braces {}.

const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue",
address: {
street: "123 Main St",
city: "Anytown"
}
};

Properties are accessed using dot notation (person.firstName) or bracket notation (person["lastName"]). Objects are highly versatile and form the basis of complex data structures.

The typeof operator returns a string indicating the type of its operand.

typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number" (NaN is a special number)
typeof false // Returns "boolean"
typeof [1, 2, 3, 4] // Returns "object" (Arrays are objects)
typeof { name: 'John', age: 34 } // Returns "object"
typeof new Date() // Returns "object"
typeof function() {} // Returns "function" (Functions are special objects)
typeof myVariable // Returns "undefined" (if myVariable is not declared or unassigned)
typeof null // Returns "object" (This is a historical bug)
typeof Symbol('id') // Returns "symbol"
typeof 9007199254740991n // Returns "bigint"
Note: typeof null returning “object” is a long-standing quirk in JavaScript. To properly check for null, use strict equality: myVar === null.

undefined is a primitive value automatically assigned to variables that have just been declared, or to function arguments for which there are no actual arguments, or to missing object properties.

let personName; // Value is undefined, typeof personName is "undefined"
function greet(name) {
console.log(name); // If called as greet(), name will be undefined
}
const obj = {};
console.log(obj.missingProperty); // undefined

null is a primitive value that represents the intentional absence of any object value. It must be explicitly assigned.

let user = null; // Value is null, typeof user is "object" (the quirk)
// To explicitly clear an object reference:
let myObject = { data: "some data" };
myObject = null; // The object is now eligible for garbage collection

undefined typically means a variable has not been initialized or a value is missing. null is used to explicitly indicate that a variable should have no value or that an object reference points to nothing.

console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"
console.log(null === undefined); // false (strict equality)
console.log(null == undefined); // true (loose equality, due to type coercion - generally avoid)

It’s generally recommended to use strict equality (=== and !==) to avoid confusion caused by type coercion when comparing null and undefined.