Understanding the fundamental data types in JavaScript
JavaScript is a dynamically typed language, which means variables can hold different types of data. Understanding these data types is crucial for effective programming.
JavaScript has six primitive data types:
let name = "John"; // String
let age = 30; // Number
let isStudent = true; // Boolean
let job; // Undefined
let salary = null; // Null
let id = Symbol('id'); // Symbol
In addition to primitive data types, JavaScript has an Object data type. Objects are used to store collections of data and more complex entities.
let person = {
name: "John",
age: 30,
isStudent: true
};
JavaScript also has some special data types:
JavaScript is a loosely typed language, which means it can automatically convert between types. This is known as type coercion.
console.log("5" + 2); // Outputs: "52" (string)
console.log("5" - 2); // Outputs: 3 (number)
You can use the typeof operator to check the type of a variable:
console.log(typeof "Hello"); // Outputs: "string"
console.log(typeof 42); // Outputs: "number"
console.log(typeof true); // Outputs: "boolean"
Understanding data types is fundamental to working with JavaScript effectively. It helps in writing more efficient and error-free code.