Skip to main content

Command Palette

Search for a command to run...

99 JavaScript Tricky Questions | Must Have

Published
12 min readView as Markdown
R

I am a MERN stack developer. Here to learn and share my knowledge to help other to grow.

Certainly! Here are 10 tricky JavaScript questions:

  1. Variable Declaration and Initialization:

     let x = 5, y = 10;
     console.log(x + y);
    

    What is the output, and why?

  2. Truthy or Falsy:

     console.log([] == false);
    

    What is the output, and why?

  3. Scope and Variable Hoisting:

     var a = 10;
     (function () {
        console.log(a);
        var a = 20;
     })();
    

    What is the output, and why?

  4. Type Coercion:

     console.log("5" - 2);
    

    What is the output, and why?

  5. Closures:

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

    What is the output, and why?

  6. Prototype Chain:

     function Person() {}
     Person.prototype.walk = function() { console.log("walking"); };
     var john = new Person();
     john.walk();
    

    What is the output, and why?

  7. Async/Await:

     async function foo() {
        console.log(1);
        await Promise.resolve();
        console.log(2);
     }
     foo();
     console.log(3);
    

    What is the output, and why?

  8. this in Arrow Functions:

     const obj = {
        value: 100,
        getValue: () => console.log(this.value)
     };
     obj.getValue();
    

    What is the output, and why?

  9. Strict Mode:

     "use strict";
     function strictModeExample() {
        undeclaredVar = 10;
        console.log(undeclaredVar);
     }
     strictModeExample();
    

    What is the output, and why?

  10. Event Bubbling:

    <div id="parent">
       <button id="child">Click me</button>
    </div>
    <script>
       document.getElementById('parent').addEventListener('click', function() {
          console.log('Parent clicked');
       });
       document.getElementById('child').addEventListener('click', function(e) {
          console.log('Child clicked');
          e.stopPropagation();
       });
    </script>
    

    What happens when you click the button, and why?

    Certainly! Here are 20 more tricky JavaScript questions:

    1. Global Object:

      var a = 1;
      console.log(window.a === a);
      

      What is the output, and why?

    2. NaN Comparison:

      console.log(NaN === NaN);
      

      What is the output, and why?

    3. Array Equality:

      console.log([1] == [1]);
      

      What is the output, and why?

    4. Hoisting in Functions:

      function example() {
        console.log(bar);
        var bar = 10;
        console.log(bar);
      }
      example();
      

      What is the output, and why?

    5. Default Parameter Value:

      function greet(name = "Guest") {
        console.log("Hello, " + name);
      }
      greet();
      greet("John");
      

      What is the output, and why?

    6. typeof Operator:

      console.log(typeof null);
      console.log(typeof undefined);
      

      What is the output, and why?

    7. == vs ===:

      console.log(1 == "1");
      console.log(1 === "1");
      

      What is the output for each line, and why?

    8. instanceof Operator:

      function Car() {}
      const myCar = new Car();
      console.log(myCar instanceof Car);
      

      What is the output, and why?

    9. Object Property Access:

      var obj = { x: 10, y: 20 };
      var { x, y } = obj;
      console.log(x, y);
      

      What is the output, and why?

    10. setTimeout and this:

      const obj = {
        count: 0,
        increment: function() {
          setTimeout(function() {
            console.log(this.count);
          }, 1000);
        }
      };
      obj.increment();
      

      What is the output, and why?

    11. Function Declarations vs Expressions:

      console.log(foo());
      console.log(bar());
      function foo() { return "Hello, I'm foo!"; }
      var bar = function() { return "Hello, I'm bar!"; };
      

      What is the output, and why?

    12. Promise Chaining:

      Promise.resolve(1)
        .then((res) => {
          console.log(res);
          return 2;
        })
        .catch((err) => console.error(err))
        .then((res) => console.log(res));
      

      What is the output, and why?

    13. delete Operator:

      const obj = { x: 10, y: 20 };
      delete obj.x;
      console.log(obj.x);
      

      What is the output, and why?

    14. Template Literals:

      const name = "John";
      const age = 30;
      console.log(`My name is ${name} and I am ${age} years old.`);
      

      What is the output, and why?

    15. Object.keys and Property Order:

      const obj = { a: 1, b: 2, c: 3 };
      console.log(Object.keys(obj));
      

      What is the output, and why?

    16. Function Execution Context:

      const a = 10;
      function example() {
        console.log(a);
        const a = 20;
      }
      example();
      

      What is the output, and why?

    17. Array.prototype.map:

      const arr = [1, 2, 3];
      const result = arr.map(function(value) {
        return value * 2;
      });
      console.log(result);
      

      What is the output, and why?

    18. JSON.stringify:

      const obj = { x: 10, y: undefined, z: function() {} };
      console.log(JSON.stringify(obj));
      

      What is the output, and why?

    19. Regular Expressions:

      const regex = /ab+c/;
      const str = "abbc";
      console.log(regex.test(str));
      

      What is the output, and why?

    20. parseInt Function:

      console.log(parseInt("10.5"));
      

      What is the output, and why?

      1. Function.prototype.bind:

        const obj1 = { x: 10 };
        const obj2 = { x: 20 };
        function getX() {
          return this.x;
        }
        const boundGetX1 = getX.bind(obj1);
        const boundGetX2 = getX.bind(obj2);
        console.log(boundGetX1(), boundGetX2());
        

        What is the output, and why?

      2. Array.isArray:

        console.log(Array.isArray([]));
        console.log(Array.isArray({}));
        

        What is the output, and why?

      3. Arrow Functions and this:

        const obj = {
          count: 0,
          increment: function() {
            setTimeout(() => {
              console.log(this.count);
            }, 1000);
          }
        };
        obj.increment();
        

        What is the output, and why?

      4. Map Object Keys:

        const myMap = new Map();
        const key1 = { a: 1 };
        const key2 = { b: 2 };
        myMap.set(key1, 'value1');
        myMap.set(key2, 'value2');
        console.log(myMap.get(key1));
        

        What is the output, and why?

      5. Event Delegation:

        <ul id="list">
          <li>Item 1</li>
          <li>Item 2</li>
          <li>Item 3</li>
        </ul>
        <script>
          document.getElementById('list').addEventListener('click', function(event) {
            console.log(event.target.innerText);
          });
        </script>
        

        What happens when you click on an item, and why?

      6. Object.create:

        const person = {
          greet: function() {
            console.log('Hello!');
          }
        };
        const john = Object.create(person);
        john.name = 'John';
        john.greet();
        

        What is the output, and why?

      7. Number Object:

        console.log(typeof 42);
        console.log(typeof new Number(42));
        

        What is the output, and why?

      8. IIFE (Immediately Invoked Function Expression):

        (function() {
          var a = b = 5;
        })();
        console.log(b);
        console.log(a);
        

        What is the output, and why?

      9. arguments Object:

        function sum() {
          console.log(arguments.length);
        }
        sum(1, 2, 3);
        

        What is the output, and why?

      10. setTimeout and this in Non-Arrow Function:

        const obj = {
          count: 0,
          increment: function() {
            setTimeout(function() {
              console.log(this.count);
            }.bind(this), 1000);
          }
        };
        obj.increment();
        

        What is the output, and why?

      11. instanceof and Inheritance:

        function Animal() {}
        function Dog() {}
        Dog.prototype = Object.create(Animal.prototype);
        const myDog = new Dog();
        console.log(myDog instanceof Dog);
        console.log(myDog instanceof Animal);
        

        What is the output, and why?

      12. Multiple catch Blocks:

        try {
          throw new Error('Error occurred');
        } catch (e) {
          console.log('Catch block 1:', e.message);
        } catch (e) {
          console.log('Catch block 2:', e.message);
        }
        

        What is the output, and why?

      13. WeakMap and Garbage Collection:

        let obj = {};
        const weakMap = new WeakMap();
        weakMap.set(obj, 'value');
        obj = null;
        console.log(weakMap.get(obj));
        

        What is the output, and why?

      14. Array.prototype.reduce:

        const numbers = [1, 2, 3];
        const sum = numbers.reduce(function(acc, num) {
          return acc + num;
        }, 0);
        console.log(sum);
        

        What is the output, and why?

      15. Promise.all:

        const promise1 = Promise.resolve(1);
        const promise2 = new Promise((resolve) => setTimeout(() => resolve(2), 1000));
        const promise3 = 3;
        Promise.all([promise1, promise2, promise3])
          .then((values) => console.log(values))
          .catch((err) => console.error(err));
        

        What is the output, and why?

      16. for...of Loop:

        const iterable = [1, 2, 3];
        for (let value of iterable) {
          console.log(value);
        }
        

        What is the output, and why?

      17. NaN and Equality:

        console.log(NaN == NaN);
        console.log(NaN === NaN);
        

        What is the output for each line, and why?

      18. Global Variables and window Object:

        var globalVar = 5;
        console.log(window.globalVar === globalVar);
        

        What is the output, and why?

      19. Closure and setTimeout:

        for (var i = 0; i < 5; i++) {
          setTimeout(function() {
            console.log(i);
          }, 1000);
        }
        

        What is the output, and why?

      20. Generator Functions:

        function* generatorFunction() {
          yield 1;
          yield 2;
          yield 3;
        }
        const generator = generatorFunction();
        console.log(generator.next().value);
        console.log(generator.next().value);
        

        What is the output, and why?

        1. Array.prototype.slice:

          const array = [1, 2, 3, 4, 5];
          const newArray = array.slice(2);
          console.log(newArray);
          

          What is the output, and why?

        2. null and typeof:

          console.log(typeof null);
          

          What is the output, and why?

        3. Object.freeze:

          const obj = { prop: 42 };
          Object.freeze(obj);
          obj.prop = 10;
          console.log(obj.prop);
          

          What is the output, and why?

        4. Event Bubbling and Event Capturing:

          <div id="parent">
            <button id="child">Click me</button>
          </div>
          <script>
            document.getElementById('parent').addEventListener('click', function() {
              console.log('Parent clicked');
            }, true);
            document.getElementById('child').addEventListener('click', function() {
              console.log('Child clicked');
            }, true);
          </script>
          

          What is the order of log messages when you click the button, and why?

        5. Array.prototype.splice:

          const array = [1, 2, 3, 4, 5];
          const removed = array.splice(2, 2);
          console.log(array, removed);
          

          What is the output, and why?

        6. Function Constructor:

          const func = new Function('return 10 + 5');
          console.log(func());
          

          What is the output, and why?

        7. Object Destructuring:

          const { x, y } = { x: 10, y: 20 };
          console.log(x, y);
          

          What is the output, and why?

        8. Array.prototype.filter:

          const numbers = [1, 2, 3, 4, 5];
          const filtered = numbers.filter(function(num) {
            return num % 2 === 0;
          });
          console.log(filtered);
          

          What is the output, and why?

        9. arguments Object and Arrow Function:

          const sum = () => {
            console.log(arguments.length);
          };
          sum(1, 2, 3);
          

          What is the output, and why?

        10. Object.keys and Inherited Properties:

          function Animal() {}
          Animal.prototype.legs = 4;
          const dog = new Animal();
          dog.bark = function() { console.log('Woof!'); };
          console.log(Object.keys(dog));
          

          What is the output, and why?

        11. Object.defineProperty:

          const obj = {};
          Object.defineProperty(obj, 'x', { value: 42, writable: false });
          obj.x = 10;
          console.log(obj.x);
          

          What is the output, and why?

        12. Unicode Escape Sequences:

          console.log('\u0061');
          console.log('\u{1F602}');
          

          What is the output, and why?

        13. Array.prototype.concat:

          const arr1 = [1, 2, 3];
          const arr2 = [4, 5, 6];
          const result = arr1.concat(arr2);
          console.log(result);
          

          What is the output, and why?

        14. JSON.parse with Reviver Function:

          const jsonString = '{"name":"John","age":30,"city":"New York"}';
          const obj = JSON.parse(jsonString, function(key, value) {
            if (key === 'age') return value + 5;
            return value;
          });
          console.log(obj);
          

          What is the output, and why?

        15. String.prototype.replace with Regular Expression:

          const str = 'apple orange apple banana';
          const result = str.replace(/apple/g, 'fruit');
          console.log(result);
          

          What is the output, and why?

        16. Object.prototype.toString:

          const obj = {};
          console.log(Object.prototype.toString.call(obj));
          

          What is the output, and why?

        17. Object.entries:

          const obj = { a: 1, b: 2, c: 3 };
          const entries = Object.entries(obj);
          console.log(entries);
          

          What is the output, and why?

        18. Array.prototype.map with thisArg:

          const numbers = [1, 2, 3];
          const doubled = numbers.map(function(num) {
            return num * this.multiplier;
          }, { multiplier: 2 });
          console.log(doubled);
          

          What is the output, and why?

        19. typeof Operator and Symbol:

          const sym = Symbol('mySymbol');
          console.log(typeof sym);
          

          What is the output, and why?

        20. Object.prototype.hasOwnProperty:

          const obj = { a: 1, b: 2 };
          console.log(obj.hasOwnProperty('a'));
          console.log(obj.hasOwnProperty('toString'));
          

          What is the output, and why?

          1. Array.from:

            const arrayLike = { 0: 'a', 1: 'b', length: 2 };
            const newArray = Array.from(arrayLike);
            console.log(newArray);
            

            What is the output, and why?

          2. RegExp Object and exec:

            const pattern = /a/g;
            const str = 'abcabc';
            let match;
            while ((match = pattern.exec(str)) !== null) {
              console.log(match[0], pattern.lastIndex);
            }
            

            What is the output, and why?

          3. Object.setPrototypeOf:

            const obj1 = { x: 10 };
            const obj2 = { y: 20 };
            Object.setPrototypeOf(obj2, obj1);
            console.log(obj2.x);
            

            What is the output, and why?

          4. Promise.race:

            const promise1 = new Promise(resolve => setTimeout(() => resolve('Promise 1'), 1000));
            const promise2 = new Promise(resolve => setTimeout(() => resolve('Promise 2'), 500));
            Promise.race([promise1, promise2])
              .then(value => console.log(value))
              .catch(err => console.error(err));
            

            What is the output, and why?

          5. Number and Decimal Representation:

            console.log(0.1 + 0.2 === 0.3);
            

            What is the output, and why?

          6. Date Object and Month Index:

            const date = new Date(2022, 0, 31);
            console.log(date.getMonth());
            

            What is the output, and why?

          7. String.prototype.slice:

            const str = 'abcdef';
            const sliced = str.slice(-3, -1);
            console.log(sliced);
            

            What is the output, and why?

          8. this in Arrow Functions and Constructor Functions:

            function Person() {
              this.age = 0;
              setInterval(() => {
                this.age++;
                console.log(this.age);
              }, 1000);
            }
            const person = new Person();
            

            What is the output, and why?

          9. Array.prototype.every:

            const numbers = [2, 4, 6, 8];
            const allEven = numbers.every(function(num) {
              return num % 2 === 0;
            });
            console.log(allEven);
            

            What is the output, and why?

          10. Promise and async/await:

            async function example() {
              return Promise.resolve('Hello');
            }
            example().then(value => console.log(value));
            

            What is the output, and why?

          11. Array.prototype.findIndex:

            const numbers = [10, 20, 30, 40, 50];
            const index = numbers.findIndex(function(num) {
              return num > 25;
            });
            console.log(index);
            

            What is the output, and why?

          12. for...in Loop and Object Properties:

            const obj = { a: 1, b: 2, c: 3 };
            for (const key in obj) {
              console.log(key);
            }
            

            What is the output, and why?

          13. Object.create and Inheritance:

            const parent = { x: 10 };
            const child = Object.create(parent);
            console.log(child.x);
            

            What is the output, and why?

          14. Array.prototype.some:

            const numbers = [1, 3, 5, 7, 9];
            const someEven = numbers.some(function(num) {
              return num % 2 === 0;
            });
            console.log(someEven);
            

            What is the output, and why?

          15. Promise and Promise.resolve:

            const promise = Promise.resolve('Resolved');
            promise.then(value => console.log(value));
            

            What is the output, and why?

          16. String.prototype.indexOf:

            const str = 'hello world';
            console.log(str.indexOf('o'));
            console.log(str.indexOf('o', 5));
            

            What is the output for each line, and why?

          17. Array.isArray and instanceof:

            const arr = [1, 2, 3];
            console.log(Array.isArray(arr));
            console.log(arr instanceof Array);
            

            What is the output for each line, and why?

          18. Date Object and Timezone Offset:

            const date = new Date('2022-03-01T12:00:00Z');
            console.log(date.toISOString());
            

            What is the output, and why?

          19. JSON.stringify with Replacer Function:

            const obj = { a: 1, b: 2, c: 3 };
            const jsonString = JSON.stringify(obj, function(key, value) {
              if (key === 'b') return undefined;
              return value;
            });
            console.log(jsonString);
            

            What is the output, and why?

          20. Array.prototype.reverse:

            const arr = [1, 2, 3, 4, 5];
            const reversed = arr.reverse();
            console.log(reversed);
            

            What is the output, and why?

            1. RegExp and exec with Global Flag:

              const pattern = /a/g;
              const str = 'abcabc';
              let match;
              while ((match = pattern.exec(str)) !== null) {
                console.log(match[0], pattern.lastIndex);
              }
              

              What is the output, and why?

            2. Number and toString:

              const num = 42;
              console.log(num.toString());
              console.log((42).toString());
              

              What is the output for each line, and why?

            3. Object.keys and Property Order:

              const obj = { 10: 'a', 2: 'b', 7: 'c' };
              console.log(Object.keys(obj));
              

              What is the output, and why?

            4. Array.prototype.join:

              const arr = [1, 2, 3];
              const joined = arr.join('-');
              console.log(joined);
              

              What is the output, and why?

            5. Math.max and apply:

              const numbers = [1, 2, 3, 4, 5];
              const max = Math.max.apply(null, numbers);
              console.log(max);
              

              What is the output, and why?

            6. JSON.parse with Reviver Function:

              const jsonString = '{"a":1,"b":2,"c":3}';
              const obj = JSON.parse(jsonString, function(key, value) {
                if (key === 'b') return value * 10;
                return value;
              });
              console.log(obj);
              

              What is the output, and why?

            7. String.prototype.split:

              const str = 'apple,orange,banana';
              const splitArray = str.split(',');
              console.log(splitArray);
              

              What is the output, and why?

            8. Object.defineProperty and Getter/Setter:

              const obj = {};
              let value = 42;
              Object.defineProperty(obj, 'x', {
                get: function() { return value; },
                set: function(newValue) { value = newValue; }
              });
              obj.x = 10;
              console.log(obj.x);
              

              What is the output, and why?

            9. Date Object and Day of the Week:

              const date = new Date('2022-03-01T12:00:00Z');
              console.log(date.getDay());
              

              What is the output, and why?

More from this blog

R

Revive Coding

184 posts

Join Revive Coding on Hashnode for JavaScript, React, Node.js tutorials, tips, and articles. Enhance your skills with 800+ monthly visitors! 🚀 #WebDev #CodingTips