What is scope?

Question

What is scope?

Answer

scope is the context of code that determines the availability of parts of a program - including variables, objects, functions, etc - to another part of the program when the code is executed. If a variable/object/function/etc is not in the current scope that means it’s not available for reference or use.

For example:

let x = 1;

const myFunction = () => {
  let x = 2; //sets a `let` variable x to the value `2`
}
myFunction(); //calls myFunction 
console.log(x); //`1` is logged to the console because although there are two `let` variables that have the same name, the `let` variable inside the function is scoped to the block (in this case a function) it's in and the console.log outside of the function is not able to access the `let x` variable that is inside the function because it's scoped. 

Do note that this explanation and example is a very basic overview of scope. For a more detailed and in-depth explanation please check out the MDN documentation, other documentation, and tutorials for variables (in particular, how different variables are scoped), scope, and hoisting.

Scope is the environment in which a value exists, and any references to that value. Scope exists along a chain. Nothing associated with the link above can gain access to that environment. There is no parent looking over this scope. It’s variables and constants are inaccessible to parent scope

The JavaScript interpreter is greedy and relentless. We should always keep this in mind. JS will look for a variable of the name written and if it finds it somewhere in the scope chain, use that value, legal or not.

7 Likes

I’m confused, can someone explain the answer for this exercise? I can’t tell where the scope error is and the difference between the original and solution.

@jnijnijni
Hey, to find out easily and quickly where errors may occur in our code it’s best to run it,
the output we get can sometimes point us towards where an error is.

In this exercise, the code return [8] rather than [8,4,16,32], so we can see the for loop may have run once instead of 4 times, then we have to ask ourselves why?
const numbers = [5, 3, 9, 30];

const smallestPowerOfTwo = arr => {
let results = ;
// The ‘outer’ for loop - loops through each element in the array
for (let i = 0; i < arr.length; i++) {
number = arr[i];

// The ‘inner’ while loop - searches for smallest power of 2 greater than the given number
i = 1;
while (i < number) {
i = i * 2;
}
results.push(i);

  }


  return results

}

console.log(smallestPowerOfTwo(numbers))
// Should print the returned array [ 8, 4, 16, 32 ] instead prints the returned array [8]

The scope error occurs within the “for” loop, notice we use “i” as our iterator variable in the “for” loop. Then just above the “while” loop, our iterator variable has been sneakily reassigned to “1”. To make things worse, we use “i” in our “while loop! For this exercise in the first iteration the number is 5, meaning the least power of two greater than 5 is 8.
Notice again that 'i” which is our iterator variable has been reassigned to 8!

Now our stopping condition is “i < arr.length”, the arr.length for this exercise is 4 and our iterator variable “i” had previous been reassigned to 8, therefore the loop only runs once!
:slightly_smiling_face:

8 Likes

Feeling like an idiot here. I could tell the errors of the code by reading it, but my head have not been able to wrap around the coding request itself. What is this function looking for? it is driving me bunkers!

Basically, if I am asked to write this code from scratch right now I will find it very difficult to do so.

2 Likes

Consider the global namespace where we can declare both functions and variables. Their scope is global.

const foo = function () {
  a = 'foo'
}
let a = 'bar'
foo()

If we log a, what will it be?

console.log(a)    //  ????
1 Like

Thanks for the reply, I was confused about how the while loop operated to find the power of 2, but I have figured it out.

2 Likes

Do you mind explaining it? I’m racking my brain trying to find out what exactly the nested code block is doing and how we are getting the results we do.

thanks!

There are two loops, one of which is definite (has a defined range) and the other which is indefinite (has a defined operating condition).

The defined range is the length of the array.

for (let i = 0; i < arr.length; i++) {
    const number = arr[i]    //  value from the array
    let j = 1    //  always starts with initial value of 1
    while (j < upperBound) {
        //  upperBound is based on number
        //  augment value of j
    }
}

Point out which part(s) you are having a problem understanding.

1 Like

this exercise took me the longest to figure out.

FOR THOSE WHO ARE STUCK WHO WANTS TO FIGURE IT OUT WIHTOUT CLICK THE CODE SOLUTION

  • so you need to create an inner loop using while
  • it should start with 1 but replace the i since it was already used
  • keep multiplying it with 2 untill i is greater than the number
  • so it will have to do 2 4 6 8 10 12 14 16 18 untill it is greater than the number
3 Likes

Thanks for this, this makes perfect sense!

LITTLE EXTRA HELP:

The while statement will find the powers of 2, as follows :

j = 1;
while (j < 10) {
j = j * 2;
console.log(j);
}

// OUTPUT : 2 4 8 16 ;

j=1 * 2 = 2 ;
j=2 * 2 = 4;
j=4 * 2 = 8;
j=8 * 2 = 16 ← it will stop here as j > 10