Skip to main content

Command Palette

Search for a command to run...

Output-Based JavaScript Questions

JavaScript is full of surprises — especially when it comes to tricky output-based questions. These problems test how deeply you understand concepts!

Published
8 min read
Output-Based JavaScript Questions

Q1. What is the output of 3+2+'7' ?

  • Output:

  • 57

  • In javascript, the addition associativity is from left to right. Due to this initially 3+2 will be evaluated and it will become 5. Now expression becomes 5+”7”

  • In javascript when ever we try to perform addition between a numeric value and a string, javascript will perform type coercion and convert numeric value in to a string.

  • Now expression becomes “5”+ “7” this performs string concatenation andresults in “57”.

Q2. What is the output of below logic ?

  • 
        const a = 1<2<3;
        const b = 1>2>3;
    
        console.log(a,b) //true,false
    

    Output:

    true, false

  • In JavaScript, the comparison operators < and > have left-to-right associativity. So, 1 < 2 < 3 is evaluated as (1 < 2) < 3, which becomes true < 3. When comparing a boolean value (true) with a number (3), JavaScript coerces the boolean to a number, which is 1. So, true < 3 evaluates to 1 < 3, which is true.

  • Similarly, 1 > 2 > 3 is evaluated as (1 > 2) > 3, which becomes false > 3. When comparing a boolean value (false) with a number (3), JavaScript coerces the boolean to a number, which is 0. So, false > 3 evaluates to 0 > 3, which is false.

  • That's why console.log(a, b) prints true false.

Q3. Guess the ouput ?

  • 
        const p = { k: 1, l: 2 };
        const q = { k: 1, l: 2 };
        let isEqual = p==q;
        let isStartEqual = p=== q;
    
        console.log(isEqual, isStartEqual)
    

    OutPut:

  • False,False

  • In JavaScript, when you compare objects using == or ===, you're comparing their references in memory, not their actual contents. Even if two objects have the same properties and values, they are considered unequal unless they reference the exact same object in memory.

  • In your code:

  • isEqual will be false because p and q are two different objects in memory, even though they have the same properties and values.

  • isStartEqual will also be false for the same reason. The === operator checks for strict equality, meaning it not only compares values but also ensures that the objects being compared reference the exact same memory location.

  • So, console.log(isEqual, isStartEqual) will output false false.

Q4. Guess the output ?

  • 
        a) 2+2 = ? 
        b) "2"+"2" = ?
        c) 2+2-2 = ?
        d) "2"+"2"-"2" = ? (tricky remember this)
        e) 4+"2"+2+4+"25"+2+2 ?
    

    Output:

    
        // a) 2+2 = ?
        console.log(2 + 2); // Output: 4
    
        // b) "2"+"2" = ?
        console.log("2" + "2"); // Output: "22" (string concatenation)
    
        // c) 2+2-2 = ?
        console.log(2 + 2 - 2); // Output: 2
    
        // d) "2"+"2"-"2" = ?
        console.log("2" + "2" - "2"); // Output: 20 (string "22" is converted
        to a number, then subtracted by the number 2)
    
        // e) 4+"2"+2+4+"25"+2+2
        console.log(4+"2"+2+4+"25"+2+2); // "42242522"
    

Q5. What is the output of below logic ?

  • 
        let a = 'jscafe'
        a[0] = 'c'
    
        console.log(a)
    

    Output:

  • 'jscafe'

  • Strings are immutable in javascript so we cannot change individual characters by index where as we can create a new string with desired modification as below.

  • a = 'cscafe' // outputs 'cscafe'

Q6. Output of below logic ?

  • 
        var x=10;
        function foo(){
          var x = 5;
          console.log(x)
        }
    
        foo();
        console.log(x)
    

    Output:

    5 and 10

    In JavaScript, this code demonstrates variable scoping. When you declare a variable inside a function using the var keyword, it creates a new variable scoped to that function, which may shadow a variable with the same name in an outer scope. Here's what happens step by step:

  • var x = 10;: Declares a global variable x and initializes it with the value 10.

  • function foo() { ... }: Defines a function named foo.

  • var x = 5;: Inside the function foo, declares a local variable x and initializes it with the value 5. This x is scoped to the function foo and is different from the global x.

  • console.log(x);: Logs the value of the local variable x (which is 5) to the console from within the foo function.

  • foo();: Calls the foo function.

  • console.log(x);: Logs the value of the global variable x (which is still 10) to the console outside the foo function.

Q7. Guess the output ?

  • 
        console.log("Start");
        setTimeout(() => {
        console.log("Timeout");
        });
        Promise.resolve().then(() => console.log("Promise"));
        console.log("End");
    

    Output:

    Start, End,Promise,Timeout.

  • 'Start' is logged first because it's a synchronous operation.

  • Then, 'End' is logged because it's another synchronous operation.

  • 'Promise' is logged because Promise.resolve().then() is a microtask and will be executed before the next tick of the event loop.

  • Finally, 'Timeout' is logged. Even though it's a setTimeout with a delay of 0 milliseconds, it's still a macrotask and will be executed in the next tick of the event loop after all microtasks have been executed.

Q8. This code prints 6 everytime. How to print 1,2,3,4,5,6 ? (Most asked)

  • ```plaintext

function x(){

for(var i=1;i<=5;i++){ setTimeout(()=>{ console.log(i) },i*1000) }

}

x();


    Solution: Either use let or closure

    ```plaintext

      function x() {
        function closur(x) {
          // Set a timeout to log the value of x after x seconds
          setTimeout(() => {
            console.log(x);
          }, x * 1000);
        };

        // Loop from 1 to 5
        for (var i = 1; i <= 5; i++) {
          // Call the closure function with the current value of i
          closur(i);
        }
      }

      // Call the outer function x
      x();

The function we have written defines an inner function closur which is supposed to log the value of x after x seconds. The outer function x calls this inner function for values from 1 to 5.

The code will log the values 1 to 5 after 1 to 5 seconds respectively. Here's an explanation of how it works:

  • The outer function x is called.

  • Inside x, a loop runs from i=1 to i=5.

  • For each iteration of the loop, the inner function closur is called with the current value of i.

  • Inside closur, a setTimeout is set to log the value of x after x seconds.

  • Each call to closur(i) creates a new closure that captures the current value of i and sets a timeout to log that value after i seconds.

  • When you run this code, the output will be:

  • 
        1 (after 1 second)
        2 (after 2 seconds)
        3 (after 3 seconds)
        4 (after 4 seconds)
        5 (after 5 seconds)
    

    This happens because each iteration of the loop calls closur with a different value of i, and each setTimeout inside closur is set to log that value after i seconds.

Q9. What will be the output or below code ?

  • ```plaintext

function x(){ let a = 10; function d(){ console.log(a); } a = 500; return d; }

var z = x(); z();


    Solution: 500 - Closures concept

    In JavaScript, this code demonstrates lexical scoping and closure. Let's break it down:

* function x() { ... }: Defines a function named x.

* let a = 10;: Declares a variable a inside the function x and initializes it with the value 10.

* function d() { ... }: Defines a nested function named d inside the function x.

* console.log(a);: Logs the value of the variable a to the console. Since d is defined within the scope of x, it has access to the variable a defined in x.

* a = 500;: Changes the value of the variable a to 500.

* return d;: Returns the function d from the function x.

* var z = x();: Calls the function x and assigns the returned function d to the variable z.

* z();: Calls the function d through the variable z.

* When you run this code, it will log the value of a at the time of executing d, which is 500, because d retains access to the variable a even after x has finished executing. This behavior is possible due to closure, which allows inner functions to access variables from their outer scope even after the outer function has completed execution.


**Q10. What’s the output of below logic ?**

* ```plaintext

      getData1()
      getData();

      function getData1(){
      console.log("getData11")
      }

      var getData = () => {
      console.log("Hello")
      }

      // Here declaring getData with let causes reference error.
      // ie.,"ReferenceError: Cannot access 'getData' before initialization 
      // As we are declaring with var it throws type error as show below

Output:

Uncaught TypeError: getData is not a function at index.js:2.1

Explanation:

In JavaScript, function declarations are hoisted to the top of their scope, while variable declarations using var are also hoisted but initialized with undefined. Here's what happens in your code:

  • getData1() is a function declaration and getData() is a variable declaration with an arrow function expression assigned to it.

  • When the code runs:`getData1()` is a function declaration, so it's hoisted to the top and can be called anywhere in the code. However, it's not called immediately.

  • getData is declared using var, so it's also hoisted to the top but initialized with undefined.

  • The arrow function assigned to getData is not hoisted because it's assigned to a variable.

  • When getData() is invoked- It will throw an error because getData is undefined, and you cannot call undefined as a function.

  • Therefore, if you try to run the code as is, you'll encounter an error when attempting to call getData().

  • If you want to avoid this error, you should either define getData before calling it or use a function declaration instead of a variable declaration for getData. Here's how you can do it:

  • Modification needed for code:

  • 
        var getData = () => {
        console.log("Hello")
        }
    
        getData1(); // This will log "getData11"
        getData();  // This will log "Hello"