Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    1Topic
    |
    1 Quiz
Lesson 5, Topic 6
In Progress

JavaScript: Practice Good Scoping

Yasin Cakal 10 Nov 2021
Lesson Progress
0% Complete

We should use block scope to scope our variables as tightly as possible because of the problems with global variables and scope pollution.

In several ways, tightly scoping your variables will greatly improve your code:

  • Because the blocks divide your code into discrete sections, it will be easier to read.
  • It clarifies which variables are associated with different parts of the program rather than having to keep track of them line by line, making your code more understandable!
  • Because your code will be modular, it will be easier to maintain.
  • It will save memory in your code because it will no longer exist once the block has completed its execution.

Here’s another example of how to use block scope within an if statement:

const returnDay = () => {
  const weekend = true;
  let day = 'Monday'; 
  if (weekend) {
    let day = 'Sunday';
    console.log(day); // Sunday
  }
  console.log(day); // Monday
};
console.log(day); // ReferenceError: day is not defined

You’ll notice the following:

  • Within the returnDay() function, we create a variable called day.
  • We create a new code block with the braces after the if statement. If the if statement is true, we assign a new value to the variable day.
  • The day variable has the value Sunday within the if block, but the day variable has the value Monday outside the if block, in the function body.
  • Even though we are using block scope, we are still polluting our namespace by repeating the same variable name. Renaming the variable inside the block is a better practice.

In JavaScript, block scope is a useful tool because it allows us to define variables precisely while avoiding polluting the global namespace. If a variable isn’t required outside of a block, it shouldn’t be there!

Responses

Leave a Reply

%d bloggers like this: