DEV Community

Cover image for Variables scope in Javascript
Muhammad Bilal
Muhammad Bilal

Posted on • Updated on

Variables scope in Javascript

Javascript variables are a container for storing values. In javascript, there are three types of variables let const and var.

var variable has a functional scope which means that variables that are defined inside a function can only be accessible within the function.
var functional scope

var type variables don't have block scope they are accessible outside of the block
var block scope

var type variables override var type variable which has the same name in their scope.
Alt Text

Redeclaring a let or const variable with var is not allowed in the same scope and in functional scope
Alt Text

let type variable has the same functional scope as var variable but they also have Block sope
let functional scope

let type variable defined in Block are NOT accessible outside of Block as shown in the example.
let block scope

Redeclaring a let variable with type let or const or var is not allowed in the global. The compiler will throw an error
let variable global scope

Redeclaring a let variable with type let or const or var is not allowed in the block. The compiler will throw an error
let variable block scope

Redeclaring a let variable with type let or const or var is not allowed in the functional scope. The compiler will throw an error
let variable function scope

Now let's talk about const variables. As the name suggests we cannot reassign a value to the const variable.
const variable

const type variable also have functional and Block level scope.
const functional scope

const type variable defined in Block is NOT accessible outside of block as shown in the example.
const block scope

Redeclaring a const variable with type let or const or var is not allowed in the global. The compiler will throw an error
const variable global scope

Redeclaring a const variable with type let or const or var is not allowed in the block. The compiler will throw an error
const variable block scope

Redeclaring a const variable with type let or const or var is not allowed in the functional scope. The compiler will throw an error
const variable functional scope

Top comments (0)