By Ronak Wanjari | Intern at @devsyncin
Functions are the heart of JavaScript, and understanding how they work internally helps write better and cleaner code. As I learned during my internship at @devsyncin , every function in JavaScript creates its own world called the Execution Context when it runs.
๐ง What's Inside a Function Execution?
When a function is invoked, JavaScript creates:
๐ฆ A Variable Environment โ stores variables and parameters.
๐ A Scope Chain โ connects it to outer environments.
๐งโโ๏ธ A this keyword โ depends on how the function is called.
๐** Understanding Variable Environment**
The Variable Environment includes:
Function parameters
Variables (var, let, const)
Inner function declarations
This environment is temporary and recreated every time the function is called.
function greet(name) {
let message = "Hello " + name;
return message;
}
Each call to greet("Ronak") creates a fresh environment with name = "Ronak" and message = "Hello Ronak".
๐งฉ Hoisting & Variable Environment
Understanding variable environments makes hoisting easier to grasp. Variables declared with var are hoisted to the top of the environment, but only the declarationโnot the value.
function test() {
console.log(x); // undefined
var x = 5;
}
x exists in the environment but is undefined at first.
Mentored and guided by @devsyncin
Top comments (2)
Been messing with this exact thing lately, the scope stuff always makes my head hurt but I get it a bit more every time. Nice one.
Maybe you could have written how the code is interpreted with "hoisting" :
x exists in the environment but is undefined at first.