Data types in JavaScript define the type of data that can be stored and manipulated within a program. They are essential for understanding how to work with variables and perform operations in JavaScript.
JavaScript has two main categories of data types: Primitive and Non-Primitive (or Reference) data types.
Primitive data types are the most basic data types in JavaScript. They include:
"Hello, World!"42,
3.14
true or
false.
// String
let name = "Ayush";
console.log(typeof name); // Output: string
// Number
let age = 25;
console.log(typeof age); // Output: number
// Boolean
let isStudent = false;
console.log(typeof isStudent); // Output: boolean
// Undefined
let x;
console.log(typeof x); // Output: undefined
// Null
let y = null;
console.log(typeof y); // Output: object
typeof operator is used to determine the data type of a variable.Non-Primitive data types are more complex and can store collections of data or more complex entities. They include:
{ name: "Ayush", age: 21 }[1, 2, 3, 4, 5]// Object
let person = { name: "Ayush", age: 21 };
console.log(typeof person); // Output: object
// Array
let numbers = [1, 2, 3, 4, 5];
console.log(typeof numbers); // Output: object
// Function
function greet() {
return "Hello!";
}
console.log(typeof greet); // Output: function
JavaScript is a dynamically typed language, meaning you don't have to declare the data type of a variable explicitly. The type is determined automatically based on the value assigned to the variable.
typeof operator to check the data type of a variable.Understanding these data types will help you write more effective JavaScript code!