DEV Community

Muhammad    Uzair
Muhammad Uzair

Posted on

Function Scope Vs Block Scope

In JavaScript there’s two kinds of scope: function-scope and block-scope

Function-scope

function myFn() {
var foo = 'peekaboo!';
console.log(foo); // 'peekaboo!'
}
console.log(foo); // ReferenceError: foo is not defined

Using var, variables are function-scoped because their visibility is limited to the function. When you try to use it outside of the function, you’ll get an error.

Block-scope

A block of code is the code between curly braces in JavaScript

if (true) {
var message= 'peekaboo!';
let text = 'i see u';
const string = 'baby blue!';
console.log(message); // 'peekaboo!';
console.log(text ); // 'i see u';
console.log(string ); // 'baby blue!';
}
console.log(message); // 'peekaboo!';
console.log(text ); // ReferenceError: bar is not defined
console.log(string ); // ReferenceError: baz is not defined

Notice the visibility of message isn’t limited by the if-statement block. However, both text and string are limited in visibility to the block of code.

This concept of scope is the most prominent distinction between the old-fashioned var and modern let/const.

We will cover use of let/const/var in next article.

Top comments (0)