In JavaScript, data types are the classification of values that determine the kind of operations that can be performed on them. JavaScript has two main categories of data types: primitive types and objects.
Primitive Data Types:
Number: Represents both integers and floating-point numbers. For example:
javascriptlet integerNumber = 10; let floatNumber = 3.14;
String: Represents sequences of characters. For example:
javascriptlet greeting = "Hello, World!";
Boolean: Represents a logical value, either true
or false
. For example:
javascriptlet isTrue = true;
let isFalse = false;
Null: Represents the intentional absence of any object value. For example:
javascriptlet nullValue = null;
Undefined: Represents an uninitialized variable or a function without a return statement. For example:
javascriptlet undefinedValue;
Symbol: Introduced in ECMAScript 6, symbols are unique and immutable primitive values. They are often used to create unique property keys in objects.
Object Data Type:
javascriptlet person = {
name: "John",
age: 25,
isStudent: false
};
Special Data Types:
Function: JavaScript treats functions as first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned as values from other functions.
Array: Although typeof Array returns "object", arrays in JavaScript are a specialized form of objects. They are used to store ordered collections of values.
JavaScript is a dynamically-typed language, meaning that variables can hold values of any type, and the type of a variable can change during the execution of a program. You can use the typeof
operator to determine the type of a variable or value. For example:
javascriptlet num = 42;
console.log(typeof num); // Outputs: "number"
let str = "Hello";
console.log(typeof str); // Outputs: "string"
Understanding data types is crucial when working with JavaScript, as it helps you write more robust and efficient code.