Data types in JavaScript are attributes that determine the type of value that a variable can hold. These data types are used to represent different types of information.
JavaScript is a dynamic typing programming language, which means that it is not necessary to explicitly declare the type of a variable at the time of its creation.
But that doesn’t mean that JavaScript doesn’t have types. The type is simply determined automatically when a value is assigned.
Primitive Data Types
Primitive data types are those that represent individual values and do not have methods or properties. They are immutable, which means they cannot be changed once they have been created.
Numbers (number
)
The number
data type in JavaScript represents both integers and floating-point numbers. Numbers in JavaScript are handled according to the IEEE 754 standard.
let age = 25;
let price = 99.95;
String (string
)
The string
data type represents a sequence of characters, such as text or words. Strings must be enclosed in single quotes ' '
or double quotes " "
.
let name = 'Luis';
let message = "Hello, world!";
Boolean (boolean
)
The boolean
data type represents a truth value, which can be true
or false
. It is useful in conditional and logical expressions.
let isOlder = true;
let isActive = false;
Value null
In JavaScript, null
is a special value that represents the intentional absence of any object or value.
let data = null;
Value undefined
The value undefined
indicates that a variable has been declared but has not yet been assigned any value.
let data;
console.log(data); // Output: undefined
Composite Data Types
Composite data types in JavaScript are those that can contain multiple values and have methods and properties. They are mutable, which means they can change after their creation.
Objects (object
)
Objects in JavaScript are collections of key-value pairs, where the key is a string (or symbol) and the value can be any data type, including other objects.
let person = {
name: 'Ana',
age: 30,
married: false
};
Arrays (array
)
Arrays in JavaScript are special objects that allow storing multiple values in a single variable, numerically indexed.
let colors = ['red', 'green', 'blue'];
Special Data Types
Functions (function
)
Functions in JavaScript are special objects that contain an executable block of code and are used to perform a specific task.
function add(a, b) {
return a + b;
}
Symbol Data Type (symbol
)
The symbol
data type is unique and is used for unique identifiers of objects.
const id = Symbol('id');