Defining Variables - var vs. const vs. let

This tutorial provides a quick reference on using var, let, and const for variable declarations in JavaScript. Understanding the differences between these keywords is crucial for writing clean, efficient, and bug-free code.

var

var is the oldest way to declare variables in JavaScript. It has function scope or global scope.

var x = 10; function example() { var y = 20; if (true) { var z = 30; } console.log(x, y, z); // 10, 20, 30 } example(); console.log(x); // 10 console.log(y); // ReferenceError: y is not defined

Key points:

  • Function-scoped or globally-scoped

  • Can be redeclared and updated

  • Hoisted to the top of its scope

let

let was introduced in ES6 (ES2015) and provides block-scoping.

let a = 1; if (true) { let b = 2; console.log(a, b); // 1, 2 } console.log(a); // 1 console.log(b); // ReferenceError: b is not defined

Key points:

  • Block-scoped

  • Can be updated but not redeclared in the same scope

  • Not hoisted

const

const is also block-scoped and used for values that shouldn't be reassigned.

const PI = 3.14159; PI = 3; // TypeError: Assignment to a constant variable const obj = { key: "value" }; obj.key = "new value"; // This works obj = {}; // TypeError: Assignment to a constant variable

Key points:

  • Block-scoped

  • Cannot be updated or redeclared

  • Must be initialized at declaration

  • For objects and arrays, the reference is constant, but properties can be modified

Best Practices

  1. Use const by default

  2. Use let when you need to reassign a variable

  3. Avoid var in modern JavaScript

// Good practice const MAX_SIZE = 100; let currentSize = 0; for (let i = 0; i < MAX_SIZE; i++) { currentSize++; } console.log(currentSize); // 100

This reference should help you choose the right variable declaration for your needs. Remember, using let and const leads to cleaner, more predictable code.

Start Building in JavaScript Today

Lilbots is the best platform for creating powerful JavaScript bots

  • Built in access to cutting edge AI models
  • Out of the box integration with hundreds of APIs
  • Collaborate with coding workspaces
  • Discover and fork thousands of bots built by the community

Learn JavaScript

JavaScript Objects

JavaScript Arrays

JavaScript Basics