JavaScript Interview Questions - Set 5

JavaScript Interview Questions

← Prev

This page consists of JavaScript interview questions and answers.

Q1: What are global variables in JavaScript?

Global variables are the variables that are available throughout the code.

If we create a variable without the var keyword then it becomes a global variable.

Q2: What is the this keyword in JavaScript?

The this keyword is used to refer to the object from where it is called.

Q3: What is the use of "use strict"; in JavaScript?

The "use strict"; in JavaScript is used to execute the code in strict mode.

So, for example in strict mode we can't use undeclared variables.

"use strict"; is a literal expression and not a statement and is ignored by older JavaScript versions.

Q4: What is setTimeout in JavaScript?

The setTimeout function executes a function after a given delay.

In the following example we will get "Hello World" message in the browser console after 5000ms (milliseconds) delay.

setTimeout(function() {
  console.log('Hello World');
}, 5000)

Q5: What is setInterval in JavaScript?

The setInterval function is used to execute a function repeatedly after a given delay. The execution stops only when we stop the timer using the clearInterval function.

In the following example we will get "Hello World" after every 3 seconds (3000ms) for 5 times.

var count = 0;
var t = setInterval(function() {
  console.log('Hello World');
  count++;
  if (count === 5) {
    clearInterval(t);
    console.log('End');
  }
}, 3000);

Q6: What is the difference between View state and Session state?

View state is specific to a page in a session. Whereas, Session state is specific to a user or browser session and is accessible from all pages.

Q7: What are the different loop structure available in JavaScript?

Following are the loop structure available in JavaScript.

  • while
  • do-while
  • for

Q8: Write JavaScript code to print individual characters of a given string 'Hello World' in the browser console.

var str = 'Hello World';
for (var i = 0, len = str.length; i < len; i++) {
  console.log(str[i]);
}

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

console.log(typeof typeof null);

The output is "string".

Explanation:

The typeof null will give us "object". This is in double quotes so, it is a string.

Next, the typeof "object" will give us "string".

Hence, the final answer is "string".

Q10: What is the use of Void(0) in JavaScript?

Void(0) is used to prevent a page from refreshing when used with hyperlinks.

In the following example we have a hyperlink which when clicked will not refresh the page or jump to the top of the page.

<a href="javascript:void(0);" ondblclick="alert('Hello World')">Double click me</a>
← Prev

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

We use cookies to enhance user experience. By continuing to browse this site you agree to our use of cookies. More info

Got it!