0
0
Javascriptprogramming~10 mins

Block scope in Javascript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a block-scoped variable.

Javascript
function test() {
  [1] message = 'Hello';
  console.log(message);
}
Drag options to blanks, or click blank then click option'
Avar
Blet
Cconst
Dfunction
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'var' instead of 'let' causes the variable to be function-scoped.
Using 'function' keyword incorrectly to declare a variable.
2fill in blank
medium

Complete the code to correctly access the block-scoped variable inside the block.

Javascript
if (true) {
  let [1] = 5;
  console.log(num);
}
Drag options to blanks, or click blank then click option'
Anum
Bnumber
Cvalue
Dcount
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a different variable name than declared causes a ReferenceError.
Trying to access the variable outside the block.
3fill in blank
hard

Fix the error by choosing the correct keyword to declare a block-scoped constant.

Javascript
if (true) {
  [1] PI = 3.14;
  console.log(PI);
}
Drag options to blanks, or click blank then click option'
Aconst
Blet
Cvar
Dfunction
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'var' or 'let' when the value should be constant.
Using 'function' keyword incorrectly.
4fill in blank
hard

Fill both blanks to create a block-scoped variable and check its scope.

Javascript
function checkScope() {
  [1] x = 10;
  if (true) {
    [2] x = 20;
    console.log(x);
  }
  console.log(x);
}
Drag options to blanks, or click blank then click option'
Alet
Bvar
Cconst
Dfunction
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using var for both variables causes the inner assignment to overwrite the outer.
Using const incorrectly when reassignment is needed.
5fill in blank
hard

Fill all three blanks to create a block-scoped variable, a constant, and print their values.

Javascript
function demo() {
  [1] name = 'Alice';
  if (true) {
    [2] greeting = 'Hello';
    [3](greeting + ', ' + name);
  }
}
Drag options to blanks, or click blank then click option'
Alet
Bconst
Cconsole.log
Dvar
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using const for variables that are reassigned.
Forgetting to use console.log to print.