Introduction to JavaScript​ 5

1/7 SCOPE

Scope

Scope refers to where a variable can be accessed in a program. While some variables can be accessed from anywhere within a program, other variables may only be available in a specific context. Scope depends entirely on where a variable is declared.

You can think of scope like the view of the night sky from your window. Everyone who lives on the planet Earth is in the global scope of the stars. The stars are accessible globally. Meanwhile, if you live in a city, you may see the city skyline or the river. The skyline and river are only accessible locally in your city, but you can still see the stars that are available globally.

 

We’ll learn more about scope in this lesson through the use of variables.

 

2/7 SCOPE

Global Scope

We’ll start with global scope. Variables defined in the global scope are declared outside of a set of curly braces {}, referred to as a block, and are thus available throughout a program. We’ll cover more on blocks in subsequent exercises.

Let’s take a look at an example of global scope.

 

const color = ‘blue’

 

const colorOfSky = () => {

  return color; // blue 

};

console.log(colorOfSky()); // blue

Here the variable color is declared outside of the function block, giving it global scope.

In turn, color can be accessed within the colorOfSky function.

Global variables make data accessible from any place within a program.

 

Instructions

  1. At the top of sky.js, write two global variables using const, one named satellite set equal to ‘The Moon’, the other named galaxy set equal to ‘The Milky Way’.
  2. Using let, write another global variable name stars and set it equal to ‘North Star’.
  3. Below these variables, using const, write a function named myNightSky. Inside the function, include a return statement like this:

return ‘Night Sky: ‘ + satellite + ‘, ‘ + stars + ‘, ‘ + galaxy;

 

  1. Beneath the myNightSky() function, use console.log() to log the value of myNightSky() to the console.
    You’ll notice that the myNightSky() function is able to access the global variables without any problem since the variables are available globally.

3/7 SCOPE

Global Scope II

While it’s important to know what global scope is, it’s better to avoid defining variables in the global scope. Globally scoped variables can collide with variables that are more locally scoped, causing unexpected behavior in our code.

Let’s explore our program a little further.

 

Instructions

  1. Let’s see what happens if we create a variable that overwrites a global variable.
    Inside the myNightSky() function, on the very first line of the function, assign the variable stars to ‘Sirius’ as such:

stars = ‘Sirius’;

 

  1. Outside the function, under the previous console.log() statement, console.log() the value of stars.
    You’ll notice that the global variable stars was reassigned to ‘Sirius’. In other words, we unexpectedly changed the value of the global variable, and this could impact our program in ways we do not intend.

4/7 SCOPE

Block Scope

Because of the challenges with global scope, it is preferable to define variables in block scope.

A block refers to the {} braces of a function, a loop, or an if statement, and serves as an important structural marker for our code. Block scope means that a variable defined in the block is only accessible within the curly braces.

Block scope works like this:

 

const colorOfSky = () => {

  let color = ‘blue’

  console.log(color); // blue 

};

 

colorOfSky(); // blue 

console.log(color); // undefined

 

You’ll notice:

  • We define a function colorOfSky().
  • Within the function, the color variable is only available within the curly braces of the function.
  • If we try to log the same variable outside the function, it logs undefined.

 

Instructions

 

  1. In light.js, using const, define a function visibleLightWaves().
  2. Within the visibleLightWaves() function, using let, create a variable lightWaves and set it equal to ‘Moonlight’.
  3. Within the function, beneath the lightWaves variable, add a console.log() statement that will log the value of the lightWaves variable when the function runs.
  4. Call the visibleLightWaves() function from outside the function.
  5. Beneath the function call, log the value of lightWaves to the console from outside the function.
    You’ll notice that it logs a ReferenceError since the variable is tied to the block scope of the function!

5/7 SCOPE

Block Scope II

Let’s take a look at another example of block scope, as defined within an if block:

 

const colorOfSky = () => {

  const dusk = true;

  let color = ‘blue’

  if (dusk) {

    let color = ‘pink’;

    console.log(color); // pink

  }

  console.log(color); // blue 

};

 

colorOfSky(); // blue

console.log(color); // undefined

 

Here, you’ll notice:

  • We create a variable dusk inside the colorOfSky() function.
  • After the if statement, we define a new code block with the {} braces. Here we assign a new value to the variable color if the if statement is true.
  • Within the if block, the color variable holds the value pink, though outside the if block, in the function body, the color variable holds the value blue.

Block scope is a powerful tool in JavaScript, since it allows us to define variables with precision, and not pollute the global namespace.

 

Instructions

 

  1. Remove the statement that erroneously logs the value of the lightWaves variable to the console outside of the function block.
  2. Let’s continue by adding another variable to the visibleLightWaves() function. Beneath the lightWaves variable, using let, add a variable region and set it equal to ‘The Arctic’.
  3. Beneath the region variable, create an if statement that checks if the region is the ‘The Arctic’.
  4. Inside the if block, define a new variable lightWaves and set it equal to ‘Northern Lights’.
  5. Beneath the variable in the if block, use console.log() to log the value of the block variable inside the if block.
    Notice the ouput. Inside the if block console.log(lightWaves) logs the value Northern Lights to the console. Outside the if block, but still within the function, the same statement logs Moonlight to the console.

6/7 SCOPE

Block Scope III

Let’s take a look at one other common example of block scope, as defined within a for loop.

 

const cloudCount = () => {

  let i = 2;

  console.log(i); // 2

  for (let i = 0; i < 10; i++) {

    console.log(i); // All numbers from 0 to 9

  }

};

 

cloudCount();

console.log(i); // undefined

 

  • Here the variable i is defined in the cloudCount() function.
  • Within the for loop block, we again define i, as a value that will be incremented.
  • The local value of i, whether defined in the function block or the for loop, has no impact on the global scope of our program.

 

Instructions

  1. Using const, declare a new function called starCount().
  2. Within the starCount() function, declare a variable named i and set it equal to 5.
  3. Right beneath the variable declaration, log the value of the i value to the console.
  4. Beneath the previous console.log() statement, create a for loop.
    The for loop should begin counting when i = 0, as long as i < 12, and increment the value i by 1 each time the loop runs.
    Within the block of the for loop, log the value of i to the console, as demonstrated in the example.

 

const starCount = () => {

… 

  for (let i = 0; i < 12; i++) {

    console.log(i); // All numbers from 0 to 11

  }

};

 

  1. Call starCount() function, from outside of the function.
  2. Finally, beneath the function call, log the value of i to the console from outside of the function.
    You will notice that it returns a Reference Error! The value of i is contained in the block scope.

7/7 SCOPE

Review: Scope

This unit introduced you to scope.

 

    • Scope is the idea in programming that some variables are accessible/inaccessible from other parts of the program.
    • Global Scope refers to variables that are accessible to every part of the program.
    • Block Scope refers to variables that are accessible only within the block they are defined.
 

Sé el primero en comentar

Deja una respuesta