Java Script Interview Major Topics
What happen behind the scene of JavaScript?
Every JavaScript program requires a specific environment to?execute because our computers and other machines do not understand JavaScript syntax. So there are many different engines available out there with the most popular being the?Chrome - v8,Firefox - Spider monkey,Safari - JavaScript core, IE- Chakra
What are the different data types present in JavaScript?
Primitive types : Which used to store single value. Primitive data types are also known as in-built data types. Primitive Data types are predefined?e.g. string , number, null, integer, symbol
Non-primitive types : To store multiple and complex values, non-primitive data types are used. It is also known as derived data types or reference data types. Non-Primitive data types are created by programmer. e.g. object, array
Explain Hoisting in JavaScript.
Hoisting is the default behavior of JavaScript where all the variable and function declarations are moved on top. only declarations not initializations. This work only for var and functions not for let and const. let and const must be init along with declaration.
What are the possible ways to create objects in JavaScript
Object constructor
var object = new Object();
Object's create method
var object = Object.create(null);
Object literal syntax
var object =
name: "Pawan",
age: 34
};{
Function constructor
function Person(name)
this.name = name;
this.age = 21;
}
var object = new Person("Pawan");{
Function constructor with prototype
function Person() {
Person.prototype.name = "Pawan";
var object = new Person();
}
Singleton pattern
var object = new (function () {
this.name = "Pawan";
})();
What is a prototype chain
Prototype chaining?is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language.
Difference between “ == “ and “ === “ operators.
Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ is used to compare both values and types.
JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators take type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,
0 == false // true
0 === false // false
1 == "1" // true
1 === "1" // false
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
[]==[] or []===[] //false, refer different objects in memory
{}=={} or {}==={} //false, refer different objects in memory
Difference between var, let and const keywords in JavaScript
var?declarations are globally scoped or function/locally scoped.
The scope is global when a?var?variable is declared outside a function. This means that any variable that is declared with?var?outside a function block is available for use in the whole window.
var?is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.
Problem with var
There's a weakness that comes with?var. I'll use the example below to explain:
var greeter = "hey hi"
var times = 4;
if (times > 3) {
var greeter = "say Hello instead";
}
console.log(greeter) // "say Hello instead";
So, since?times > 3?returns true,?greeter?is redefined?to?"say Hello instead". While this is not a problem if you knowingly want?greeter?to be redefined, it becomes a problem when you do not realize that a variable?greeter?has already been defined before.
If you have used?greeter?in other parts of your code, you might be surprised at the output you might get. This will likely cause a lot of bugs in your code. This is why?let?and?const?are necessary.
let : A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block.
let can be updated but not re-declared.
Just like?var,?a variable declared with?let?can be updated within its scope. Unlike?var, a?let?variable cannot be re-declared within its scope. So while this will work:
let greeting = "say Hi"
greeting = "say Hello instead";;
Hoisting of let
Just like?var,?let?declarations are hoisted to the top. Unlike?var?which is initialized as?undefined, the?let?keyword is not initialized. So if you try to use a?let?variable before declaration, you'll get a?Reference Error.
const : Variables declared with the?const?maintain constant values.?const?declarations share some similarities with?let?declarations.
const cannot be updated or re-declared
This means that the value of a variable declared with?const?remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with?const, we can neither do this:
const greeting = "say Hi"
greeting = "say Hello instead";// error: Assignment to constant variable. ;
Hoisting of const
Just like?let,?const?declarations are hoisted to the top but are not initialized.
What are first class citizen in JavaScript?
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
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!");
What is a higher order function
Higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.
const firstOrderFunc = () =>
console.log("Hello, I am a First order function");
const higherOrder = (ReturnFirstOrderFunc) => ReturnFirstOrderFunc();
higherOrder(firstOrderFunc);
What is a unary function
Unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function. Let us take an example of unary function
const unaryFunction = (a) => console.log(a + 10);
What is a pure function
A Pure Function is?a function (a block of code) that always returns the same result if the same arguments are passed.??It does not depend on any state or data change during a program's execution. Rather, it only depends on its input arguments.
function calculateGST( productPrice )
{
return productPrice * 0.05;
}
What is the Temporal Dead Zone
Temporal Dead Zone is?the period of time during which the let and const declarations cannot be accessed.?The Temporal Dead Zone is a behavior in JavaScript that occurs when declaring a variable with the let and const keywords, but not with var. In ECMAScript 6, accessing a?let?or?const?variable before its declaration (within its scope) causes a ReferenceError. The time span when that happens, between the creation of a variable’s binding and its declaration, is called the temporal dead zone.
function somemethod()
console.log(counter1); // undefined
console.log(counter2); // ReferenceError
var counter1 = 1;
let counter2 = 2;
}{
What is IIFE(Immediately Invoked Function Expression)
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The signature of it would be as below,
领英推荐
(function?(x,?y,?z)?{?
???console.log(x);??
???console.log(y);??
???console.log(z);??
?})(100,?200,?300);???
What is Closure?
When a function binds together with its lexical scope or Closure is?concept of function + lexical environment in which function it was created Or A?closure?is the combination of a function bundled together (enclosed) with references to its surrounding state (the?lexical environment).
function makeFunc()
const name = 'Mozilla';
function displayName() {
console.log(name);
}
return displayName;
}
const myFunc = makeFunc();
myFunc();{
What is use case of closure in javaScript?
const LoggingService = (function () {
const infoMessage = 'Info: ';
const warningMessage = 'Warning: ';
const errorMessage = 'Error: ';
return {
info: function (str) {
console.log(`${infoMessage}${str}`);
},
warning: function (str) {
console.log(`${warningMessage}${str}`);
},
error: function (str) {
console.log(`${errorMessage}${str}`);
},
};
})();
// someOtherFile.js
LoggingService.info('one'); // Info: one
LoggingService.warning('two'); // Warning: two
LoggingService.error('three'); // Error: three
What is memoization
Memoization is a programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache. Let's take an example of adding function with memoization,
const memoizAddition = () => {
let cache = {};
return (value) => {
if (value in cache) {
console.log("Fetching from cache");
return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation.
} else {
console.log("Calculating result");
let result = value + 20;
cache[value] = result;
return result;
}
};
};
// returned function from memoizAddition
const addition = memoizAddition();
console.log(addition(20)); //output: 40 calculated
console.log(addition(20)); //output: 40 cached
Classes are?a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes. 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";
}
}
What is scope in javascript
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.
What is a service worker
A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don't need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.
What is IndexedDB
IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.
What is web storage
Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user's browser, in a much more intuitive fashion than using cookies. The web storage provides two mechanisms for storing data on the client.
What is an event flow
Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object. There are two ways of event flow
What is event bubbling
Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element.
What is event capturing
Event capturing is a type of event propagation where the event is first captured by the outermost element, and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the innermost DOM element.
What is the difference between document load and DOMContentLoaded events
The?DOMContentLoaded?event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).
What is the purpose of void 0
Void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect, because it will return the undefined primitive value. It is commonly used for HTML documents that use href="JavaScript:Void(0);" within an?<a>?element. i.e, when you click a link, the browser loads a new page or refreshes the same page. But this behavior will be prevented using this expression. For example, the below link notify the message without reloading the page
<a href="JavaScript:void(0);" onclick="alert('Well done!')">
Click Me!
</a>
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.?
What is the use of stopPropagation method
The stopPropagation method is used to stop the event from bubbling up the event chain.
How GC work in JavaScript?
The Garbage Collection mechanism in JavaScript is governed by two algorithms which are listed below.
This algorithm actually goes through 3 important steps.
H???? ?????? ???????????????????? ?????????????? ???????????????? ?????????????????????
JS runtime provides all the necessary components in order to use and run a javascript program in a browser.
?????????????????? ???????????????? ???? ???? ?????????????? (???????? ??????????):
1. JavaScript Engine : This is main component and it has further two components :
2. Event Loop : It is an endless loop that handles the execution of multiple chunks of your program over time, each time invoking the JS Engine. It actually monitors the “call stack”, “microtask queue” and “callback queue”.
3. Web API : Provides extra functionalities which are not part of JS language itself but provided by the browsers. Few examples are DOM, Timers, Fetch, Console.log etc.
4. Callback Queue : It’s a queue that contains all the callback functions that are ready to be executed.
5. Microtask Queue : It is similar to callback queue and stores special callback functions with the only difference is that it has higher priority than the callback function waiting inside the callback queue.
Difference in arrow function and normal function of JavaScript ?
More details :
What is the drawback of creating true private in JavaScript?
One of the drawback of creating a true private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance.
var Employee = function (name, company, salary) {
this.name = name || ""; //Public attribute default value is null
this.company = company || ""; //Public attribute default value is null
this.salary = salary || 5000; //Public attribute default value is null
// Private method
var increaseSalary = function () {
this.salary = this.salary + 1000;
};
// Public method
this.dispalyIncreasedSalary = function() {
increaseSalary();
console.log(this.salary);
};
};
// Create Employee class object
var emp1 = new Employee("John","Pluto",3000);
// Create Employee class object
var emp2 = new Employee("Merry","Pluto",2000);
// Create Employee class object
var emp3 = new Employee("Ren","Pluto",2500);
Here each instance variable?emp1,?emp2,?emp3?has own copy of increaseSalary private method.
What's the Diffecrence Between freeze(), seal(), and preventExtentions()?
With Object.freeze we achieve full immutability. But there are two other methods that provide object immutability, only partially.
Good Articles for further reference and study.