--- id: 56533eb9ac21ba0edf2244be title: Global Scope and Functions challengeType: 1 videoUrl: https://scrimba.com/c/cQM7mCN forumTopicId: 18193 localeTitle: Глобальная область и функции --- ## Description
В JavaScript область видимости относится к видимости переменных. Переменные, определенные вне функционального блока, имеют глобальную область. Это означает, что их можно увидеть везде в вашем JavaScript-коде. Переменные, которые используются без ключевого слова var , автоматически создаются в global области. Это может привести к непредвиденным последствиям в другом месте вашего кода или при повторном запуске функции. Вы всегда должны объявлять переменные с помощью var .
## Instructions
Используя var , объявляйте global переменную myGlobal вне любой функции. Инициализируйте его со значением 10 . Внутри функции fun1 присвойте 5 oopsGlobal без использования ключевого слова var .
## Tests
```yml tests: - text: myGlobal should be defined testString: assert(typeof myGlobal != "undefined"); - text: myGlobal should have a value of 10 testString: assert(myGlobal === 10); - text: myGlobal should be declared using the var keyword testString: assert(/var\s+myGlobal/.test(code)); - text: oopsGlobal should be a global variable and have a value of 5 testString: assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5); ```
## Challenge Seed
```js // Declare your variable here 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 Tests
```js 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 Tests
```js fun1(); fun2(); uncapture(); (function() { return logOutput || "console.log never called"; })(); ```
## Solution
```js // Declare your variable here var myGlobal = 10; function fun1() { // Assign 5 to oopsGlobal Here oopsGlobal = 5; } // 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); } ```