Page 1 of 1
A variable in JavaScript is a container used to store data. * It can be declared using "var", "let", or "const", with each having different scoping rules and mutability.
let name = "Alice"; // 'let' is block-scoped
const birthYear = 1990; // 'const' is block-scoped and cannot be reassigned
var city = "New York"; // 'var' is function-scoped (deprecated in modern JS)
JavaScript has two main categories of data types: - Primitive Types and Non-primitive Types. * Primitive types are immutable and hold a single value, while non-primitive types are mutable and can hold multiple values. * Primitive Types: String, Number, Boolean, Null, Undefined, Symbol, BigInt. * Non-primitive Types: Object (including Array, Function, etc.)
let name = "John"; // String
let age = 30; // Number
let isAdult = true; // Boolean
let address = null; // Null
let salary; // Undefined
let uniqueID = Symbol("id"); // Symbol
let bigNumber = 9007199254740991n; // BigInt (add 'n' at the end for BigInt)
let person = { name: "John", age: 30 }; // Object
let colors = ['red', 'green', 'blue']; // Array
let greet = function() { return "Hello"; }; // Function
"null" is a special value representing the absence of any value, while "undefined" means a variable has been declared but not assigned a value.
let address = null; // Null
let phoneNumber; // Undefined (not assigned a value)
In JavaScript, `let`, `var`, and `const` are used for variable declarations, but they differ in their behavior: - **`var`**: * Function-scoped. * Can be redeclared and updated. * Hoisted with undefined value (not block-scoped). - **`let`**: * Block-scoped. * Cannot be redeclared in the same scope but can be updated. * Hoisted but not initialized (temporal dead zone). - **`const`**: * Block-scoped. * Cannot be redeclared or updated. * Used for variables whose value should not change. * For objects and arrays declared with `const`, the reference cannot be reassigned, but the contents can be mutated.
var x = 10;
if (true) {
var x = 20; // Redeclares and updates the same variable
console.log(x); // Output: 20
}
console.log(x); // Output: 20
let y = 10;
if (true) {
let y = 20; // Creates a block-scoped variable
console.log(y); // Output: 20
}
console.log(y); // Output: 10
const z = 10;
if (true) {
const z = 20; // Creates a block-scoped variable
console.log(z); // Output: 20
}
console.log(z); // Output: 10
// Mutating objects with const
const person = { name: "John" };
person.name = "Doe"; // Allowed: Mutating the object
console.log(person.name); // Output: Doe
// Reassigning a const variable
// const person = {}; // Error: Cannot reassign a const variable
Page 1 of 1