LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 25 of 25

JavaScript Output Questions Questions and Concepts

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

Introduction & Syntax

JavaScript Output Questions · Study material

"What is the output of this code?" is the most common JavaScript question in campus placement tests, online assessments (HackerRank, AMCAT, Mettl, CoCubes) and technical interviews. These puzzles are short, but each one hides a rule: how + and == convert types, what is hoisted, which this a function sees, what a closure remembers, and in what order promises and timers run. This topic collects the rules on one page, then gives you 60 brand-new questions – 15 rapid-fire MCQs and 45 predict-the-output programs in three sets (types and operators; scope, closures and this; promises and the event loop). Every answer is the real output from Node.js.

Rule 1: the + operator and type coercion

+ concatenates as soon as either operand is (or becomes) a string, and it evaluates left to right. Every other arithmetic operator converts its operands to numbers. Objects and arrays are first turned into primitives (arrays become their comma-joined string).

// + : if either side becomes a string, it concatenates; otherwise it adds numbers
console.log(1 + 2 + "3");        // (1 + 2) + "3"
console.log("1" + 2 + 3);        // ("1" + 2) + 3
console.log([1, 2] + [3]);       // arrays become strings: "1,2" + "3"
console.log(true + 1, null + 1, undefined + 1);
// - * / % always convert to numbers
console.log("10" - "4", "6" * "2", "abc" - 1);

Output

33
123
1,23
2 1 NaN
6 12 NaN

Rule 2: == vs ===

=== compares without conversion. == converts: null and undefined equal only each other, booleans become numbers, objects become primitives. NaN is not equal to anything, including itself – use Number.isNaN or Object.is.

console.log(0 == "", 0 == "0", "" == "0");          // == converts; not transitive!
console.log(null == undefined, null == 0, null >= 0);
console.log(NaN === NaN, Object.is(NaN, NaN), [NaN].includes(NaN));
console.log([] == false, [0] == false, [1] == true);

Output

true true false
true false true
false true true
true true true

Rule 3: hoisting and the temporal dead zone

Function declarations are hoisted with their body; var is hoisted and set to undefined; let, const and class are hoisted but unusable (TDZ) until their line runs.

console.log(typeof greet, typeof later);   // function declarations are hoisted whole; var only as undefined
function greet() { return "hi"; }
var later = () => "later";

try {
  console.log(blockScoped);                // let/const: hoisted but in the TDZ
} catch (e) {
  console.log(e.name);
}
let blockScoped = 1;

Output

function undefined
ReferenceError

Rule 4: what this refers to

this depends on how a function is called: obj.method() → obj; a plain call → undefined in strict code (the global object in sloppy scripts); call/apply/bind → the value given (bind wins and cannot be re-bound); new → the new object. Arrow functions have no own this – they use the surrounding one.

const course = {
  title: "JS Mastery",
  regular() { return this?.title; },
  arrow: () => typeof this,                      // arrows use the surrounding this (module top level: undefined)
  later() { return [1].map(() => this.title)[0]; },  // arrow inside a method: the method's this
};
const detached = course.regular;
console.log(course.regular(), detached(), course.arrow(), course.later());
console.log(detached.call({ title: "via call" }), course.regular.bind({ title: "bound" })());

Output

JS Mastery undefined undefined JS Mastery
via call bound

Rule 5: the event-loop order

Synchronous code first (including promise executors and async functions up to their first await), then all microtasks (then/catch/finally, await continuations), then one task (timers), then microtasks again.

console.log("1 sync");
setTimeout(() => console.log("5 timer (task)"), 0);
Promise.resolve().then(() => console.log("3 then (microtask)"));
(async () => {
  console.log("2 async body (sync until await)");
  await null;
  console.log("4 after await (microtask)");
})();

Output

1 sync
2 async body (sync until await)
3 then (microtask)
4 after await (microtask)
5 timer (task)

How to solve output questions

  1. Note the mode: script or module, strict or sloppy – it changes this and undeclared assignments.
  2. Hoist first: list functions, vars (undefined) and TDZ bindings for each scope.
  3. Evaluate expressions left to right, applying coercion rules one operator at a time.
  4. For loops and closures, keep a trace table of every variable.
  5. For async code, keep three columns: output, microtask queue, task queue.
  6. Remember Node's printing: strings inside arrays get quotes, [ 1, 2 ], { a: 1 }.

Common traps

  • typeof null is "object"; typeof NaN is "number"; typeof [] is "object".
  • 0.1 + 0.2 !== 0.3 (binary floating point).
  • [] is truthy, but [] == false is true.
  • sort() without a compare function sorts as strings: [10, 1, 2] → [1, 10, 2].
  • let a = b = 5 creates a global b in sloppy mode.
  • A returned object from a constructor replaces this.
  • Closures remember variables, not values.
  • Returning a promise from then or async adds extra microtask steps.

Frequently asked questions

Are these questions run in strict mode?

The practice questions run as normal (sloppy) scripts on Node.js, like most online tests, unless the code says "use strict". The study examples above run as ES modules, which are always strict.

Why do Node.js and the browser console sometimes print differently?

The values are the same, but the formatting differs (quotes, spacing, collapsed objects). Tests based on Node.js use its console.log format, which these answers follow.

Where can I learn more?

Revise type coercion, the this keyword and the event loop in the JavaScript tutorial, then work through the four exercises below.

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