Files

2.7 KiB

title
title
Compare Scopes of the var and let Keywords

:triangular_flag_on_post: Remember to use Read-Search-Ask if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:

Problem Explanation:

Change the code so that the variable i declared in the if block is separately scoped than the variable i declared at the beginning of the function.

:speech_balloon: Hint: 1

  • Be certain not to use the var keyword anywhere in your code.

try to solve the problem now

  • Remember that let's scope is limited to the block, function or statement in which you declare it.

try to solve the problem now

Spoiler Alert!

warning sign

Solution ahead!

:beginner: Basic Code Solution:

    function checkScope() {
      "use strict";
      let i = "function scope";
      if (true) {
        let i = "block scope";
        console.log("Block scope i is: ", i);
      }
    console.log("Function scope i is: ", i);
    return i;
    }

Code Explanation:

By using let you can declare variables in relation to their scope.

Resources

  • :warning: DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
  • Add an explanation of your solution.
  • Categorize the solution in one of the following categories — Basic, Intermediate and Advanced. :traffic_light: