CodeNewbie Community 🌱


Posted on

What is the scope of variables in JavaScript?

Hey all! I've been taking an online development course for a few weeks and have working on JavaScript lately. But I've been struggling with the idea of scope.

Can anyone help me understand what scope of variables is in JavaScript?

Many thanks!

Top comments (2)

vonheikemen profile image

I like to think the scope as an "area". An area where a variable exists with a given value.

If someone asks me "what is the scope of a variable?", I imagine they try to ask me "where does this variable exists?"

Take this example.

function process() {
  let color = 'rebeccapurple'
  // moar code

Enter fullscreen mode Exit fullscreen mode

The area of the code where color has the value rebeccapurple is the block inside the process function. It doesn't exists anywhere else. In fact, that piece of code will throw a ReferenceError telling you color is not defined.

There are different types of scope that people mention a lot:

  • Global scope: Means the whole program. A variable in the global scope is one that you can access in the whole codebase.

  • Function scope: Means the body of a function. When someone says "this variable doesn't leave the function scope", they try to tell you the variable doesn't exists outside the function.

  • Block scope: This I need to show you.

  let color = 'hotpink'

Enter fullscreen mode Exit fullscreen mode

Those curly braces form a block, and it has it's own scope. What's interesting is that even thought is not a function, the variable color only exists with the value hotpink inside those curly braces.

When you think about the scope of a variable, just try to ask yourself "where does this variable exists?"

jacobmgevans profile image
Jacob M-G Evans

Ok so a little on this. I am going to ignore var for this it's special and for another time.
So let's talk about block scope. When I am writing something in a file there is a global level outside all functions, once I enter a function I am inside the scope of that function, however it doesn't end there, say I enter a statement block like if (something) { statement block scope } now comes the interesting part...

const unicorn = "unicorn";
console.log(unicorn); //unicorn

if (true) {
  // Scoping allows for variable shadowing
  const unicorn = "differentUnicorn";
  console.log(unicorn); // differentUnicorn

  const rainbows = "RAINBOW";
  console.log(rainbows); // "RAINBOW"

function hellowWorld() {
  const helloWorld = "MyName"; // 'helloWorld' is declared but its value is never read.

console.log(helloWorld); // helloWorld is not defined

console.log(rainbows); // rainbows is not defined
Enter fullscreen mode Exit fullscreen mode