freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-an.../basic-javascript/local-scope-and-functions.e...

2.3 KiB

id title challengeType
56533eb9ac21ba0edf2244bf Local Scope and Functions 1

Description

Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function. Here is a function myTest with a local variable called loc.
function myTest() {
  var loc = "foo";
  console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
loc is not defined outside of the function.

Instructions

Declare a local variable myVar inside myLocalScope. Run the tests and then follow the instructions commented out in the editor. Hint
Refreshing the page may help if you get stuck.

Tests

tests:
  - text: No global <code>myVar</code> variable
    testString: 'assert(typeof myVar === ''undefined'', ''No global <code>myVar</code> variable'');'
  - text: Add a local <code>myVar</code> variable
    testString: 'assert(/var\s+myVar/.test(code), ''Add a local <code>myVar</code> variable'');'

Challenge Seed

function myLocalScope() {
  'use strict'; // you shouldn't need to edit this line
  
  console.log(myVar);
}
myLocalScope();

// Run and check the console
// myVar is not defined outside of myLocalScope
console.log(myVar);

// Now remove the console log line to pass the test

Before Test

var logOutput = "";
var originalConsole = console
function capture() {
  var nativeLog = console.log;
  console.log = function (message) {
    logOutput = message;
    if(nativeLog.apply) {
      nativeLog.apply(originalConsole, arguments);
    } else {
      var nativeMsg = Array.prototype.slice.apply(arguments).join(' ');
      nativeLog(nativeMsg);
    }
  };
}

function uncapture() {
  console.log = originalConsole.log;
}

After Test

console.info('after the test');

Solution

function myLocalScope() {
  'use strict';
  
  var myVar;
  console.log(myVar);
}
myLocalScope();