In JavaScript, a data type defines the type of value a variable can hold. JavaScript is a dynamically typed language, meaning you don't need to specify the data type when declaring a variable; it is determined automatically based on the value assigned.
Here are the main data types in JavaScript with examples:
1. Number
- Represents both integer and floating-point numbers.
let age = 25; // Integer
let price = 19.99; // Floating-point
2. String
- Represents a sequence of characters (text).
let name = "Alice"; // Using double quotes
let greeting = 'Hello'; // Using single quotes
3. Boolean
- Represents a logical value:
true
orfalse
.
let isStudent = true;
let isAdult = false;
4. Undefined
- A variable that has been declared but not assigned a value.
let unassignedVar;
console.log(unassignedVar); // Output: undefined
5. Null
- Represents an intentionally empty or non-existent value
let emptyValue = null;
6. Object
- Represents a collection of properties, where each property is a key-value pair. Objects can also represent more complex data structures like arrays and functions.
let person = {
name: "John",
age: 30,
isStudent: false
};
Array: A special type of object for storing ordered lists.
let numbers = [1, 2, 3, 4, 5];
Function: A block of code designed to perform a particular task.
function sayHello() { return "Hello!"; }
7. Symbol (ES6)
- Represents a unique and immutable identifier.
let sym = Symbol('unique');
8. BigInt (ES11)
- Represents integers with arbitrary precision.
let bigNumber = 1234567890123456789012345678901234567890n;
Example Code Snippet Using Different Data Types:
let age = 25; // Number
let name = "Alice"; // String
let isStudent = true; // Boolean
let unassignedVar; // Undefined
let emptyValue = null; // Null
let person = { // Object
name: "John",
age: 30,
isStudent: false
};
let numbers = [1, 2, 3, 4, 5]; // Array
function sayHello() { // Function
return "Hello!";
}
let sym = Symbol('unique'); // Symbol
let bigNumber = 1234567890123456789012345678901234567890n; // BigInt
These are the fundamental data types in JavaScript, each serving different purposes depending on the needs of your program.
Tags:
JavaScript