DEV Community

ABISHEK M
ABISHEK M

Posted on

Scope in JavaScript

What Does Scope Mean?

Scope means: where can we use a variable? Some variables work everywhere in the code. Some variables work only in one small part.

Think of a House

In a house, everyone can use the TV in the living room. But only you can use the things in your own bedroom. Variables are the same. Some are like the TV (usable everywhere). Some are like your bedroom things (usable only in one place).

var — Works in the Whole Function

var can be used anywhere inside the function, even outside an if block.

function testVar() {
  if (true) {
    var name = "Abishek";
  }
  console.log(name); // works fine
}
Enter fullscreen mode Exit fullscreen mode

let — Works Only Inside its Block

let can only be used inside the { } where it was made.

function testLet() {
  if (true) {
    let name = "Abishek";
  }
  console.log(name); // error
}
Enter fullscreen mode Exit fullscreen mode

const — Same Rule as let

const also works only inside its block. The only difference is, its value cannot be changed later.

function testConst() {
  if (true) {
    const name = "Abishek";
  }
  console.log(name); // error
}
Enter fullscreen mode Exit fullscreen mode

Simple Table

Keyword Where it works
var Whole function
let Only its block
const Only its block

In Short

var works in the whole function. let and const work only inside their own block. Knowing this helps you understand why some errors happen in JavaScript.

Top comments (0)