JavaScript Tips and code explained Use const and let

Use const and let

Always declare variables with const or let, rather than var:

// Use let

let name = ‘John Doe’;

// Use const

const PI = 3.14;

var, let, and const are used to declare variables.

var is the oldest way to declare variables in JavaScript and has function scope. This means that a variable declared with var inside a function is only accessible within that function. If a var variable is declared outside of a function, it is considered a global variable and can be accessed from anywhere in the code.

var x = 10; // global scope

function example() {

  var y = 20; // function scope


console.log(x); // 10

console.log(y); // ReferenceError: y is not defined

let and const are introduced in ES6 and are block-scoped, meaning that a variable declared with let or const is only accessible within the block it was declared in.

let x = 10; // global scope

if (true) {

  let y = 20; // block scope


console.log(x); // 10

console.log(y); // ReferenceError: y is not defined

The difference between let and const is that let allows you to reassign the variable to a different value, while const does not. Once a variable is declared with const, its value cannot be changed.

const x = 10;

x = 20; // TypeError: Assignment to constant variable.

const y = [1, 2, 3];

y.push(4); // allowed, since arrays are mutable in JavaScript

It is recommended to use const by default, and only use let when you need to reassign the variable. This helps to ensure that your code is more readable, predictable, and secure.