DEV Community

Olayemi Elsie
Olayemi Elsie

Posted on

JavaScript Concept

One of the first and most important concepts you encounter in JavaScript is variables

JavaScript provides three main ways to declare variables:

  1. var,
  2. let, and
  3. const

While they may look similar, they behave very differently.

Variable

A variable is like a container that holds a value. You give it a name so you can reference or update that value later in your code.

Example:
let age = 16;

Here, age is assigned to a value of 16.

  1. var – The Old Way: var is the older method of declaring variables in JavaScript.

Key features of var:

  • Function scoped
  • Can be redeclared
  • Can be updated

Example:
Redeclaration
var fruit = "orange"; // declearation
var fruit = "apple"; //redeclearation
console.log(fruit); // apple

Making update
var fruit = "orange";
fruit = "apple"; // update
console.log(fruit); // apple

Redeclaring a variable may overwrite values unexpectedly, making bugs harder to track.

  1. let – This was introduced to fix many of the problems caused by var.

Key features of let:

  • Block scoped can be updated
  • redeclared.

Example:
let age = 16; // declaration
age = 17; // updating (allowed)
console.log(age); // 17

// Redeclaring in the same scope will cause an error:
let age = 16;
if (true) {
let age = 18; // allowed, block-scoped
}

  1. const – const is used for Fixed Values. const is used for values that should never change.

Key features of const:

  • Block scoped,
  • Cannot be updated and
  • Cannot be redeclared.
  • It Must be initialized immediately

Example:

const country = "Nigeria";

Using the correct variable type helps:

  • Prevent bugs
  • Make your code more readable
  • Improve maintainability

Best Practices for Declaring Variables in JavaScript:

  • Use const by default — for values that should not change.
  • Use let only when you need to update or reassign a variable.
  • Avoid var in modern JavaScript to prevent unexpected redeclarations and scope issues.

Top comments (0)