JavaScript Data Types
JavaScript is a dynamically-typed language, which means that variables can hold values of any data type without the need for explicit declaration. JavaScript has several built-in data types that can be classified into two main categories: primitive data types and non-primitive (or reference) data types.
Primitive Data Types
Primitive data types are the basic building blocks of JavaScript. They are immutable, meaning that their values cannot be changed once they are created. JavaScript has the following primitive data types:
- Number: This data type represents both integers and floating-point numbers. It can also represent special numeric values like
Infinity
andNaN
(Not a Number).
let age = 30;
let pi = 3.14;
let maxValue = Infinity;
let notANumber = NaN;
- String: This data type represents a sequence of characters. Strings can be enclosed in single quotes (
'
), double quotes ("
), or backticks (`
).
let name = "John Doe";
let message = 'Hello, world!';
let template = `Hello, ${name}!`;
- Boolean: This data type represents a logical value, either
true
orfalse
.
let isStudent = true;
let isEmployed = false;
- Undefined: This data type represents the absence of a value. A variable that has not been assigned a value is of type
undefined
.
let x;
console.log(x); // Output: undefined
- Null: This data type represents a non-existent or invalid value.
let person = null;
- Symbol: This data type represents a unique and immutable identifier. Symbols are primarily used as object property keys.
let id = Symbol('id');
let obj = {
[id]: 1234
};
Non-Primitive (Reference) Data Types
Non-primitive data types are complex data structures that can hold multiple values. They are mutable, meaning that their values can be changed. JavaScript has the following non-primitive data types:
- Object: This data type represents a collection of key-value pairs. Objects can be used to store complex data structures, such as arrays, functions, and other objects.
let person = {
name: "John Doe",
age: 30,
isStudent: true
};
- Array: This data type represents an ordered collection of values. Arrays can hold values of different data types, including other arrays and objects.
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "hello", true, [10, 20]];
- Function: This data type represents a reusable block of code that can be called with arguments and can return a value.
function greet(name) {
return `Hello, ${name}!`;
}
let greeting = greet("John");
Understanding the different data types in JavaScript is crucial for writing effective and efficient code. By knowing the characteristics and behaviors of each data type, developers can make informed decisions about how to store and manipulate data in their applications.