javascript - Variable Scoping

Hey there, junior coder! Today, we're going to learn about something super important in JavaScript called scoping. Scoping helps decide where you can use your variables and functions in your code.

Think of scoping like the rules of a secret club. Sometimes, only certain parts of your code are allowed to see certain variables. Let’s explore what this means with examples!

Example 1: Proper Scoping

Imagine we’re using let to create a variable inside a function:

function sayHello() { let greeting = "Hello!"; console.log(greeting); // This works! } sayHello(); console.log(greeting); // This will give an error.

What's happening here?

Example 2: Global Scope

Now let’s see what happens when we create a variable that everyone can see:

let favoriteColor = "blue"; function showColor() { console.log(favoriteColor); // This works because favoriteColor is outside the function! } showColor(); console.log(favoriteColor); // This also works!

What's happening here?

Example 3: Improper Scoping

Now let's look at an example where scoping might be a problem:

function countApples() { let appleCount = 5; } countApples(); console.log(appleCount); // This will give an error.

Why is there an error?

Tips to Remember:

Practice Time!

Try writing your own function that creates a local variable and see what happens if you try to use it outside the function. Here’s a quick challenge:


function sayGoodbye() { let farewell = "Goodbye!"; console.log(farewell); // This works! } sayGoodbye(); try { console.log(farewell); // This will give an error. } catch (e) { alert("Oops! It looks like 'farewell' is not defined outside the function."); }

Other Resources

W3Schools JS Scope