--- id: 56533eb9ac21ba0edf2244be title: Global Scope and Functions localeTitle: Ámbito global y funciones challengeType: 1 --- ## Description
En JavaScript, el alcance se refiere a la visibilidad de las variables. Las variables que se definen fuera de un bloque de función tienen alcance global . Esto significa que pueden verse en todas partes en su código JavaScript. Las variables que se utilizan sin la palabra clave var se crean automáticamente en el ámbito global . Esto puede crear consecuencias no deseadas en otra parte de su código o al ejecutar una función nuevamente. Siempre debes declarar tus variables con var .
## Instructions
Usando var , declare una variable global myGlobal fuera de cualquier función. Inicialízalo con un valor de 10 . Dentro de la función fun1 , asigne 5 a oopsGlobal sin usar la palabra clave var .
## Tests
```yml tests: - text: myGlobal debe ser definido testString: 'assert(typeof myGlobal != "undefined", "myGlobal should be defined");' - text: myGlobal debe tener un valor de 10 testString: 'assert(myGlobal === 10, "myGlobal should have a value of 10");' - text: myGlobal debe declararse usando la palabra clave var testString: 'assert(/var\s+myGlobal/.test(code), "myGlobal should be declared using the var keyword");' - text: oopsGlobal debe ser una variable global y tener un valor de 5 testString: 'assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5, "oopsGlobal should be a global variable and have a value of 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 Test
```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 Test
```js console.info('after the test'); ```
## 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); } ```