JAVASCRIPT

JavaScript let: Syntax, Usage, and Examples

let is a JavaScript keyword that declares a variable you can reassign later. It also gives your code cleaner rules for scope than older variable declarations.

How to Use let

You use let when you want to create a variable and allow its value to change over time.

Basic syntax

let message ="Hello";
message ="Hi";// reassignment is allowed

A let variable starts at the moment JavaScript reaches its declaration. After that, you can read it, update it, and pass it around like any other variable.

Declaring first, assigning later

Sometimes you don’t know the value yet. That’s fine.

let username;
username ="Amina";

Until you assign a value, the variable exists but holds undefined.

Block scope with curly braces

A key feature of let is block scope. That means a variable created inside { ... } only exists in that block.

if (true) {
let color ="purple";
console.log(color);// "purple"
}

console.log(color);// ReferenceError

This reduces accidental bugs, because your variables stay where they belong.

Updating a variable in a loop

let is a natural fit for loops, especially when the counter changes.

for (let i =0; i <3; i++) {
console.log(i);
}

The loop counter i only exists inside the loop, which helps avoid naming conflicts.

Declaring multiple variables

You can declare more than one variable in a single statement, although many developers prefer one per line for readability.

let firstName ="Kai", lastName ="Ng";

Re-declaring is not allowed

You cannot declare the same let variable twice in the same scope.

let score =10;
let score =20;// SyntaxError

This is another safety net that prevents confusing code.

When to Use let

let is useful whenever a value needs to change, but you still want predictable scoping.

1) When a value changes over time

Scores, counters, search input, and toggles often update.

let lives =3;
lives = lives -1;

2) When you need temporary variables inside a block

Inside if, switch, and loops, you often want helper variables that should not leak outside.

if (userRole ==="admin") {
let label ="Admin tools enabled";
console.log(label);
}

3) When you want to avoid weird bugs from function scope

Older JavaScript used var, which is function-scoped. let behaves in a more “what you see is what you get” way.

4) When writing modern JavaScript

Most ES6+ codebases prefer let for variables that change, and const for variables that should not change. That makes intent obvious to someone reading your code.

Examples of let

Example 1: Tracking form input

A common pattern is storing user input so you can validate it or send it to an API.

let email ="";

functionupdateEmail(newValue) {
  email = newValue.trim();
}

updateEmail("  sam@example.com  ");
console.log(email);// "sam@example.com"

The variable updates as the user types or when an event fires.

Example 2: Building a shopping cart total

Totals often change as items are added and removed.

let total =0;

functionaddToCart(price) {
  total = total + price;
}

addToCart(19.99);
addToCart(4.50);

console.log(total);// 24.49

This is simple, readable, and perfect for a let.

Example 3: Counting completed tasks

Imagine a small checklist app.

const tasks = [
  {title:"Write outline",done:true },
  {title:"Draft content",done:false },
  {title:"Review",done:true }
];

let completed =0;

for (let i =0; i < tasks.length; i++) {
if (tasks[i].done) {
    completed = completed +1;
  }
}

console.log(completed);// 2

The loop counter and completed value both change, so let fits naturally.

Example 4: Safe variables inside a condition

Sometimes you want a value only inside one branch.

const temperature =8;

if (temperature <10) {
let message ="Bring a jacket.";
console.log(message);
}else {
let message ="T-shirt weather.";
console.log(message);
}

Each message exists only inside its own block. They don’t collide.

Learn More About let

let vs const

A quick rule that works well:

  • Use const when you do not plan to reassign the variable.
  • Use let when reassignment is expected.
const appName ="Mimo";
let activeTab ="Home";

activeTab ="Build";

const does not mean a value is “frozen,” it only means the variable binding cannot be reassigned. For objects and arrays, the contents can still change.

const colors = ["red","blue"];
colors.push("green");// allowed

let vs var

var is the older way to declare variables. Modern JavaScript mostly uses let and const instead, because they behave more predictably.

Scope differences

  • let is block-scoped.
  • var is function-scoped.

That difference can lead to bugs that are hard to spot.

functiondemo() {
if (true) {
var x ="I exist outside the block";
let y ="I stay inside the block";
  }

console.log(x);// works
console.log(y);// ReferenceError
}

demo();

With var, x escapes the if block. With let, y does not.

Hoisting differences

Both var and let are hoisted, meaning the declaration is processed before code runs. The big difference is how you can use them.

With var, you can access the variable before the declaration, and you’ll get undefined.

console.log(city);// undefined
var city ="Vienna";

With let, accessing the variable before the declaration throws an error. JavaScript puts it in a “temporary dead zone” until the declaration runs.

console.log(city);// ReferenceError
let city ="Vienna";

This is a good thing. It prevents accidental use of variables before they exist.

Re-declaration differences

var allows re-declaration in the same scope, which can cause surprises.

var points =5;
var points =10;// allowed

let blocks that mistake.

let points =5;
let points =10;// SyntaxError

If you are writing modern JavaScript, let is usually the safer choice.

let in loops and closures

A classic JavaScript bug happened when var was used in loops with async code. All callbacks would often see the same final value.

let fixes that because each loop iteration gets its own block-scoped variable.

for (let i =1; i <=3; i++) {
setTimeout(() => {
console.log(i);
  },100);
}

This prints 1, 2, 3. With var, it often prints 4 three times, because the same variable was reused.

Common mistakes with let

1) Trying to use it before it exists

console.log(total);
let total =50;

This throws a ReferenceError. Move the declaration above usage.

2) Accidentally shadowing variables

Shadowing means declaring a new variable with the same name inside a nested scope.

let status ="offline";

if (true) {
let status ="online";
console.log(status);// "online"
}

console.log(status);// "offline"

This is not always bad, but it can be confusing. Using clearer names can help.

3) Using let when const makes more sense

If the variable never gets reassigned, const communicates intent better.

const maxRetries =3;

Summary

let is the modern way to declare variables that can change. It gives you block scope, prevents accidental re-declaration, and avoids many of the confusing behaviors that came with var. Use let for values that change, and pair it with const for values that should stay the same.