Data types in JavaScript are attributes that determine the type of value that a variable can contain. These data types are used to represent different types of information.
JavaScript is a dynamically typed programming language, which means that it is not necessary to explicitly declare the type of a variable when it is created.
But that does not mean that JavaScript has no types. The type is automatically determined 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, meaning 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 isAdult = true;
let isActive = false;
Null Value
In JavaScript, null
is a special value that represents the intentional absence of any object or value.
let data = null;
Undefined Value
The undefined
value 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, meaning 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, indexed numerically.
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 object identifiers.
const id = Symbol('id');