A value in JavaScript is always of a certain type. For example, a string or a number. Understanding data types is fundamental to writing effective JavaScript code, as the type of a value determines what you can do with it.
JavaScript is a dynamically typed language. This means that you do not have to declare the type of a variable when you create it. The data type is determined automatically at runtime.
A variable can hold a number one moment and a string the next.
// No error let message = "hello"; console.log(typeof message); // "string"message = 123456; console.log(typeof message); // "number"
There are eight basic data types in JavaScript, which can be divided into two main categories:
A primitive data type is data that has a primitive value (it has no properties or methods). There are 7 primitive data types:
string: Represents textual data (e.g., "hello").number: Represents both integer and floating-point numbers.bigint: For integer numbers of arbitrary length.boolean: Represents a logical entity and can have two values: true and false.undefined: A variable that has been declared but not assigned a value.null: Represents the intentional absence of any object value.symbol: A unique and immutable primitive value used as the key of an Object property.The object type is a non-primitive type. Unlike primitives, objects can store collections of data and more complex entities.
object: Represents a collection of key-value pairs. This includes standard objects, arrays, functions, dates, and more.Key Difference: Primitives are immutable (their value cannot be changed, only reassigned) and are compared by their value. Objects are mutable (their contents can be changed) and are compared by their reference (their location in memory).
typeof OperatorTo find the type of a JavaScript variable, you can use the built-in typeof operator.
console.log(typeof "John"); // "string"
console.log(typeof 3.14); // "number"
console.log(typeof NaN); // "number"
console.log(typeof false); // "boolean"
console.log(typeof [1,2,3,4]); // "object"
console.log(typeof {name:'John'}); // "object"
console.log(typeof new Date()); // "object"
console.log(typeof null); // "object" (This is a famous bug!)
console.log(typeof undefined); // "undefined"
In the following chapters, we will explore each of these data types in greater detail.
Due to a famous historical bug in JavaScript, what does typeof null return?