JavaScript Interview Questions - Set 4

JavaScript Interview Questions

This page consists of JavaScript interview questions and answers.

Q1: Write the difference between undefined and not defined in JavaScript?

When we declare a variable but do not assign any value to it then by default it is assigned the undefined value.

The following code will print undefined.

var x;
console.log(x);

If we try to access a variable that is not declared then we get the not defined error and the script stops to execute further.

The following code will give us not defined error.

console.log(y);

Output:

Uncaught ReferenceError: y is not defined

Q2: What are the primitive data types in JavaScript?

Following are the primitive data types in JavaScript.

  • Number
  • String
  • Boolean
  • Undefined
  • Null

Q3: What are the non-primitive data types in JavaScript?

Following are the non-primitive data types in JavaScript.

  • Array
  • Object

Q4: What is the output of the following JavaScript code?

for (var i = 0; i < 3; i++) {
  var str = "";
  for (var j = 0; j <= i; j++) {
    str += j + " ";
  }
  console.log(str);
}

The output for the above code is the following.

0
0 1
0 1 2

Q5: What is the output of the following JavaScript code?

var user = {
  name: 'Yusuf Shakeel',
  score: 10,
  username: 'yusufshakeel'
};

var score = user.score;

score += 10;

user['score'] = score;

console.log(user);

The above code will give us the following result.

{
  name: 'Yusuf Shakeel',
  score: 20,
  username: 'yusufshakeel'
}

Q6: What is the output of the following JavaScript code?

function foo(x) {
  var y = x + 10;
  function bar(y) {
    console.log(x);
    console.log(y);
  }
  bar(y);
}

foo(10);

The output for the above code is.

10
20

Q7: What is the output of the following JavaScript code?

function bar(x) {
  return function foo() {
    console.log(x);
  }
}

var x = bar(10);
x();

The answer for the above code is 10.

Q8: What value is returned by a function having no return statement when it is called in JavaScript?

The default return value is undefined for a function if no return statement is present.

Q9: What is the output of the following JavaScript code?

var str = "Hello".split('').reverse().join('');
console.log(str);

The output of the above code is "olleH".

Q10: What is the output of the following JavaScript code?

var movie = (function() {
  return {
    name: 'Avengers: Infinity War',
    getName: function() {
      return this.name;
    }
  };
}());
console.log(movie.getName());

The above code will print "Avengers: Infinity War".

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT