DEV Community

Cover image for 🔍 How Functions Work in JavaScript ❤️ & Variable Environment
ronak wanjari
ronak wanjari

Posted on

🔍 How Functions Work in JavaScript ❤️ & Variable Environment

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".
Enter fullscreen mode Exit fullscreen mode

🧩 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.

Enter fullscreen mode Exit fullscreen mode

Mentored and guided by @devsyncin

JavaScript #Functions #VariableEnvironment #Hoisting #WebDevelopment #Devsync

Top comments (2)

Collapse
 
nevodavid profile image
Nevo David

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.

Collapse
 
alexmustiere profile image
Alex Mustiere

Maybe you could have written how the code is interpreted with "hoisting" :

function test() {
  var x; // declaration is "hoisted" at the top
  console.log(x); // undefined
  x = 5; // affectation remains where it was writtent
}
Enter fullscreen mode Exit fullscreen mode

x exists in the environment but is undefined at first.