Top JavaScript interview code-based questions

Jump to

JavaScript is an undisputed leader in web application development. In the last two decades, the programming language has grown to the extent that 98% of websites use JavaScript.

Technological giants like Google and Facebook use JavaScript to build complex web applications because of the availability of vast open-source frameworks and libraries supporting JavaScript. Given the versatility of the language and its excessive use, any software developer can expect to face JavaScript code-based questions during interviews.

If you’re planning to become a JavaScript developer or interviewing as one, here are the essential code-based JavaScript questions.

1. Explain the output of the following JavaScript code

(function(){

  var a = b = 3;

})();

console.log(“a defined? ” + (typeof a !== ‘undefined’));

console.log(“b defined? ” + (typeof b !== ‘undefined’));

The output of the above code will be:

a defined? false

b defined? true

Explanation: Most JavaScript developers expect that the output of this code will be undefined because both a and b are defined within the enclosing scope of the function. Since the code begins with the var keyword, they assume ‘typeof a’ and ‘typeof b’ to be undefined.

That’s a mistake. It is because the statement var a = b = 3; is not shorthand for:

var b = 3;

var a = b;

But, it is shorthand for:

b = 3;

var a = b;

As a result, b ends up in a global variable available outside the scope of the enclosing function.

However, note that, in strict mode, the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined.

2. What will be the output of the code below, and why?

var myObject = {

   foo: “bar”,

   func: function() {

     var self = this;

console.log(“outer func: 

this.foo = ” + this.foo);

console.log(“outer func: 

self.foo = ” + self.foo);

     (function() {

console.log(“inner func: 

this.foo = ” + this.foo);

console.log(“inner func: 

self.foo = ” + self.foo);

     }());

   }

};

myObject.func();

The output of the code will be:

outer func: this.foo = bar

outer func: self.foo = bar

inner func: this.foo = undefined

inner func: self.foo = bar

As both this and self refers to myObject in the outer object, they can properly reference and access foo.

Back in the inner function, they no longer refer to myObject, which results in undefined this.foo in the inner function. However, the reference to the local variable self remains in scope and therefore is accessible.

3. Will the following two functions return the same output? Why or why not?

function foo1()

{

  return {

    bar: “hello”

  };

}

function foo2()

{

  return

  {

    bar: “hello”

  };

}

No, these two functions will not return the same output.

The following statements:

console.log(“foo1 returns:”);

console.log(foo1());

console.log(“foo2 returns:”);

console.log(foo2());

will return:

foo1 returns:

Object {bar: “hello”}

foo2 returns:

undefined

It is a tricky JavaScript code-based interview question because surprisingly foo2() returns undefined without any error being thrown.

The reason for this outcome is that in JavaScript, semicolons are technically optional. As a result, when the return statement is encountered in foo2(), a; is automatically inserted at the end of the return statement. Hence no error was thrown as the remainder of the code is perfectly valid.

This is why you should always follow the convention of placing an opening curly brace at the end of a code line in JavaScript rather than beginning on a new line. It is not just a stylistic preference but also essential to avoid unexplained bugs.

4. Write a simple JavaScript function (less than 160 characters) that checks whether a string is a palindrome or not. 

Here is the function that will check the input and return True if the string is a palindrome, otherwise, the output will be False.

function isPalindrome(str) {

  str = str.replace(/\W/g, ”).toLowerCase();

  return (str == str.split(”).reverse().join(”));

}

Some console output examples:

console.log(isPalindrome(“level”)); // logs ‘true’

console.log(isPalindrome(“levels”)); // logs ‘false’

console.log(isPalindrome(“A car, a man, a maraca”)); // logs ‘true’

5. Consider the following JavaScript code:

for (var i = 0; i < 5; i++) {

  var btn = document.createElement(‘button’);

btn.appendChild(document.createTextNode(‘Button ‘ + i));

btn.addEventListener(‘click’, function(){ console.log(i); });

document.body.appendChild(btn);

}

What will be logged into the console when the user clicks Button 4 and why?

Also, provide an alternative JavaScript implementation of the same.

No matter what the user clicks on the keyboard, the number 5 will be displayed every time. It is because by the time the onclick method is invoked, irrespective of what button is clicked, the for loop has already been completed and the variable i is assigned a value of 5.

As an alternative, we need to write a function to capture the value of i at each pass when the for loop executes and pass the value into a newly created function object. Here is the alternative code:

for (var i = 0; i < 5; i++) {

  var btn = document.createElement(‘button’);

btn.appendChild(document.createTextNode(‘Button ‘ + i));

btn.addEventListener(‘click’, (function(i) {

   return function() { console.log(i); };

  })(i));

document.body.appendChild(btn);

}

Conclusion 

JavaScript code-based questions can be a bit tricky. It would help if you focused on understanding the basics of the JavaScript components to tackle such interviews. Here are some more technical JavaScript interview questions.

Talent500 is the platform to discover job opportunities with global companies. Join our elite pool of talent, and sign up here.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

You may also like

AWS DevOps Certification

AWS DevOps Certification: Guide, Exam & Benefits

Planning to earn an AWS DevOps Certification? Explore certification paths, exam requirements, key AWS services, CI/CD practices, infrastructure automation, monitoring, and deployment strategies. Discover the skills and preparation approaches needed to validate your expertise in cloud DevOps.

backend technologies

Backend Technologies: Frameworks, Tools & Languages

From programming languages and frameworks to databases, APIs, and cloud platforms, backend technologies power the server-side functionality of modern applications. Explore essential tools, their capabilities, popular use cases, and how they work together to build secure, scalable, and high-performing systems.

Database Replication

Database Replication: Types, Benefits & How It Works

Database Replication helps maintain data availability and reliability by copying data across multiple database servers. Explore replication types, synchronization methods, failover strategies, benefits, and challenges, along with best practices for improving scalability, fault tolerance, and disaster recovery.

Categories
Interested in working with Backend, java, Job Interview Tips ?

These roles are hiring now.

Loading jobs...
Scroll to Top