JavaScript Data Types
JavaScript variables can store different types of data. Data types tell JavaScript what kind of value a variable holds.
Primitive Data Types
- Number
- String
- Boolean
- Null
- Undefined
Non-Primitive Data Types
- Object
- Array (a type of object)
Number
Represents numerical values. Numbers can be written with or without decimals.
Example:
let x1 = 34.00;
let x2 = 34;
let x3 = 3.14;
Output:
34
34
3.14
String
Represents text. Strings must be enclosed in quotation marks (single or double).
Example:
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
Output:
It's alright
He is called 'Johnny'
He is called "Johnny"
Boolean
Represents only two values: true or false. Often used in conditions and comparisons.
Example:
let isPassed = true;
let isAdmin = false;
Output:
true
false
Array
An array stores multiple values in one variable. Array indexes are zero-based, meaning the first item is at index 0.
Example:
const cars = ["Saab", "Volvo", "BMW"];
cars[0];
Output:
Saab
Object
Objects store data in key-value pairs.
Example:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Output:
John is 50 years old.
Null
Represents an intentional empty value. It means a variable exists but has no value.
Example:
let car = "";
Output:
The value is:
The type is: string
Note: In JavaScript, an empty string ("") is not the same as null, but your example demonstrates that empty strings still have a type.
Undefined
A variable is undefined when no value has been assigned to it.
Example:
let car;
Output:
undefined
undefined
Summary
- Number: numerical values
- String: text
- Boolean: true or false
- Null: intentionally empty value
- Undefined: a variable with no value assigned
- Object: key-value pairs
- Array: ordered collection of values