In JavaScript, variables and constants are used to store data that can be referenced and manipulated within a program. Understanding how to declare and use variables and constants, as well as the concepts of scope, is essential for writing effective and maintainable code. This blog will cover the different ways to declare variables (var, let, and const) and explain variable scope (global vs. local scope).
The var keyword is used to declare a variable. Variables declared with var are function-scoped or globally scoped if declared outside a function. The var keyword has been part of JavaScript since its inception, but it has some limitations and quirks.
var name = 'Alice';
console.log(name); // Output: Alice
var inside a function is only accessible within that function.function greet() {
var greeting = 'Hello';
console.log(greeting); // Output: Hello
}
console.log(greeting); // ReferenceError: greeting is not defined
var are hoisted to the top of their scope and can be used before they are declared, but they will be undefined until the declaration is encountered.console.log(age); // Output: undefined
var age = 25;
The let keyword is used to declare block-scoped variables, introduced in ES6 (ECMAScript 2015). Unlike var, let variables are not hoisted to the top of their block.
let city = 'New York';
console.log(city); // Output: New York
let is only accessible within the block (e.g., { }) in which it is declared.{
let color = 'blue';
console.log(color); // Output: blue
}
console.log(color); // ReferenceError: color is not defined
let are not hoisted to the top of their block, so using them before declaration results in a Reference-error.console.log(height); // ReferenceError: height is not defined
let height = 180;