Open In App
Related Articles

Front End Developer Interview Questions and Answers [2024]

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

This article consists of commonly asked interview questions and their answers for front-end developers. Before directly going to the questions let us first discuss what actually the frontend development is.

What is Frontend Development?

Frontend Development basically deals with creating the UI of the web pages. It deals with displaying the data sent by the backend in an interactive and easy-to-read format. The UI of an application can attract users and the way of arranging the items interactively and attractively for different devices in a readable format is Frontend Development. Frontend Development involves different technologies like HTML, CSS, JavaScript, and some frameworks of JavaScript and CSS such as ReactJS and Bootstrap respectively.

Commonly Asked Interview Questions for Frontend Developers

1. What is HTML?

HTML stands for Hyper Text Markup Language. It is a markup language that consists of different tags. It is used to define the structure of the web pages.

2. What are Semantic elements in HTML?

The semantic elements in HTML are the elements that contain the meaning of the content and the structure of the HTML document. These elements contain content that is related to their names or reflects their names. These are the some of semantic HTML elements are listed below:

  • Header
  • Main
  • Section
  • Article
  • Aside
  • Footer etc.

3. What are the Empty elements in HTML?

The empty elements in HTML are the elements that don’t require and closing tag followed by the opening tag. These elements are also known as self-closing elements. Example: <img>, <input>, <br>, <hr> etc.

4. Differentiate between the Inline and the Block elements in HTML.

The Inline elements in HTML are the elements that do not start from a new line every time and take up the same space and width as acquired by the content. The margin and padding properties applied at the top and the bottom of these elements may not have the expected effect. Examples: <a>, <strong>, <img>, <input> etc.

The Block elements automatically starts from a new line and takes up the whole view-port width irrespective of the contained content. The padding and margin properties have the same effect on all the four sides. Examples: <div>, <h1> to <h6>, <p>, <table> etc.

5. What is list in HTML? Explain different types of list available in HTML.

In HTML, the lists are used to represent a collection of different items. There are three types of lists available in HTML as listed below:

  • Unordered List: It is defined using the <ul> and the <li> tags. By default, it represents the items with a bulleted dot.
<ul>
<li>List Item 1</li>
<li>List Item 3</li>
<li>List Item 3</li>
</ul>
  • Ordered List: It is defined using the <ol> and <li> tag. By default, it represents the list items with numeric digits.
<ol>     
<li>List Item 1</li>
<li>List Item 3</li>
<li>List Item 3</li>
</ol>
  • Definition List: It is a special kind of list which is used to list the or terms with their definitions. It can be defined using the <dl>, <dt> and <dd> tags. dt – definition term, dd – definition description
<dl>
<dt>First term</dt>
<dd>Definition 1</dd>

<dt>Second term</dt>
<dd>Definition 2</dd>

<dt>Third term</dt>
<dd>Definition 3</dd>
</dl>

6. What is the basic structure of an HTML document?

The basic structure of an HTML document in HTML5 is shown below:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>

</body>
</html>

7. Explain the elements used in the basic structure of an HTML document.

The elements used in the basic structure of an HTML document are explained below:

  • <!DOCTYPE html>: It represents the HTML5 version of the HTML.
  • <html>: It is the root element of the HTML document.
  • <head>: It contains the meta data i.e. the data about the data. The content contained by this tag is not visible on the web page.
  • <title>: It contains the title of the document which will be visible in the browser tab.
  • <body>: It contains the content of the web page in the form of the HTML tags like div, anchor, paragraph, headings, etc.

8. Explain tags in HTML.

The HTML tags are used to define the elements on the web page. Basically, they are the keywords that are enclosed inside the angle brackets(<>). The examples of HTML tags are <div>, <p>, <a>, <span>, <img> etc.

9. Why ‘alt’ attribute is used with the <img> tag in HTML?

The alt attrbute provides a alternative content that is related to the image which will be shown on the web page if the image does not gets loaded. It is used to define our image in that case.

10. What is the difference between the <div> and <span> tag in HTML?

The below table will show the differences between the div and span tag in HTML:

<div> tag

<span> tag

It is a block-level element.

It is an inline element.

It can be used to group and structure the content of the web page.

It is mainly used to interact and style the particular part of the web page.

It represents a bigger section of the web page.

It is used to traget small parts of the web page.

It starts from a new line and takes up the full width available.

It does not starts from a new line and takes up only the required width as taken by the content.

11. Why the <meta charset = “UTF-8”> tag is used?

It is used to set the character encoding of the charaters for the document to UTF-8 to properly display the text and the special characters on the web page.

12. What is the purpose of using the ‘role’ attribute in HTML?

The role attribute defines the functionality and the purpose of an element mainly the accessibility. It provides the additional information for the assisstive technologies such as screen readers, to convey the exact meaning of the element to the users with disabilities.

13. Differentiate between the GET and the POST methods in HTML forms.

The below table will explain the differences between the GET and POST methods in HTML forms:

GET Method

POST Method

It is a insecure way to send data on the server.

It is a secure way of sending the form data.

All the form data parameters are visible in the URL.

None of the parameters are visible anywhere.

It has a URL length limit that varies for different browsers.

It has a bigger URL length limit as compare to the limit of the GET method.

Results are cached by the browser by default.

Does not caches the responses in the browser by default.

Users can bookmark the form submission.

Responses can be bookmarked easily.

14. What is the use of the <iframe> tag?

The <iframe> tag is used to embed the external documents or the web pages inside the current document by specifying its link inside it. It is mainly used to embed the external videos, maps and other external content.

15. Explain the features of HTML5?

HTML5 introduced some new features that are listed below:

  • Introduced new semantic elements like: <header>, <footer>, <nav>, <aside>, <article>, <section> etc.
  • New form input types such as email, url, number, date, etc.
  • It introduced the <audio> and <video> tags to embed audios and videos and reduces the dependence on the third party libraries.
  • <canvas> element to draw graphics and animations using JavaScript.
  • Introduces the browser storage as localStorage and sessionStorage to store data in the browser.

16. What is localStorage?

It is a web storage API that allows users to store the data in the form of key-value pairs locally on the browser. It allows the users to store data persistently across browser sessions. The stored data will be available to the user even if user closes or reopens the browser tabs.

17. What is sessionStorage?

It is also a web storage API provided by the web browsers to store the data in the similar way as stored in the localStorage in the form of the key-value pairs. The data stored in the sessionStorage will only be accessible for one session such that if user closes the window or tab the stored data will be lost.

18. Differentiate between localStorage and sessionStorage.

The below table lists the differences between the local and the session storage:

localStorage

sessionStorage

The stored data can be accessible in all the opened tabs in the browser.

The stored data access is limited to the current tab or window only.

The data will be persistent if the tabs are closed and opened again.

The data will be lost once user closes the tab or the window.

Used to store the data for long term.

It is used to store the data for as long as you want to store it.

The data can be cleared using the clear() method only.

The data can be cleared either by closing the tab or by using the clear() method as well.

19. What is the purpose of using <figure> and <figcaption> elements in HTML5?

The <figure> element is used to display the media content on the web page like audios, videos etc. While, the <figcaption> element is used to give a caption or legend to the content shown by the <figure> element.

20. Write the HTML code to create a table with 3 columns and 3 rows.

The below code creates a table with 3 rows and 3 columns:

<table border="1px">
<thead>
<tr>
<th>col 11</th>
<th>col 12</th>
<th>col 13</th>
</tr>
</thead>
<tbody>
<tr>
<td>col 21</td>
<td>col 22</td>
<td>col 23</td>
</tr>
<tr>
<td>col 31</td>
<td>col 32</td>
<td>col 33</td>
</tr>
</tbody>
</table>

21. How you can merge the rows and columns of a HTML table?

You can use the colspan and the rowspan attributes with the <td> element and specify the number of rows and columns to be merged by passing a numerical value to the defined attributes. The colspan attribute can be used to merge columns while the rowspan to merge the rows.

22. Describe data attributes in HTML.

The data attributes in HTML are defined to collect the data that is private to the web page or the web application. The that is collected is basically used to personalize the JavaScript for the particular user or visitor on the web page based on the actions of that user on the web page. Now a days, the data attributes are suggested not to use on a web page as these attributes can be changed easily by going to the browser developer tools and inspect element.

23. What is CSS?

CSS, which stands for the Cascading Style Sheets. It helps to design and style the web page to make it attractive for users. CSS provides us a lot of selectors to select the HTML elements and style them according to the requirements. Some of the CSS selectors are Element Selectors, Class Selectors and Id Selectors.

24. Explain selectors in CSS.

In CSS, selectors are used to select elements and style the element by providing CSS properties to it. Below is the list of some common CSS selectors:

  • Element Selector: Select directly by using the name of the element.
  • ID Selector: Define ID attribute and select using the # prefix followed by the value of ID attribute.
  • Class Selector: Define Class attribute and select using the . prefix followed by the value of class attribute.
  • Universal Selector (*): Select using the * sign.
  • Attribute Selector: Select the elements based on the attribute values. Eg: input[type=”text”]{}
  • Direct Child Selector: Select element using any of the above selectors and use > followed by direct child selector. Eg: parent > child{}
  • Pseudo Selectors: These are selectors like :hover, :nth-child(), ::after, ::before etc.

25. Explain the precedence of the Class, Id and Element selectors in CSS.

The precedence of the ID, Class and Element CSS selecors is shown below:

  • ID Selector > Class Selector > Element Selector
  • ID Selector + Class Selector > ID Selector + Element Selector > Class Selector + Element Selector

26. What are the best practices for using JavaScript and CSS?

The best practices for JavaScript and CSS can be defined according to the project requirements. Below are some general best practices listed for JavaScript and CSS:

  • Always use an external file for defining the JavaScript and CSS with .js and .css extensions respectively.
  • Always link the CSS file inside the <head> tag of the HTML document.
  • Always add the script file at the end of the <body> tag just before where body closes.
  • Try to write JavaScript in strict mode to avoid errors and write cleaner JavaScript.
  • Avoid creating global variable and use the meaningful name to define the variables.

27. What is difference between visibility: hidden and display: none properties in CSS?

The visibility: hidden property only hides the content of the element on which it is used. It does not removes the element from the document and keep the space as it is so that no other element can replace it on the UI. On the other hand, the display: none property not only hides the element but removes it from the document and the space acquired by the element is now free to be acquired by the other elements.

28. Mention the issues faced by developers while running the CSS in Internet Explorer (IE)?

Below list shows the issues faced by the developers in Internet Explorer:

  • Transparency of the images with .png extension.
  • Issues related to Z-index property.
  • Sometimes, it doubles the margin added to an element.
  • Box model has a different interpretation.
  • Lack the support for the CSS3 Features.

29. Explain box-model in CSS.

The box model in CSS is basically a blue print of an element with some properties. The box model contains four elements which are content, padding, border and margin.

  • Content: It can be the text content or the nested HTML elements with some content inside a element.
  • Padding: It is the space around the content of the element or the space between the content and the borders.
  • Border: This is the stroke or outline provided to the element to see its boundaries or style it.
  • Margin: It is the space around the whole element, it is the gap outside the element from other elements or the space between the border of this element and other elements.

30. What is the purpose of z-index property in CSS?

The z-index property is used to control the stacking order of the elements that are positioned using the position property in CSS. The higher or the positive values will make the element appear on the top of the other elements while the negative or the lower values make them appear behind the elements with higher values.

31. What is the use of float property?

The float property allows to set the child elements of a container either on the left side of it or at the right side of it. The possible values for this property are left, right, initial, inherit, and none.

32. Explain different ways to display an element at the center of the web page.

There are many ways to center a element on the web page as described below:

  • Using margin: The margin property can be used to center a element horizontally by giving margin auto from left and right of the element as margin: 0 auto;.
  • Using display: The display property with value flex can be used to center a element vertically as well as horizontally by using some extra properties as align-items: center; and justify-content: center;.
  • Using position and transform: You can position a element to give it a left and top to 50% and then use the transform property with value translateY(-50%);

33. Describe the use of the position property in CSS.

The position property is used to position an element with respect to different elements according to the given property value. The possible values of this property are relative, absolute, fixed, sticky, and static.

34. What are pseudo classes and pseudo elements in CSS?

The pseudo classes and pseudo elements are different entities in CSS. They are combinely known as pseudo selectors in CSS. Below is the explanation for them:

  • pseudo classes: These are the classes that selects the elements based on their state and the position. Some pseudo classes are :hover, :focus, :nth-child etc.
  • pseudo elements: These are the virtual elements that are mainly defined to style a particular part of an element in the HTML document. Some pseudo elements are :before and :after.

35. Why is the ‘!important’ used in CSS?

The !important declaration is used to give higher precedence to a CSS property to override it from other conflicting styles defined on a element using the same property such as width: 30px !important; will override the property width: 25px; defined on the same element.

36. What is the purpose of ‘box-sizing’ property in CSS?

The box-sizing property is used to determine the way of calculating the height and width of a element. It determines whether the border and padding will be included or not to calculate the height and width of the element. The common values are content-box(default) and border-box.

37. Tell me about CSS preprocessors and their advantage over pure CSS?

A CSS preprocessor is created using a scripting language that extends the CSS rules and processed in the regular CSS by creating a file with .css extension. Mostly used CSS preprocessors are SASS and LESS. SASS is based on the Ruby language while LESS is based on JavaScript, initially it was also based on Ruby but now shifted to JavaScript. They rpovide some extra features like creating variables, mixins, code nesting and some other features to enhance code maintainablility.

38. What is the meaning of ‘Cascading’ in Cascading Style Sheet?

Cascading represents the specificity order in applying styles. These styles can be defined by the user, author or they can be the default browser styles. The specificity order for the styles is user styles > author styles > default browser styles.

39. Explain Media Queries in CSS.

Media queries are the block of CSS code defined for a particular width or range of the width. These can be defined using the @media keyword with screen to specify styles for a particular width or range of width. They are used very commonly to create responsive designs.

40. Describe CSS sprites and their importance to improve website performance.

CSS sprites are a technique that is used to compress multiple images available on the web page into a single image file. It arranges all the images in a grid-like layout. The background-position property of CSS can be used to display the different parts of the combined image as background for different elements. It improves the web performance by reducing the server requests as the website has to request only a single image now instead of requesting multiple images.

41. How you can optimize the loading of CSS files in browser?

There are multiple techniques available to optimize loading of CSS files as listed below:

  • By minimizing number of CSS files.
  • CSS minification
  • By leveraging the browser cache
  • Load the un-necessary styles using asynchronous or deffered loading.

42. How to create responsive designs?

There are some key concepts available in CSS that can help you in creating responsive desings as listed below:

  • Using Media queries
  • Using the flexbox layout
  • Using the grid layout
  • Using responsive CSS properties like percentage and vh, vw.

43. What is JavaScript?

JavaScript is a high level scripting language. It is a dynamically typed language. JavaScript is used to add the dynamic elements and styles to the HTML document to make the web page more interactive and attractive. JavaScript is used in both frontend as well as backend.

There are a lot of frameworks and libraries of JavaScript available that can be used in frontend like ReactJS, Vue.JS, AngularJS, NextJS etc. There is only one framework of JavaScript avaiable for the backend development which is Node.JS.

44. What is difference between == and === in JavaScript?

The == operator is known as the double equal to operator in JavaScript and === is the triple equal to operator. Both of these operators are the comparison operators and used to compare the values of the operands. These operators are almost same, there is only one difference between them. The == operator checks only for the values of the operands and return true if the values are same. On the other hand, the === operator not only checks for the values of the operands but also for the types of the operands. It returns true only if the values and the type of the operands is same.

3 == "3" // Returns true
3 === "3" // Returns false

45. How to defer an element’s event handler if it depends on an external script that takes some time to load?

In order to defer the event handler of an element if it depends on an external script that takes some time to load. You can use the defer attribute inside the script tag while adding the external JavaScript file. The defer attribute confirms that the script will be executed after the HTML gets parsed.

<script src='external-script-file.js' defer></script>

Now, you need to attach the event listener to the element dynamically. In order to wait for the external script file load, we can attach the load or the DOMContentLoaded events before executing the script and once the loading is completed, you can attach the event listener to your element by checking any function or variable from external script, whether it is loaded or not and run the code with respect to it. Refer the below code for understanding:

document.addEventListener('load', function(){
if(typeof coder === "boolean"){
const myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(){
console.log("Button is Clicked!!");
})
}
})

In above code, we are assuming the the external script file contains a variable coder of boolean type and using this variable to check whether the external script is loaded or not.

46. Optimal strategy for winning a game where let’s say, I start with 1, opponent can cite a number X within the range [2, 11]. Then I have to say a number in the range [X + 1, X + 10], then opponent, then me, and so on. Whoever says 100 in the end wins and the game ends.

The optimal strategy for winning this game is to put your oppenent in a situation where they have no choice to say some number that is closer to 100 and then you have 100 in the range from that number + 1 to that number + 10, so that you can say 100 first and wins the game.

47. Why would you use the prototype in JS?

The prototype is a very important and fundamental concept of JavaScript. It is the basic concept of the Object Oriented Programming and the prototype chain. The below list involves some reasons of using prototype in JavaScript.

  • To modify the properties and methods of an object dynamically.
  • Used in inheritance implementation.
  • To allow the sharing of properties and methods of an object.
  • JavaScript is a prototype based language.
  • Prototypes can be used to create shared methods that can save memory.

48. What is the meaning of ‘this’ in JS?

The this keyword in JavaScript is a identifier that based on the scope of the function or variable from which it is invoked. The scoping behaviour of this keyword changes based on the scope where it is used. At the global level this keyword refers to the global window object. In below example, the this keyword will refer to the scope of the object whose function is called:

const myObj = {
name: "GeeksforGeeks",
stats: function(desc){
this.desc = desc;
}
}
console.log(myObj.stats("A Computer Science portal for Geeks."));

49. Namespaces in JavaScript

Namespaces in JavaScript are the basic programming paradigm that provides encapsulation to some variables of functions. So that, if the functions and variables with same names are defined the program at some other place do not collapse and work as expected. You can also use the objects to achieve the same effect.

//Declaring namespace
let myNamespace = {
nameSpace: "Creating a name space in JavaScript"
}

//Accessing namespace identifiers
console.log(myNamespace.nameSpace);

//Output: Creating a name space in JavaScript

50. Difference between null and undefined in JS.

The undefined and null are basically the values that the variables or function gets by default. The meanings of both these values are different do not use these values interchangeably.

Undefined Value:

  • The undefined is the default value that is assigned to an variable which is declared but not initialised.
  • It is also the default return value of a function.
  • When you try to access some value or property that is not in the part of object, it returns undefined.

Null Value:

  • It can be assigned to an variable to make it an empty variable.
  • It represent that the accessing variable is not present in the code.

51. Explain closures in JS with an example of statements in loop

A closure in JavaScript forms when a function is defined inside another function or returned by a function. The ability of inner function to remember its scope and the scope of its parent function’s chain is known as closure. A closure function can access the variables of its parent function even if it gets executed.

function sum(a){
return function sum2(b){
return a+b;
}
}

for(let i=1; i<=5; i++){
console.log(sum(i)(i+1));
}

52. What is event loop in JavaScript?

JavaScript is a synchronous and single threaded language, that means JavaScript executes the code line by line in one go and do not wait for any code to get execute. The event loop is a mechanism built in JavaScript engine to handle the asynchronous tasks efficiently. The event loop continuously check the call stack and the callback queue. If it finds that the call stack is empty, it immediately pushes the asynchronous task from the callback queue to call stack to get executed.

53. Explain hoisting in JS?

Hoisting is a concept in JavaScript, which allow us to access or extract the values of the functions and variables even before initialising or assinging values to them. The reason behind this is the allocation of memory to the variables and functions during the first phase of execution.

console.log(hoistedVariable);  // Undefined
var hoistedVariable = 25;
console.log(hoistedVariable); // 25

54. What are different Data types in JS?

JavaScript is a dynamically typed language, that means unlike the other programming languages like C, C++ the type of the variables is decided at the run time instead of the compile time. In JavaScript, there are two types of data types available:

  • Primitive Data type: These are the predefined data types like string, number, boolean, undefined, null, BigInt etc.
  • Non-Primitive Data type: These are the data types that are derived from the primitive data types like arrays and objects.

55. If the typeof([]) is object, then What is the content and the length of b in below code?

let b = [];
b.v = 10;
b.push(11);

Arrays in JavaScript are a special kind of data type which can hold the numerical values and the values with key as well. In the above code,

  • the line var b = [], creates an empty array,
  • then the line b.v=10, adds a key in the array with a value of 10 and
  • finally the line b.push(11), pushes the numeric value 11 to the array.

It makes the content of the array as: [11, v: 10], and the length of the array as 1, because these is only one numeric value present in the array.

56. Different ways to create objects in JS?

In JavaScript, we can create objects using the different syntaxes. Below are some ways to create object in JavaScript:

  • Using Object Literal
let obj = {}
  • Using construction function
function Student(name, class){
this.name = name;
this.class = class;
}
let obj = new Student("Neha", 8);
  • Using Object.create() method
const obj = Object.create(prototype)
  • Using Class
class Student{    
constructor(name, class){
this.name = name;
this.class = class;
}
}

let obj = new Student("Neha", 8);
  • Using Object constructor
let obj  = new Object();
obj.name = "Neha";

57. How to implement inheritance in JS?

In JavaScript, the inheritance can be implemented in two different ways:

  • Prototypal Inheritance: It can be implemented as shown below.
// Parent constructor function
function Student(name) {
this.name = name;
}

// Adding a method to the prototype of the parent
Student.prototype.getName = function() {
console.log('My name is ' + this.name);
};

// Child constructor function
function Rahul(name, std) {
// Call the parent constructor using call or apply
Student.call(this, name);

// Add properties specific to the child
this.std = std;
}

// Inherit from the parent prototype
Rahul.prototype = Object.create(Student.prototype);

// Add a method specific to the child
Rahul.prototype.speak = function() {
console.log('Hello World!');
};

// Create an instance of the child
const myObj = new Rahul('Rahul', '8th');

// Access inherited method from the parent
myObj.getName(); // Output: My name is Rahul

// Access method specific to the child
myObj.speak(); // Output: Hello World!
  • Class based Inheritance: It uses the Object Oriented Programming Concepts of JavaScript and inherits properties of parent class using the extends keyword as shown below.
class Parent{
// Some properties
}
class Child extends Parent{
// Some properties
}

58. Explain call(),apply() and bind() methods in JavaScript.

These methods are in-built JavaScript methods and used to call the functions with the specified context and the this value of the context. These methods can also be used to set the value of this keyword to some other context while invoking the functions.

  • call() method: It is used to call the functions with a specified this identifier value and individual multiple arguements.
let myObj = {
implementCall: function(name, desc){
this.name = name;
this.desc = desc;
console.log("Implementing Call method");
console.log(this.name, this.desc);
}
}
let func = myObj.implementCall;
func.call(this, "GeeksforGeeks,", "A Computer Science portal for all geeks");
  • apply() method: The apply() method in JavaScript is almost same as the call() method, there is only one difference between them, that is the apply method allows you to pass multiple arguments together to the function in the form of an array.
let myObj = {
implementApply: function(name, desc){
console.log("Implementing Apply method");
console.log(name, desc);
}
}
let func = myObj.implementApply;
func.apply(this, ["GeeksforGeeks,", "A Computer Science portal for all geeks"]);
  • bind() method: The call() and apply() methods invokes the function immediately after the application but the bind() method is used to bind a function to some variable with the passed parameters and the scope of this identifier, so that the function can be called later when you need to call it.
let myObj = {
implementApply: function(name, desc){
console.log("Implementing Bind method");
console.log(name, desc);
}
}
let bindedFunc = myObj.
implementApply.bind(myObj, "GeeksforGeeks,", "A Computer Science portal for all geeks");
bindedFunc();

59. What is event delegation in JavaScript?

Event delegation is a technique in JavaScript that is used to improve the performance and reduce the memory usage of our website by attaching a single event listener to the parent in the case when you need to attach event listeners to each child of that element. You can handle the changes on the website by using only one event with the parent element.

60. Tell me about key features of JavaScript.

There are many features provided by JavaScript, some of them are listed below:

  • It is a Single threaded language.
  • Dynamic variable typing.
  • Prototypal and classical inheritance
  • First class functions
  • Higher order functions.
  • Hoisting and closures etc.

61. What is the use of “use strict” directive in JavaScript?

The use strict diretive is used to write the clean JavaScript code which is less prone to errors. It catches common coding errors like assigning a variable without declaring it or passing different parameters with same names to a function etc.

62. What is event propagation in JavaScript?

Event propagation defines the behaviour how the events will propagate when they are attached with the child and the parent elements. There are two ways in which events can propagate.

  • Event Bubbling
  • Event Capturing

63. Define event bubbling in JavaScript?

Event bubbling is the process in which the event propagate from the target element back up to its ancestors in the DOM tree that means if the innermost element is clicked the event will travel up to the outermost ancestor or the parent element in the DOM tree. It is the default behaviour of the event propagation.

64. What is event capturing?

Event capturing is just opposite of the event bubbling. The event propagate from the outermost element to the innermost element in this case. It can be enabled by passing an extra parameter as false to the addEventListener() method at the time of attaching an event.

65. What are callback functions in JavaScript?

A callback function in JavaScript is a function that can be passed as an parametr to another function and then it is the responsibility of that function to call it later at some time. For Example: addEventListener() method takes a callback function and calls it when the passed event occurrs, setTimeout() method also takes a callback function which will be called later once the passed time period expired.

66. What is callback hell and how to avoid it?

Callback hell refers to a situation in which multiple nested callback function are used i.e. a function contains multiple nested functions and all of them are called by passing a callback function as parameter to them. It is mainly occurrs when you are dealing with asynchronous operations. Promises and async/await statemetn can be used to avoid callback hell.

67. Explain Promises in JavaScript.

A Promise is an object that represents the completion or failure of an asynchronous task and its resulting value according to the status. There are three states of an promise:

  • pending: It is the initial state in which promise is neither rejected nor fulfilled.
  • fulfilled: It represents the successful state of the promise where it completes the task.
  • rejected: It represnts that the asynchronous task gets failed.

68. What is the use of async await in JavaScript?

The async statement is used to represent the asynchronous task that tkes sometime to get resolved. While, the await statement is used to wait for a promise or asynchronous task to resolve or fulfill to continue the asynchronous function execution.

69. Explain the concept of currying in JavaScript?

Currying is a technique which is used to transform a function that takes n parameters into a chain of n functions in which each function contains only one parameter.

function normalFunction(a, b){
return a*b;
}
normalFunction(3, 2) // Output: 6

function curryingFunction(a){
return function(b){
return a*b;
}
}
curryingFunction(3)(2); // Output: 6

70. What is the purpose of passing defer or async attributes to the script tag?

The defer and the async attributes are used to load the script in a particular manner as explained below:

  • defer: It parallely fetches the HTML and script, once the whole script is fetched it stops fetching HTML and executes the script first, then again starts fetching HTML and execute it once it is completely fetched.
<script src="script_file_path" defer></script>
  • async: The async attribute makes the server to fetch the script and HTML parallely and once it fetches both of them it starts executing script and only after that it will execute the HTML.
<script src="script_file_path" async></script>

71. Explan try catch block in JavaScript.

The try and catch blocks are used to efficiently handle the different states of an operation. The try block checks the code written inside it for the errors. If the code executes with errors the catch block catches that error and display them to the user. Otherwise, the code written inside the try block for the successful condition will executes.

try{
// try block code
}
catch(error){
// Show errors to users
}

72. How to stop event propagation in JavaScript?

There is a in-built method e.stopPropagation() provided by the JavaScript events which can be used to stop event propagation. The method can be implements as follows:

element.addEventListener('event', function(e){
e.stopPropagation();
})

73. How to prevent the default behaviour of a event in JavaScript?

The e.preventDefault() is a in-built method provided by JavaScript that can be used to prevent the default behaviour of an JavaScript event.

74. Describe the concept of CORS?

CORS stands for Cross-Origin Resource Sharing. It is a technique used by the browsers to make our web page more secure. The web browsers use this feature to prevent requests from one domain to another domain.

75. Explain debouncing in JavaScript?

It is a technique used to improve the performance of the web page by ensuring that the time consuming tasks do not fire so often in the code. One use case of debouncing is to handle the situation in which frequent server requests are made evertime a key is pressed. For Example: search functionality on different web pages.



Last Updated : 09 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads