0
0
Javascriptprogramming~20 mins

Global scope in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Global Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this code involving global and local variables?

Consider the following JavaScript code:

var x = 10;
function test() {
  var x = 20;
  console.log(x);
}
test();
console.log(x);

What will be printed to the console?

Javascript
var x = 10;
function test() {
  var x = 20;
  console.log(x);
}
test();
console.log(x);
A20\n10
B10\n20
C20\n20
D10\n10
Attempts:
2 left
πŸ’‘ Hint

Remember that variables declared inside a function have local scope and do not affect the global variable.

❓ Predict Output
intermediate
2:00remaining
What happens when you omit var/let/const in a function?

Look at this code:

function setValue() {
  y = 5;
}
setValue();
console.log(y);

What will be the output?

Javascript
function setValue() {
  y = 5;
}
setValue();
console.log(y);
ATypeError
BReferenceError: y is not defined
Cundefined
D5
Attempts:
2 left
πŸ’‘ Hint

Variables assigned without var, let, or const inside functions become global.

🧠 Conceptual
advanced
2:00remaining
Which statement about global scope is true?

Choose the correct statement about global scope in JavaScript.

AVariables declared with <code>let</code> at the top level become properties of the global object.
BVariables declared with <code>var</code> at the top level become properties of the global object.
CUsing <code>const</code> inside a function creates a global variable.
DFunctions declared inside blocks are always global.
Attempts:
2 left
πŸ’‘ Hint

Think about how var and let differ in global scope.

❓ Predict Output
advanced
2:00remaining
What is the output when modifying a global variable inside a function?

Consider this code:

let count = 0;
function increment() {
  count++;
}
increment();
console.log(count);

What will be printed?

Javascript
let count = 0;
function increment() {
  count++;
}
increment();
console.log(count);
AReferenceError
BNaN
C1
D0
Attempts:
2 left
πŸ’‘ Hint

Variables declared with let at global scope can be accessed and changed inside functions.

❓ Predict Output
expert
3:00remaining
What is the output of this code with nested scopes and global variable?

Analyze this code snippet:

var a = 1;
function outer() {
  var a = 2;
  function inner() {
    a = 3;
  }
  inner();
  console.log(a);
}
outer();
console.log(a);

What will be printed to the console?

Javascript
var a = 1;
function outer() {
  var a = 2;
  function inner() {
    a = 3;
  }
  inner();
  console.log(a);
}
outer();
console.log(a);
A3\n1
B3\n3
C2\n3
D2\n1
Attempts:
2 left
πŸ’‘ Hint

Remember that inner changes the a in outer's scope, not the global a.