DEV Community

Ragul
Ragul

Posted on

Variables in JavaScript

In JavaScript, variables are named containers used to store data values. They are declared using three keywords: var, let, and const

let:

The recommended modern way to declare variables. It is block-scoped, meaning it is only accessible within the block {} where it is defined. It allows reassignment.

let Name = "Ragul"; // String value
Name = "Ragul Kannadasan";       // Reassignment is allowed
console.log(Name);  // Output: Ragul Kannadasan
Enter fullscreen mode Exit fullscreen mode

const:

Used to declare constants. Like let, it is block-scoped, but the value cannot be reassigned after initialization.

const PI = 3.14;        // Numeric value
// PI = 3.15;          // This would throw an error
Enter fullscreen mode Exit fullscreen mode

var:

The legacy method. It is function-scoped (or globally-scoped if outside a function), which often leads to confusing bugs and is generally avoided in modern code.

function testScope() {
  if (true) {
    var color = "Pink";
  }
  console.log(color); // Output: "Pink" (accessible outside the if block)
}
testScope();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)