JavaScript is a dynamically typed language, which means variables can hold values of different data types. Understanding data types is essential for working with values effectively.
JavaScript has six primitive (or simple) data types:
let numberVar = 42; // Number
let price = 19.99; // Floating-point number
let stringVar = "Hello"; // String
let booleanTrue = true; // Boolean
let booleanFalse = false; // Boolean
let nullVar = null; // Null
let undefinedVar; // Undefined
let id = Symbol("unique identifier"); // Represents a unique and immutable value often used as object property keys.
// Creating a Symbol
let idSymbol = Symbol("id");
// Using Symbols as object property keys
let user = {
[idSymbol]: 123,
name: "Alice"
};
console.log(user[idSymbol]); // Access the property using the Symbol
// Checking for the existence of a Symbol property
console.log(idSymbol in user); // true
// Getting the description of a Symbol
console.log(idSymbol.description); // "id"
In this example, the idSymbol is used as a property key in the user object. The Symbol is unique, so it doesn't clash with other properties. The description property allows you to retrieve the description provided during the Symbol creation.
Symbols are often used in libraries and frameworks to define non-enumerable properties, manage internal states, and ensure property uniqueness. While Symbols are not often used for everyday tasks, they provide a powerful tool for creating robust and well-encapsulated code.
JavaScript has one complex (or reference) data type
Object Represents a collection of key-value pairs, where values can be of any data type, including other objects.
var person = {
firstName: "John",
lastName: "Doe",
age: 30
};
You can use the typeof operator to check the data type of a value.
let num = 42;
console.log(typeof num); // Outputs: "number"
let name = "Alice";
console.log(typeof name); // Outputs: "string"
let isStudent = true;
console.log(typeof isStudent); // Outputs: "boolean"
JavaScript performs implicit and explicit type conversions.
let x = "5"; // String
let y = 10; // Number
let sum = x + y; // Implicit conversion: sum is "510"
let numString = "42";
let numValue = Number(numString); // Explicit conversion: numValue is 42
let value = 42;
let strValue = String(value); // Explicit conversion: Converts 42 to the string "42"
let num = 0;
let bool = Boolean(num); // Explicit conversion: Converts 0 to false, other numbers to true
Understanding JavaScript data types is crucial for writing code that works correctly and efficiently with different kinds of values.