Data type is a system of data types used to determine the type of data for a variable.
JavaScript supports 6 primitive data types:
Number: This data type is used to represent numbers in JavaScript.
let age = 25;
let height = 1.75;
String: This data type is used to represent character strings in JavaScript.
let name = "John Doe";
let message = 'Welcome to my website!';
Boolean: This data type has only two values, true or false.
let isStudent = true;
let isEmployed = false;
Null: This data type has only one value, null, which represents a non-existent or invalid value.
let data = null;
Undefined: This data type has only one value, undefined, which represents a variable that has not been assigned a value or does not exist.
let age;
console.log(age); // undefined
Symbol: This data type is used to create unique, immutable values.
let id = Symbol("uniqueId");
In addition to primitive data types, JavaScript also supports complex data types, including:
Array: This data type is used to store a collection of values.
let numbers = [1, 2, 3, 4, 5];
let names = ["John", "Jane", "Bob"];
Object: This data type is used to store data components with similar characteristics and behaviors.
let person = {
name: "John Doe",
age: 25,
isStudent: true
};
Function: This data type is used to define code blocks that can be called and executed.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("John"); // Hello, John!
JavaScript provides methods to typecast between different data types.
let age = 25;
let ageAsString = String(age); // Chuyển số thà nh chuỗi
let height = "1.75";
let heightAsNumber = Number(height); // Chuyển chuỗi thà nh số
let isStudent = true;
let isStudentAsString = String(isStudent); // Chuyển boolean thà nh chuỗi