This includes certificates (where it does nothing), but does not include any translations.
3.1 KiB
3.1 KiB
id, title, challengeType, isHidden, videoUrl, forumTopicId
id | title | challengeType | isHidden | videoUrl | forumTopicId |
---|---|---|---|---|---|
56533eb9ac21ba0edf2244be | Global Scope and Functions | 1 | false | https://scrimba.com/c/cQM7mCN | 18193 |
Description
var
keyword are automatically created in the global
scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var
.
Instructions
var
, declare a global variable named myGlobal
outside of any function. Initialize it with a value of 10
.
Inside function fun1
, assign 5
to oopsGlobal
without using the var
keyword.
Tests
tests:
- text: <code>myGlobal</code> should be defined
testString: assert(typeof myGlobal != "undefined");
- text: <code>myGlobal</code> should have a value of <code>10</code>
testString: assert(myGlobal === 10);
- text: <code>myGlobal</code> should be declared using the <code>var</code> keyword
testString: assert(/var\s+myGlobal/.test(code));
- text: <code>oopsGlobal</code> should be a global variable and have a value of <code>5</code>
testString: assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5);
Challenge Seed
// Declare the myGlobal variable below this line
function fun1() {
// Assign 5 to oopsGlobal Here
}
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
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;
}
var oopsGlobal;
capture();
After Test
fun1();
fun2();
uncapture();
(function() { return logOutput || "console.log never called"; })();
Solution
var myGlobal = 10;
function fun1() {
oopsGlobal = 5;
}
function fun2() {
var output = "";
if(typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if(typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}