JavaScript Data Types

What Are Data Types in JavaScript?

Data types in JavaScript define the kind of values you can store and manipulate in your programs. JavaScript is a dynamically typed language, meaning you don’t need to specify the data type of a variable explicitly, it’s determined automatically during runtime.

Two Main Categories of JavaScript Data Types

  1. Primitive Data Types
  2. Non-Primitive (Reference) Data Types

1. Primitive Data Types

Primitive types are the most basic data types in JavaScript. These are immutable, meaning their value cannot be changed once assigned.

Types of Primitive Data Types

Data TypeDescriptionExample
StringRepresents text or sequences of characters.“Hello, World!”
NumberRepresents numeric values, including integers and decimals.42, 3.14
BigIntHandles large integers beyond the Number limit.1234567890123456789n
BooleanRepresents true/false values.true, false
UndefinedDenotes a variable that hasn’t been assigned a value.let x; (x is undefined)
NullRepresents an intentional absence of a value.let y = null;
SymbolRepresents a unique and immutable identifier.Symbol(‘id’)

Examples of Primitive Data Types

String Example:

let greeting = "Hello, World!";
console.log(greeting); // Output: Hello, World!

Number Example:

let price = 99.99;
console.log(price); // Output: 99.99

Boolean Example:

let isAvailable = true;
console.log(isAvailable); // Output: true

Undefined Example:

let user;
console.log(user); // Output: undefined

Null Example:

let selectedItem = null;
console.log(selectedtem); // Output: null

BigInt Example:

let bigNumber = 1234567890123456789n;
console.log(bigNumber); // Output: 1234567890123456789n

Symbol Example:

let uniqueId = Symbol('id');
console.log(uniqueId); // Output: Symbol(id)

2. Non-Primitive (Reference) Data Types

Non-primitive data types store collections of data or more complex entities. Unlike primitives, they are mutable.

Types of Non-Primitive Data Types

Data TypeDescriptionExample
ObjectStores key-value pairs.{name: “John”}
ArrayRepresents an ordered list of values.[1, 2, 3, 4]
FunctionRepresents reusable blocks of code.function() {}

Examples of Non-Primitive Data Types

Object Example:

let user = { name: "John", age: 30 };
console.log(user.name); // Output: John

Array Example:

let colors = ["red", "blue", "green"];
console.log(colors[0]); // Output: red

Function Example:

function greet() {
return "Hello!";
}
console.log(greet()); // Output: Hello!

Dynamic Typing in JavaScript

JavaScript allows variables to hold values of different data types during runtime. This is known as dynamic typing.

Example:

let data = 42;    // Initially a number
data = "Text"; // Now a string
console.log(data); // Output: Text

Checking Data Types

To determine the data type of a variable, use the typeof operator.

Example:

let value = 42;
console.log(typeof value); // Output: number

Leave a Comment