Javascript Interview Questions and Answers

What is Javascript?

  • JavaScript is a programming language that is primarily used to create interactive web pages and dynamic user interfaces. It is a high-level, object-oriented language that can be used on both the front-end and back-end of web development.
  • javascript is a client-side scripting language, loosely typed dynamic language
  • It executes in users browser and allows webpage to communicate with the server-side and make changes to the web page without requiring a page refresh.
  • Javascript can track user initiated events such as tap, drag, click, touch etc

How properties are assigned to an object?

Properties are assigned to objects in the following way obj["age"]=12 or obj.age = 12

What is the way to get the status of the checkbox?

The status can be acquired as follows alert(document.getElementById('checkbox').checked); If the checkbox will be checked, this alert will return true

What are the features of Javascript?

It is Lightweight, object based scripting language

Validates user inputs for any errors before it sending to the server

Can dynamically generate html content

Explain the difference between "==" and "==="?

"==" checks only in equality in values converting them to a common type if necessary by type coercion, "===" is a stricter equality test and returns false if either the value or the type of the two variables are different without type coercion.

Explain how to detect the operating system on the client machine

In order to detect the operating system on the client machine, the navigator.platform string property should be used

What is the function of the delete operator?

the delete keyword is used to delete the property as well as its value var person = { age: 20, name: "jhon"} delete person.age;

What is the use of void(0)?

void(0) is used to prevent the page from refreshing and parameter "zero" is passed while calling void(0)

What is the difference between alert box and confirmation box?

An alert box displays only one button which is the ok button
But a confirmation box displays two buttons namely Ok and cancel

What are javascript cookies?

Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be user name details and shopping cart information from the previous visits

What is the use of push method in Javascript?

The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments

What is the unshift method in javascript?

Unshift method is like push method which works at the beginning of the Array. This method is used to prepend one or more elements to the beginning of the Array.

Explain window.onload and onDocumentReady

The onload function does not run until all the information on the page is loaded with the entire styling from css and images. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the Dom is loaded. This allows early manipulation of the code

Define Event bubbling

Javascript allows DOM elements to be nested inside each other. In such case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too

What are first class functions?

A first class function is a function that 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 the use of history object?

The history object of the browser can be used to switch to history pages such as back and forward from the current page or another page.
There are three methods of history object

  • history.back() - it loads the previous page
  • history.forward() - it loads the next page
  • history.go(number) - the number may be positive or negative, positive for forward and negative for backward, it loads the given page number

How can you check if a variable is an array in JavaScript?

You can use the Array.isArray() method to check if a variable is an array. It returns true if the variable is an array, and false otherwise.

What is the difference between undefined value and null value?

A value that is not defined and has no keyword is known as undefined value

A value that is explicitly specified by the keyword "null" is known as null value.

Undefined means variable declared but not defined

Null means variable is defined but not assigned a value

Implies no value or no object

null is a value that represents the intentional absence of any object value

What is javascript strict mode?

"strict mode" is a restricted variant of javascript which enforces stricter parsing and error handling rules. Usually this language is not very strict in throwing errors. But in 'strict mode' it will throw all types of errors even the silent errors. Thus , the process of debugging becomes easier. And the chances for making a mistake fo the developer is reduced.

Sometimes it displays results even there is error in the code, to overcome this issue we can use strict mode in javascript, the javascript will throw all types of errors

Duplicate arguments are not allowed by developers.

In strict mode, you won't be able to use the JavaScript keyword as a parameter or function name.

The 'use strict' keyword is used to define strict mode at the start of the script. Strict mode is supported by all browsers.

Developers are not allowed to create global variables in 'Strict Mode.

What are self invoking functions?

They are also known as 'Immediately invoked function expressions' or 'self executing expressions'. These functions are invoked automatically in the code. hence they are named as 'self invoking functions' (function(){ })();

IFFE creates a closure around the code you are writing. You don't have to worry about naming conflicts or naming collisions if you are writing a library.

It is typically used to create a private scope and avoid polluting the global namespace.

Why javascript is called a loosely typed or a dynamic language?

Javascript is called as a loosely typed or a dynamic language because javascript variables are not directly associated with any value type and any variable can be assigned and re-assigned values of all types
for example: var myVar = 10; myVar = 'string'; myVar = "hi";

In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.

What is memoization?

Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned.

What is a closure?

A closure is a primary mechanism to private the data items. Closures give access to the outer functions scope from inner function scope. A closure is a function that has access to variables in its outer lexical scope, even after the outer function has returned. This allows the function to “remember” the values of those variables, even if they are no longer in scope. closures are created for every function in javascript. To define a closure, create a function inside another function to expose it

What is the use of a constructor function in javascript?

Constructor functions are used to create objects in javascript. If we want to create multiple objects having similar properties and methods, constructor functions are used.

What is recursion?

Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.

What is the difference between a for loop and a for…in loop in JavaScript?

A for loop iterates over a range of values, while a for…in loop iterates over the properties of an object.

What is lexical scope?

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration.

Explain the terms synchronous and asynchronous

The synchronous code is something that should be finished before anything else can happen, or in other words, the synchronous code is blocking. And the asynchronous code is something in which actions can happen and is not depending on other actions. in other words it is non-blocking.

or

Synchronous code is executed in a sequential order, blocking the program until a task is completed, while asynchronous code allows multiple tasks to be executed simultaneously and continues running without waiting for a task to complete.

Asynchronous functions can execute concurrently with other code, allowing multiple tasks to be performed at the same time.

What is async and await?

async always returns a promise. await waits till the promise is settled

What is the difference between a for loop and a forEach loop in JavaScript?

A for loop is a traditional looping construct that allows you to iterate over an array or object by specifying a starting point, an ending point, and an increment. A forEach loop is a built-in method on arrays that iterates over each element in the array and performs a function on each element.

Explain the terms array slice() and array splice();

Array slice() method removes the array items from the array and reforms the removed items into a new array. The selected items through an array slice() method are removed from the array and formed as another new array.
Array splice() method removes the items of the selected array from the array and does not form another array.

Can redirection of a page is possible in javascript?

Redirection of the page is possible in javascript. By using two ways we can redirect a page to other pages, they are:
location.href - this is one of the ways to redirect a page. By this, we can get back access to the document.
location.replace - In this, we can't get access back the actual document.

How to add and remove properties from object?

By using, object.propertyName = value we can add a property to the js object
By using delete object.propertyName, we can remove the property name from the js object.

What is the difference between typeof and instanceof operators in javascript?

The typeof operator returns a string of what type the operand is. whereas, the instanceof operator does not work with primitive data types. but works with objects and checks on what type the object is

Name some of the javascript frameworks

There are many javascript frameworks available today, but the most commonly used frameworks are:
Angular, Vue
React is not a framework, its a javascript library

What are the primitive data types in JavaScript?

The primitive data types in JavaScript are string, number, boolean, null, undefined, symbol and BigInt.

What are anonymous functions in javascript?

An anonymous function allows a developer to create a function that has no name. in other words, anonymous functions can be used to store a bit of functionality in a variable and pass that piece of functionality around.
let show = function () { console.log("hi"); }

What is DOM?

DOM(document object model) is an object oriented representation of the html elements. all the elements are the part of window.document. When the browser renders an HTML document, it creates an object based on the HTML document called DOM.

What is the difference between window and document in the javascript?

javascript window is a global object which holds variables objects, functions, arrays, history , location. The document also comes under the window and can be considered as the property of the window

What is the difference between HTMLCollection and NodeList?

The functions querySelectorAll() returns NodeList in which the forEach can be used directly to traverse the elements.
whereas , the getElementsByClassName() or getElementsByTagName() returns an HTMLCollection which does not have a forEach by default.

How can an HTMLCollection be traversed?

The HTMLCollection by default does not have forEach, it needs to be converted into an array (eleName = Array.from(eleName)) and then the traversal is possible using forEach.

What is scope and scope chain in javascript?

Scope is the accessibility of variables and functions at various parts of the code.

There are three types of scopes in Javascript

  • Global scope
  • Local or Function scope
  • Block scope

What is global scope ?

Any variable or function declared outside the code block {} or in the root level in the javascript code is said to be in global scope, can be accessed from anywhere in the program

Important
Global variables declared with the let keyword are not added to the global object, therefore, trying to access such variables using window.variableName results in an error.

What is local scope ?

Any variables or functions declared inside a function have local scope and Cannot be accessed from outside the code block

What is block scope?

Variables declared using let and const are block scope. It means that any variable declared inside a block { }, can only be accessed inside that block and cannot be accessed outside of it.

What is higher order function?

Accepts another function as an argument or returns another function as a result

What is a callback function?

A Callback is a function passed to another function as an argument and executed inside that function. It will be executed after another function gets executed. In javascript, functions are treated as first-class citizens, they can be used as an argument of another function, can be returned by another function.

What is difference between target and current target?

current target always refers to the element to which the event handler is attached to where as target identifies the element on which the event is occurred

What is Promise?

It allows us to write async code in synchronous way.

An Object that is used as a placeholder for the future result of an asynchronous operation, a container for an asynchronously delivered value we no longer need to rely events and callbacks passed into asynchronous functions to handle asynchronous results Instead of nesting callbacks, we can chain promises for a sequence of asynchronous operations, escaping callback hell

What is the difference between “var”, “let”, and “const” in JavaScript?

“var” declares a variable with function scope, “let” declares a variable with block scope, and “const” declares a variable that cannot be reassigned.

Meaning of scope in javascript

Scope is the accessibility of the variables and functions in the running environment.

There are two scopes supported in javascript, the local scope and the global scope

What is a web worker?

web worker is a piece of javascript code that works in the background

web workers are a simple means for web content to run scripts in background threads

the worker thread can perform tasks without interfering with the user interface and in addition it can perform input, output using xmlhttprequest and channel attributes are always null

once web worker is created, it can send messages to the javascript code that created it by posting messages to an event handler specified by that code

Why javaScript is a dynamic language?

Dynamic language means data types of the variables can change during the runtime

Explain hoisting

Its a mechanism where variables and function declarations are moved on to the top of the scope

Hosting works for all var, let and const. It's just variables defined by let and const are in temporal dead zone which can't be accessible hence we get error. Else all three(var,let,const) are hoisted.

or

hoisting works for let, const and var but while using let and const it creates a temporal dead zone where we cannot access these variable and in that scenario you will get reference error and javascript is still aware of that variable but only make restrictions of using it at TDZ

Important:
Variable initializations are not hoisted, only variable declarations are hoisted
To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code

What is the difference between a function declaration and a function expression in JavaScript?

A function declaration creates a named function that is hoisted to the top of its scope, while a function expression creates an unnamed function that is assigned to a variable or property.

What is a callback?

callbacks are used to do things asynchronously, or whenever you want to execute code not necessarily in order, but at a certain point in time or when an event takes place. Now, because of this, they're used often in events to take care of tasks, whenever the events are triggered. Callbacks often use the anonymous function, which means a functions with no names, because they're invoked immediately once the event takes place, so there's no need for a name.

What is composition in javascript?

Function composition is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result.

What is the difference between a callback function and a promise in JavaScript?

A callback is a function that is passed as an argument to another function and is called when that function completes. A promise is an object that represents the eventual completion of an asynchronous operation (fulfilled, completed, rejected), and provides a way to handle the result of that operation. Promises are used to avoid “callback hell” and make asynchronous code easier to read and maintain.

What is the difference between call, apply, and bind in JavaScript?

call and apply are methods that allow you to call a function with a specific context and arguments. The difference between them is how you pass the arguments. call accepts arguments as a comma-separated list, while apply accepts arguments in an array. bind is a method that returns a new function, allowing you to call the function later with the same context.

What is an array in JavaScript?

An array is a collection of data in JavaScript that can hold multiple values, including strings, numbers, and objects. It is declared using square brackets and each value is separated by a comma.

What is an object in JavaScript?

An object is a collection of properties in JavaScript that can hold multiple values, including strings, numbers, arrays, and other objects. It is declared using curly braces and each property is separated by a comma.

How do you prevent event bubbling in JavaScript?

You can use the stopPropagation() method of the event object to prevent event bubbling.

What is the purpose of the let keyword in JavaScript?

let is used to declare a block-scoped variable in JavaScript. It is similar to var, but the scope of the variable is limited to the block in which it is declared.

How do you loop through an array in JavaScript?

You can loop through an array in JavaScript using a “for” loop or a “forEach” loop.

How to loop through objects keys and values in Javascript?

Using a for...in loop

Object.keys method, Object.values method, Object.entries method

What is the purpose of the map() method in JavaScript?

The map() method is used to create a new array by applying a function to each element of an existing array. The original array is not modified.

What is NaN in JavaScript?

NaN stands for “Not a Number”. It is a special value that represents the result of an operation that cannot produce a valid number. To check if a value is NaN, we use the isNaN() function.

What is the difference between local storage and session storage in JavaScript?

Both local storage and session storage are mechanisms for storing data on the client-side, but local storage persists even after the browser is closed, while session storage is cleared when the tab is closed.

What is local storage?

local storage is a built-in object in web browsers that allows web applications to store key-value pairs locally within the user's browser

How do you limit the rate of api calls or reduce the cost of api calls and improve the application performance?

By using de bouncing, it is a concept that will help you to limit the rate of event triggering, like rate of limiting any execution of functions

What is the difference between the DOM and the BOM in JavaScript?

The Document Object Model (DOM) is a programming interface for HTML and XML documents that allows JavaScript to access and manipulate the content and structure of a web page. The Browser Object Model (BOM), on the other hand, provides a programming interface for the browser window and other browser-specific features, such as document, history, screen, navigator, location, and other attributes which are available in the window object.

What is meant by shallow copy in javascript?

A shallow copy of an object is a copy whose properties share the same references as those of the source object from which the copy was made

How do you check if an object has a specific property in JavaScript?

You can check if an object has a specific property in JavaScript using the “in” operator or the hasOwnProperty() method.

What is constructor in javascript?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

How do you convert a string to a number in JavaScript?

You can convert a string to a number in JavaScript using the Number() or parseInt() functions.

What is Implicit Type Coercion in javascript?

Implicit type coercion in javascript is the automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types.

What is Event Bubbling?

Event Bubbling is a concept in the DOM. It happens when an element receives an event, and that event bubbles up to its parent and ancestor elements in the DOM tree until it gets to the root element.

What is the difference between map() and forEach() in JavaScript?

The map() method creates a new array with the results of calling a function on each element in the original array, while the forEach() method executes a function on each element in the original array. The map() method returns a new array, while the forEach() method does not.

Why do we use “debugger” in javascript?

The debugger for the browser must be activated in order to debug the code. Built-in debuggers may be switched on and off, requiring the user to report faults. The remaining section of the code should stop execution before moving on to the next line while debugging.

How many different methods can you make an object in javascript?

  • class method
  • object literals
  • function constructor
  • object constructor
  • create method

What is event capturing?

Event capturing is one of two ways to do event propagation in the HTML DOM. In event capturing, an event propagates from the outermost element to the target element. It is the opposite of event bubbling, where events propagate outwards from the target to the outer elements.

Event delegation?

The pattern of handling an event on an ancestor element is called Event Delegation

Event Delegation is a useful pattern that allows you to write cleaner code, and create fewer event listeners with similar logic.

What is function currying?

Currying a function is forcing it to take a single parameter at a time. Each parameter is passed in individually, and each function call returns another function, until all parameters have been provided.

or

Currying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments.

What is "this" keyword in javascript?, what does it bind to?

"this" keyword refers to the object from where it was called or it is the reference to the object in which it is used

"this" is the property of the execution context.

The value of the “this” keyword will always depend on the object that is invoking the function.

Arrow functions in es6 and beyond don't have their own this.

The “this” keyword refers to the current object context and allows methods to access and manipulate properties and methods of the object that called them.

What is the difference between test() and exec() methods in javascript?

exec() and test() are RegExp expression methods used in javascript.

exec() is used to search a string for a specific pattern, and if it finds it, it'll return the pattern directly; else, it'll return an 'empty' result.

test() is used to find a string for a specific pattern. It will return the Boolean value 'true' on finding the given text otherwise, it will return 'false'.

List out some advantages of using External JavaScript?

External javascript is the code written in the separate js file and then link that file inside the head or body section of the webpage

Some advantages of using external javascript file are

  • We can reuse the code through out the application
  • It allows multiple developers to work on same time on same file.
  • easy readable, manageable and time saving by making changes in one single file.

What is undeclared and undefined?

undeclared means variable is not declared or initialized, undefined means variable is declared but value is not assigned

What is innerText and innerHtml?

innerText interprets html tags as text and display the tags as text where as innerHtml interprets html tags as html and display content in html format.

What is event bubbling in javascript?

Event is first captured, handled by the target element and propagated to parent elements until it reaches the root element which is document object

What are Break and Continue statements?

Break is used to jump out of the loop without executing following statements, Continue skips remaining loop statements and continues with next iteration in the loop

What are the different types of errors in javascript?

There are three types of errors in javascript

  • Syntax errors
  • Runtime errors
  • Logical errors

syntax errors occur during interpret time

run time errors occur during execution time

logical errors hard to find, we have to debug the code

Can you access cookies using javascript?

cookies can be created, read and erased by javascript, accessible through document.cookie

What are rest and spread operators?

rest operator puts the rest of the specific user supplied values into a javascript array or javascript object, but the spread operator expands iterables into individual elements

Any number of arguments will be converted into an array using the rest parameter.

we use rest when we declare the function , we use spread when we invoke the function

Important
Rest parameter should always be used as the last parameter of a function

By default javascript functions return undefined?

true

What is destructuring?

It is faster and easier way to access values from arrays and objects.

What is Array.from?

It turns array like objects into Array. It can turn string into Array

What are params and arguments?

The values passed to the function parenthesis when defined are called params. The values passed to the function parenthesis when it is invoked are called arguments