
JavaScript Interview Questions and Answers for Freshers
alert(" Hello World ") — Output data in an alert box in the browser window
confirm("Hello World ") — Opens up a yes/no dialog and returns true/false depending on user click
console.log("Hello World") — Writes information to the browser console, good for debugging pur
document.write("Hello World") — Write directly to the HTML document
prompt("Remember the like!"") — Creates a dialogue for user input
2.What is the difference between let and varYou can list out the differences in a tabular format
Feature | var | let |
---|---|---|
Availability | Available from the beginning of JavaScript | Introduced as part of ES6 |
Scope | Function scope | Block scope |
Hoisting | Variables will be hoisted | Hoisted but not initialized |
3.What are the possible ways to create objects in JavaScript
There are many ways to create objects in javascript as below
- Object constructor:
- Object's create method:
- Function constructor:
- Function constructor with prototype:
- ES6 Class syntax:
- . Singleton pattern:
The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.
var object = new Object();
The create method of Object creates a new object by passing the prototype object as a parameter
var object = Object.create(null);
Create any function and apply the new operator to create object instances,
function Person(name){ var object = {}; object.name=name; object.age=21; return object; } var object = new Person("coderstar);
This is similar to function constructor but it uses prototype for their properties and methods,
function Person(){} Person.prototype.name = "coderstar"; var object = new Person()
This is equivalent to an instance created with an object create method with a function prototype and then call that function with an instance and parameters as arguments.
function func {}; new func(x, y, z);(OR)
// Create a new instance using function prototype. var newInstance = Object.create(func.prototype) // Call the function var result = func.call( newInstance, x, y, z ), // If the result is a non-null object then use it otherwise just use the new instance console.log(result && typeof result === 'object' ? result : newInstance );
ES6 introduces class feature to create the objects
class Person { constructor(name) { this.name = name; } } var object = new Person(" Coderstar ");
A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don't accidentally create multiple instances.
var object = new function(){ this.name = "Coderstar"; }
In Javascript, functions are first class objects. First-class functions means when functions in that
language are treated like any other variable.
For example, in such a language, a function
can be passed as an argument to other functions,
can be returned by another function and can be assigned as a value to a variable. For example, in
the below example, handler functions assigned to a listener
const handler = () => console.log (' This is a click handler function '); document.addEventListener ('click', handler);5.What is a first order function
First-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.
const firstOrder = () => console.log ('I am a first order function! ');6. How do you redeclare variables in switch block without an error
If you try to redeclare variables in a switch block then it will cause errors because there is only one block. For example, the below code block throws a syntax error as below,
let counter = 1; switch(x) { case 0: let name; break; case 1: let name; // SyntaxError for redeclaration. break; }
To avoid this error, you can create a nested block inside a case clause and create a new block scoped lexical environment.
let counter = 1; switch(x) { case 0: let name; break; case 1:{ let name; // No SyntaxError for redeclaration. break; } }7.What is Hoisting
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation. Let's take a simple example of variable hoisting,
console.log (message); //output : undefined var message = ' The variable Has been hoisted ';
The above code looks like as below to the interpreter,
var message; console.log(message ); message = ' The variable Has been hoisted ';7.What are classes in ES6
In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below,
function Bike(model,color) { this.model = model; this.color = color; } Bike.prototype.getDetails = function() { return this .model + ' bike has' + this.color + ' color'; };
Whereas ES6 classes can be defined as an alternative
class Bike{ constructor(color, model) { this.color= color; this.model= model; } getDetails() { return this.model + ' bike has' + this.color + ' color'; } }8.What are modules
Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor
9.Why do you need modulesBelow are the list of benefits using modules in javascript ecosystem
- Maintainability
- Reusability
- Namespacing
Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.
11.What is a callback functionA callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. Let's take a simple example of how to use callback function
function callbackFunction(name) { console.log('Hello ' + name); } function outerFunction(callback) { let name = prompt( 'Please enter your name.' ); callback(name); } outerFunction(callbackFunction );12.What are server-sent events
Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This has been used in Facebook/Twitter updates, stock price updates, news feeds etc.
13.What is the purpose of the delete operatorThe delete keyword is used to delete the property as well as its value.
var user= {name: "John", age:20}; delete user. age; console.log(user); // {name: "John"}14.What is a strict mode in javascript
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression "use strict"; instructs the browser to use the javascript code in the Strict mode.
14.How do you access history in javascriptThe window.history object contains the browser's history. You can load previous and next URLs in the history using back() and next() methods.
function goBack() { window.history.back() } function goForward() { window.history.forward() }15.What is isNaN
The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false.
isNaN( 'Hello' ) //true isNaN('100' ) //false16.What is the use of preventDefault method
The preventDefault() method cancels the event if it is cancelable, meaning that the default action or behaviour that belongs to the event will not occur. For example, prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyperlink are some common use cases.
document.getElementById( "link" ).addEventListener( "click", function(event){ event.preventDefault(); });
Note:Remember that not all events are cancelable.
17.What is the use of setTimeoutThe setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds. For example, let's log a message after 2 seconds using setTimeout method,
setTimeout(function(){ console.log( "Good morning" ); }, 2000);18.What is the use of setInterval
The setInterval() method is used to call a function or evaluate an expression at specified intervals (in milliseconds). For example, let's log a message after 2 seconds using setInterval method,
setInterval(function(){ console.log("Good morning"); }, 2000);