JavaScript Data Types
JavaScript provides different data types to hold different types of values. There are two main categories of data types in JavaScript: Primitive and Object (Non-primitive).
Primitive Data Types
Primitive data types include String, Number, Boolean, Undefined, Null, Symbol, and BigInt. Let’s explore each of them with examples.
1. String
A string represents textual data enclosed in quotes.
Example:
let name = "John Doe";
let greeting = 'Hello, world!';
console.log(name); // Output: John Doe
console.log(greeting); // Output: Hello, world!
2. Number
A number represents both integer and floating-point numbers.
Example:
let age = 30;
let temperature = 98.6;
console.log(age); // Output: 30
console.log(temperature); // Output: 98.6
3. Boolean
A boolean represents a logical entity and can have two values: true
or false
.
Example:
let isJavaScriptFun = true;
let isSummer = false;
console.log(isJavaScriptFun); // Output: true
console.log(isSummer); // Output: false
4. Undefined
A variable that has been declared but not assigned a value is of type undefined
.
Example:
let x;
console.log(x); // Output: undefined
5. Null
null
is an assignment value that represents no value.
Example:
let y = null;
console.log(y); // Output: null
6. Symbol
A Symbol
is a unique and immutable value, often used to identify object properties uniquely.
Example:
let sym1 = Symbol("id");
let sym2 = Symbol("id");
console.log(sym1 === sym2); // Output: false
7. BigInt
BigInt
is used to represent integers that are too large to be represented by the Number
type.
Example:
let bigNumber = BigInt(9007199254740991);
console.log(bigNumber); // Output: 9007199254740991n
Non-primitive (Object) Data Types
Objects are complex data types that allow us to store collections of data and more complex entities. The most common object data type is the Object itself, but arrays and functions are also considered objects in JavaScript.
1. Object
An object is a collection of properties, where each property is defined as a key-value pair.
Example:
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
console.log(person.firstName); // Output: John
console.log(person["lastName"]); // Output: Doe
2. Array
An array is a special type of object used to store a collection of values in a single variable.
Example:
let colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // Output: Red
console.log(colors.length); // Output: 3
3. Function
A function is a reusable block of code designed to perform a particular task.
Example:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("John")); // Output: Hello, John!
Understanding these data types is fundamental to working effectively with JavaScript. By knowing how to use and manipulate these types, you can create more dynamic and functional web applications.