Member-only story
Scope and Hoisting in JavaScript For Beginners
“scope” and “hoisting”
JavaScript is a versatile and widely used programming language, but for beginners, some of its concepts like “scope” and “hoisting” can be a bit challenging to grasp.
In this article, I will explain variable scope and how JavaScript handles variable declarations.
Understanding Variable Scope
In JavaScript, “scope” refers to the context in which variables are declared and accessed. Variables can have either global or local scope:
Global Scope: Variables declared outside of any function are considered global and can be accessed from anywhere in your code.
Local Scope: Variables declared within a function are considered local and can only be accessed within that function.
Global Scope vs. Local Scope
Let’s look at some code examples to illustrate the difference between global and local scope:
// Global scope variable
const globalVar = "I'm global!";
let globalVar2 = "I'm more global";
function exampleFunction() {
// Local scope variable
const localVar = "I'm local!";
let localVar = "I'm more local";
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}…