LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 8 of 25

Scope and Hoisting Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Scope and Hoisting · Study material

The module pattern for private state

An IIFE that returns an object is the classic way to keep data private. ES modules and classes with #private fields do the same today, but the pattern appears in many interviews:

// The module pattern: an IIFE returns a public API; everything else stays private in its scope
const Wallet = (function () {
  let balance = 0;                         // private
  const log = [];                          // private
  function record(type, amount) { log.push(`${type} ${amount}`); }
  return {
    add(amount) { balance += amount; record("add", amount); },
    spend(amount) {
      if (amount > balance) return false;
      balance -= amount; record("spend", amount); return true;
    },
    get balance() { return balance; },
    history: () => [...log],               // a copy, so callers cannot change the private log
  };
})();

Wallet.add(500);
console.log(Wallet.spend(200), Wallet.spend(900));
console.log(Wallet.balance, Wallet.history(), typeof balance);

Output

true false
300 [ 'add 500', 'spend 200' ] undefined

Capturing a value now vs reading it later

A closure always reads the variable's current value. To keep the value from the moment of creation, pass it as an argument to a factory:

// A closure reads a variable's CURRENT value when it runs – not the value at creation time
let rate = 5;
const interestLive = (p) => (p * rate) / 100;

// To freeze today's value, pass it in when the function is created
const makeInterest = (fixedRate) => (p) => (p * fixedRate) / 100;
const interestFixed = makeInterest(rate);

rate = 8;
console.log(interestLive(1000), interestFixed(1000));

Output

80 50

Name resolution at a glance

SituationResult
Name found in the current scopethat variable (shadows outer ones)
Found in an enclosing scopethe nearest enclosing variable
Only a global propertythe global property
Not found, readingReferenceError (typeof gives "undefined")
Not found, assigning (sloppy)creates a global property
Not found, assigning (strict/module)ReferenceError
Found but in its TDZReferenceError

Scope checklist

  • Declare every variable, in the smallest scope that needs it.
  • Declare before use – never rely on hoisting.
  • Use modules; avoid adding properties to globalThis.
  • Avoid reusing outer names for local variables.
  • Pass values as parameters instead of reading many outer variables.
  • Keep each function name unique in its scope.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links