Javascript 【tricky】💡interview output questions (Part 1)

codecraftjs

Code Craft-Fun with Javascript

Posted on June 17, 2023

Javascript 【tricky】💡interview output questions (Part 1)

What is the output for each code mentioned below and Why ?

Add your solutions with explanation in the comment section.

Question 1

(function(){
  var variable1 = variable2 = 3;
})();
console.log("variable1 defined? " + (typeof variable1 !== 'undefined'));
console.log("variable2 defined? " + (typeof variable2 !== 'undefined'));
Enter fullscreen mode Exit fullscreen mode

Question 2

var myObject = {
    value: 1,
    printVal: function() {
        var self = this;
        console.log("printVal:  this.value = " + this.value);
        console.log("printVal:  self.value = " + self.value);
        (function() {
            console.log("inner printVal:  this.value = " + this.value);
            console.log("inner printVal:  self.value = " + self.value);
        }());
        } };
myObject.printVal();
Enter fullscreen mode Exit fullscreen mode

Question 3

console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
Enter fullscreen mode Exit fullscreen mode

Question 4

for (var i = 0; i < 5; i++) {
  setTimeout(() => console.log(i), 1000 * i);
}
Enter fullscreen mode Exit fullscreen mode

Question 5

var arr1 = "john".split("");
var arr2 = arr1.reverse();

arr2.splice(arr2.length - 1, 1);

console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));
console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
codecraftjs
Code Craft-Fun with Javascript

Posted on June 17, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related