Introduction

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).

Declaring Variables

Var

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
function greet() {
  var greeting = 'Hello';
  console.log(greeting); // Output: Hello
}
console.log(greeting); // ReferenceError: greeting is not defined
console.log(age); // Output: undefined
var age = 25;

Let

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 color = 'blue';
  console.log(color); // Output: blue
}
console.log(color); // ReferenceError: color is not defined
console.log(height); // ReferenceError: height is not defined
let height = 180;

Const