CodeBlanks Logo Icon CodeBlanks

var and scope

Learn var's function scope and hoisting.

var and scope

var is JavaScript's old variable declaration keyword. Variables declared with var have function scope; even if they are declared inside a { } block, they are accessible from outside the block.

This can cause unexpected bugs. For example, if you declare var x = 5 inside an if block, x is also visible outside the block.

That is why modern Node.js code prefers let and const.

Function and block scope

Function scope: a variable is visible throughout the function where it is declared. Block scope keeps a variable only inside the { } block where it is declared.

var is function-scoped: a var x declared inside an if block is also visible outside. let and const are block-scoped: they cannot be accessed outside the block.

This is why modern Node.js code prefers let and const; unexpected leaks are prevented.

Practice Show var vs let

Inside an if (true) block, declare let x = 10. Inside the block, call console.log(x). Outside the block, call console.log('done').

Starter code

index.js
// Inside an if (true) block, write let x = 10
// Inside the block, log x
// Outside, log 'done'

Sample solution

index.js
if (true) {
  let x = 10;
  console.log(x);
}
console.log("done");

Expected output

10
done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the scope concepts

Term Meaning
var Function scope
let Block scope (mutable)
const Block scope (fixed)
hoisting Hoisting

2 What is the main problem with var?

  • It is very slow
  • No block scope, has function scope Correct answer
  • It cannot be reassigned
  • It can only hold numbers

Explanation: var is function-scoped and leaks out of blocks.

3 Block scope with let

Question
if (true) {
  ____
  console.log(x);
}
Answer
if (true) {
  let x = 5;
  console.log(x);
}

Explanation: var gives function scope, not block scope.

All lessons in Beginner