Understanding Scope in Javascript

Understanding Scope in Javascript

This article will cover basic concept like Scope in Javascript. Scope defines the visibility of a variable, these variables are not visible outside the scope in which they are declared.

Javascript has global scope, function scope and block scope.

Global Scope

Variables defined outside any function, block or module scope have global scope. These variables can be accessed from everywhere.

let message = "Hello"
function start(){
    console.log(message);
}

start();
//Output : Hello

In the above example, you can see that the variable "message" was declared outside the function named "start" but we were able to access the variable without any error.

Function Scope

Variables and parameters that are defined in a function are visible everywhere within the function, but we won't be able to access them outside the function.

function start(greeting){
    const message = "Hi";
}
console.log(message);
//Output: ReferenceError: message is not defined

As you can see, we were not able to access the variable "message" outside the function which was declared inside the function.

Block Scope

Variables declared with 'let' and 'const' keyword within curly braces have block scope.

{
    let x = "Hi"
}
console.log(x);
//Output: ReferenceError: x is not defined

The variable defined inside the block(it can be if, for or while) can only be accessed within the block.

Bonus

Javascript has evolved over the years, initially we used to declare variables using 'var' keyword. But with the introduction of ES6, the entire perspective of variables have changed when 'let' and 'const' were introduced. The scope can only be used for variables defined with 'const' and 'let' keyword. For variables defined using 'var' keyword, the concept is completely different. Let's look at an example to understand the hoisting for 'var' in Javascript.

console.log(x);
var x = 1;
console.log(x);
// Output: undefined
//         1

The variable x is hoisted at the top of the global scope, which makes it possible to access the variable before it was declared, without any error. But what you'll notice here is the log we are trying to print doesn't print the exact value(x is initialized with 10) but 'undefined'. So when we try to access variables before it was declared, you get default initialization that happens with var which is 'undefined'. Same is not true for variables declared with 'let' and 'const' keyword

Thank you for reading!

#Scope #Hoisting #Javascript #LCO #IWriteCode #iNeuron #FullStackJavaScriptWebDeveloperBootcamp