freeCodeCamp/guide/english/certifications/javascript-algorithms-and-d.../es6/compare-scopes-of-the-var-a.../index.md

3.1 KiB

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:

We need to change var to let in our function scope and add let to our block scope.

:speech_balloon: Hint: 1

  • Find var and replace with let.

try to solve the problem now

  • Add let to the variable i inside of your if statement.

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;
    }

:rocket: Run Code

Code Explanation:

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

:clipboard: NOTES FOR CONTRIBUTIONS:

  • :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:
  • Please add your username only if you have added any relevant main contents. (:warning: DO NOT remove any existing usernames)

See :point_right: Wiki Challenge Solution Template for reference.