freeCodeCamp Challenge Guide: Global vs. Local Scope in Functions

Global vs. Local Scope in Functions


Hints

Hint 1

Remember that global scope means that the variable is available throughout the entire code. Local scope, means that the variable is available within a certain range.

In this exercise, you have an outerWear variable in global scope with “T-shirt” as its value. You should now create another variable named outerWear, but this time within the function myOutfit(). The basic code solution is as follows:


Solutions

Solution 1 (Click to Show/Hide)
var outerWear = "T-Shirt";

function myOutfit() {
  var outerWear = "sweater";
  return outerWear;
}

myOutfit();

Code Explanation

  • The function will return the closest outerWear it can find. Since we created an outerWear inside the function, that is the ‘closest’, so the function will return “sweater”.
2 Likes

The solution to this problem is:

// Setup
var outerWear = “T-Shirt”;

function myOutfit() {
// Only change code below this line
var outerWear = “sweater”;

// Only change code above this line
return outerWear;
}

myOutfit();

3 Likes

But why put a ready-made solution here? The idea is to learn something))
I would say “use var” before the variable . Or something like that

1 Like

To pass the challenge, you need to create a local variable inside **myOutfit** function that will return a string value of “sweater”.

my understanding was that you will define myOutfit and assign a new variable to to.
woule be something like this,
// Setup
var outerWear = “T-Shirt”;

function myOutfit() {
// Only change code below this line

var myOutfit =“sweater”;

// Only change code above this line
return outerWear;
}

myOutfit();

but the correct solution is

// Setup
var outerWear = “T-Shirt”;

function myOutfit() {
// Only change code below this line

var outerWear =“sweater”;

// Only change code above this line
return outerWear;
}

myOutfit();

1 Like