Javascript Tricky Questions Asked In Interview

JavaScript, with its dynamic nature and versatile capabilities, often presents developers with intriguing challenges and unexpected behaviors. Test your Javascript Knowledge, let me know in comment box if you knew answers.

Javascript


1. The Infamous Equality Conundrum

console.log(1 == '1'); // true
console.log(1 === '1'); // false

JavaScript's loose equality operator (==) coerces operands to the same type before comparison, leading to unexpected results. In the first comparison, '1' is coerced to a number, resulting in true. However, the strict equality operator (===) checks both value and type, hence the second comparison returns false.

2. Hoisting

var x = 5;
(function() {
  console.log("x:", x);
  var x = 10;
})();
Contrary to intuition, the output is undefined. This is due to hoisting, a JavaScript behavior where variable declarations are moved to the top of their containing scope during compilation. Thus, var x inside the function is hoisted, shadowing the outer x but not yet assigned a value at the time of logging.

3. The Mysterious this Keyword

const obj = {
  name: 'John',
  greet: function() {
    console.log("Hello, " + this.name);
  }
};

const greet = obj.greet;
greet(); // "Hello, undefined"
When greet is invoked, this no longer points to obj, but to the global object (window in the browser, global in Node.js). Since name is not defined in the global context, it returns undefined.

4. Clousure

let obj = {
  "name": "John",
  "greet": function(){
     return () => {
         console.log("Hello, " + this.name);
     }
   }
}

let greet = obj.greet();
greet(); // "Hello, John"
In this scenario, greet is a function returned by the greet method of obj. However, notice how greet is defined: it's an arrow function. Arrow functions in JavaScript capture the this value lexically from their surrounding scope. Therefore, even when greet is invoked outside of its original context (inside obj), it still retains access to the this context of obj. As a result, this.name within the arrow function refers to the name property of obj, yielding the expected output "Hello, John".


Comment down your tricky questions.

Post a Comment