Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

JavaScript Interview Questions and Answers 2023

NotificationsYou must be signed in to change notification settings

surbhidighe/JavaScript-Top-Interview-Questions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 

Repository files navigation


Click ⭐ if you like the project!!

Every contribution counts, regardless of its size. I value and appreciate the efforts of all contributors, from beginners to seasoned developers. Join me on this exciting journey of open-source collaboration.Together, let's build something amazing! 🤝


Contribution Guidelines

  • 👉 Please ensure that your contributions adhere to the coding style and guidelines of this project
  • 👉 Include clear and concise commit messages for all your commits
  • 👉 Provide a detailed description of your changes in the pull request.
  • 👉 Be respectful and considerate towards other contributors.

S.NoQuestions
1What is JavaScript
2What are the different data types in JavaScript
3What are the different ways to create an Object in JavaScript
4Difference between == and === operators
5Is javascript single-threaded or multi-threaded
6What are arrow functions and its features
7What do you mean by Synthetic events
8What is array destructuring
9Can we combine two arrays using any es6 operators
10Why javascript is dynamically typed language
11Difference between Undeclared and Undefined
12Difference between Null and Undefined
13What is Temporal Dead Zone
14What is IIFE
15What is Hoisting
16What are Cookies
17What is memoization
18Difference between var, let and const
19What is a callback function
20Is it possible to have both local and global variables with the same name
21Difference between Local Storage and Session Storage
22Difference between forEach() and map()
23What is rest operator
24What is spread operator
25Difference between async and defer
26What is Nullish coalescing operator
27What is the difference between a parameter and an argument
28What is a closure
29Difference between function declaration and function expression
30What are the different ways to create an array in javascript
31Difference between window and document in javascript
32What is strict mode in javaScript
33What are the different ways to empty an array in javascript
34What is NaN in javascript
35Javascript naming convention
36Difference between call(), apply() and bind()
37What is the use of isNaN function
38What is 'this' keyword in javascript
39How do we add comments in javascript
40What is the use of typeof operator
41Is JavaScript case-sensitive
42Difference between push() and unshift()
43Difference between pop() and shift()
44Different ways to access DOM elements in js
45What are promises
46What is a prototype
47What is a callback hell
48What is an event loop
49ES6 and its features
50Difference between function and method
51What is aync and await
52What is the role of event.preventDefault()
53What is the use of JSON.stringify()
54How can you stop the setTimeout
55If Javascript is single threaded, how it supports asynchronous operations
56What is javascript scope
57Difference between global scope and local scope
58What are the different ways to convert a string to an integer
59How to find the operating system in the client machine using JavaScript
60Name some JavaScript frameworks and libraries
61What is event bubbling and event capturing
62What is the role of event.stopPropagation()
63How can we change the style of an element using javascript
64What is object destructuring
65Difference between an Alert Box and a Confirmation Box
66How can we handle exceptions with javascript
67What are the advantages of using External JavaScript
68What is an anonymous function
69What is a first order function
70Different ways to access object properties in javascript
71Difference between slice() and splice()
72What are the escape characters in JavaScript
73Different ways to redirect a page in javascript
74What is the difference between innerHTML and innerText
75How can you get current time using js
76What is currying
77Difference between shallow copy and deep copy
78What is a service worker
79What is JSON
80How can you get all the keys of any object
81What is a unary function
82What is promise chaining
83What is eval
84How can you assign default values to variables
85How to determine if an object is extensible or not
86In how many ways we can make an object non-extensible
87What is object.freeze method
88What is object.seal method
89How can you determine if JavaScript is disabled on a page
90How can you compare two date objects
91Does JavaScript support automatic type conversion
92What is variable shadowing in javascript
93What is ternary operator
94Difference between Sparse array and Dense array
95How does the length property behave in dense vs sparse arrays in JavaScript

1. What is JavaScript

  • JavaScript is a scripting language used to create dynamic and interactive websites. It is supported by all major web browsers.
  • JavaScript is basically a client-side scripting language but it can also be used on the server-side with the help of technologies such as Node.js.

🔝 Scroll to Top

2. What are the different data types in JavaScript

PrimitiveNon-primitive
Boolean, NULL, undefined, BigInt, String, Number, SymbolObject, Array

🔝 Scroll to Top

3. What are the different ways to create an Object in JavaScript

a) Object Literals: A comma-separated set of name and value pairs that is wrapped inside curly braces.
varperson={name:'Surbhi',age:25,occupation:'Software Engineer'}
b) Object.create method: It Creates a new object, by using an existing object as the prototype of the newly created object.
constperson={name:'Surbhi',age:25,occupation:'Software Engineer'}varinfo=Object.create(person);console.log(info.name);// output - Surbhi
c) Object constructor: Constructor function allows to create objects with the help of new keyword
constperson=newPerson();
d) using ES6: We can create object using ES6 class feature
classPerson{constructor(name){this.name=name;}}letperson=newPerson('Surbhi');console.log(person.name);//output - Surbhi

🔝 Scroll to Top

4. Difference between “==” and “===” operators

  • == : While comparing two operands, checks for only value
console.log(1=="1");// output=>>>>>>>>> true
  • === : While comparing two operands, checks for value as well as data type
console.log(1==="1");// output=>>>>>>>>> false

🔝 Scroll to Top

5. Is javascript single-threaded or multi-threaded

  • JavaScript is Single-threaded

🔝 Scroll to Top

6. What are arrow functions and its features

Arrow functions were introduced in ES6 (ECMAScript 2015) and provide a simpler and compact way to write functions. They are also called “fat arrow functions”

Syntax
constfunctionName=(something)=>{returnsomething;}
Features of arrow functions
  1. They use a concise syntax which makes them shorter and easier to read as compared to traditional function expressions
  2. They do not bind their own this value, but instead inherit the this value from the enclosing lexical scope
  3. They do not have "prototype" property and hence cannot be used as a constructor
  4. If the arrow function body consists of a single expression, that expression will be implicitly returned, without the need for a return statement.
  5. If an arrow function has only one parameter, the parentheses around the parameter list can be omitted.

🔝 Scroll to Top

7. What do you mean by Synthetic events

Synthetic events are objects that act as a cross-browser wrapper around a browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

🔝 Scroll to Top

8. What is array destructuring

Array destructuring is a unique feature in JavaScript that allows you to extract array's value into new variables. For e.g.,

constarr=[1,2,3];const[num1,num2,num3]=arr;console.log(num1);// output =====> 1console.log(num2);// output =====> 2

🔝 Scroll to Top

9. Can we combine two arrays using any es6 operators

  • Yes, using Spread Operators
constarr1=[1,2,3,4];constarr2=[5,6];constarr3=[...arr1, ...arr2]console.log(arr3)// output =====> [1,2,3,4,5,6]

🔝 Scroll to Top

10. Why javascript is dynamically typed language

JavaScript is a dynamically typed language, because the type of a variable is determined at runtime based on the value it holds. For e.g.,

varvariable_one="surbhi"// "string" datatype is determined at runtimevarvariable_two=20// "number" datatype is determined at runtime

🔝 Scroll to Top

11. Difference between Undeclared and Undefined

Undeclared - A variable that has not been declared or doesn't exists in the code

console.log(a);// output =====> ReferenceError: a is not defined

Undefined - A variable that has been declared but not assigned a value yet

leta;console.log(a);// output =====> undefined

🔝 Scroll to Top

12. Difference between Null and Undefined

Null - Null means an empty value or a blank value. It is used to represent an intentional absence of value.

letdemo=null;console.log(demo);// output =====> null

Undefined - Undefined means the variable has been declared, but its value has not been assigned yet.

letdemo;console.log(demo);// output =====> undefined

🔝 Scroll to Top

13. What is Temporal Dead Zone

A "let" or "const" variable is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the line where the variable is declared and initialized.

In JavaScript, variables declared with let or const are hoisted to the top of the block scope, but they enter a "Temporal Dead Zone" (TDZ).

{// TDZ for name variable starts hereconsole.log(name);// ReferenceErrorletname="surbhi";// End of TDZ for name}

🔝 Scroll to Top

14. What is IIFE

IIFE stands for Immediately Invoked Function Expression. It is a JavaScript function that is executed as soon as it is defined.

An IIFE is typically written as an anonymous function expression that is enclosed within a set of parentheses, followed by another set of parentheses that call the function. For e.g.,

(function(){// code goes here})();

🔝 Scroll to Top

15. What is Hoisting

Hoisting is a default behavior in JavaScript where variable and function declarations are moved to the top of the current scope

Variable hoisting

console.log(a);// output =====> undefinedvara=10;
a=10;console.log(a);// output =====> 10vara;

Function hoisting

demo();// demo consolefunctiondemo(){console.log('demo console');}
**Note**+ Only function declarations are hoisted, not the function expressions.+ Only the declaration is hoisted, not the initialization.

🔝 Scroll to Top

16. What are Cookies

In javascript, a cookie is a piece of data, stored in small text files, on the user's computer by the browser.Cookies are set, read and deleted using the document.cookie property

//**Set a cookie**document.cookie="username=surbhi";//**Read a cookie**letcookie_variable=document.cookie;//**Delete a cookie** (set the expiration date to a past date/time)document.cookie="username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

🔝 Scroll to Top

17. What is memoization

Memoization is a technique used in JavaScript to optimize the performance of functions by caching the results of expensive function calls, based on their input parameters.For e.g., If a function is called multiple times with the same input parameters, then it will perform the same calculations each time. By memoizing the function, we can use the cached result.

functionmemoizedAdd(num1,num2){letcache={};returnfunction(a,b){constkey=num1+' and '+num2;if(keyincache){console.log('Retrieving from cache:',key);returncache[key];}else{console.log('Calculating result:',key);constresult=num1+num2;cache[key]=result;returnresult;}};}constadd=memoizedAdd();console.log(add(2,3));// "Calculating result:", "2 and 3", output ========> 5console.log(add(2,3));// "Retrieving from cache:", "2 and 3" output ========> 5

🔝 Scroll to Top

18. Difference between var, let and const

In javascript, there are 3 ways to declare a variable - var, let, and const. However, they have some differences in their behavior and scope.

varletconst
Function scopedBlock scopedBlock scoped
Can be re-declared in the same scopeCan not be re-declared in the same scopeCan not be re-declared in the same scope
Can be updated in the same scopeCan be updated in the same scopeCan not be updated in the same scope
Hoisted to the top of their scopeHoisted to the top but are not initializedHoisted to the top but are not initialized
Can be declared without being initializedCan be declared without being initializedCan not be declared without being initialized

🔝 Scroll to Top

19. What is a callback function

A callback function is a function that is passed as an argument to another function. The function that receives the callback as an argument can then invoke the callback at any time during its execution.

functionmessage(callback){console.log('Hi, i am message function');callback();}// callback functionfunctioncallBackFun(){console.log('Hey, I am a callback function');}// passing callback function as an argument to message functionmessage(callBackFun);

🔝 Scroll to Top

20. Is it possible to have both local and global variables with the same name

Yes, we can have both with the same name. But when we do this, the local variable will take precedence over the global variable within the scope of the function or block of code in which it is declared.

However, outside of that scope, the global variable will still be accessible using its name.

leta=10;functionDemo(){leta=20;console.log(a,"local scope");}Demo();console.log(a,"global scope");

🔝 Scroll to Top

21. Difference between Local Storage and Session Storage

Local storage and session storage are web storage provided by web browsers to store data on the client-side

Local Storage - Data stored in local storage will persist even after the browser window is closed or the user navigates away from the website and it is available across all windows and tabs of the same origin.

Session Storage - Data stored in session storage will be deleted when the browser window is closed or the session ends and it is available only within the same window or tab that created the data.

🔝 Scroll to Top

22. Difference between forEach() and map()

map() and forEach() are array methods that can be used to iterate over an array.map()

  1. map() method receives a function as an argument, executes it once for each array element and returns a new array
  2. It is generally used when we need to modify/change data, because it returns a new array with the transformed data
  3. It is chainable because we can attach sort(), filter() etc. after performing a map() method on an array
constarr=[1,2,3,4,5]letresult=arr.map(x=>x*x)console.log(result)// output ========> [1,4,9,16,25]

forEach()

  1. forEach() method receives a function as an argument, executes it once for each array element but returns undefined.
  2. It is generally used when we just need to iterate over an array
  3. It is not chainable
constarr=[1,2,3,4,5]letresult=arr.forEach(x=>x*x)console.log(result)// output ========> undefined

🔝 Scroll to Top

23. What is rest operator

  1. The rest operator was introduced in ES6 (ECMAScript 2015) and it is represented by three dots (...)
  2. It is used in function parameters and allows you to represent an indefinite number of arguments as an array
functionaddition(...numbers){returnnumbers.reduce((a,b)=>a+b);}console.log(addition(1,2,3,4));// output ========> 10
  1. It collects all the remaining arguments passed to a function into an array
functionprofile(name,designation,...location){returnlocation}console.log(profile("surbhi","SE","India","Indore","M.P"));// output ========> ["India", "Indore", "M.P"]

🔝 Scroll to Top

24. What is spread operator

  1. The spread operator was introduced in ES6 (ECMAScript 2015) and it is represented by three dots (...)
  2. It allows an iterable to be spread into individual elements
constarr=[1,2,3,4,5];console.log(...arr);// output ======> 1, 2, 3, 4, 5
  1. It can be used to copy the elements of an existing array into a new array, or to concatenate arrays
constarr1=[1,2,3];constarr2=[4,5,6];constarr3=[...arr1, ...arr2];console.log(arr3);// output =======> [1, 2, 3, 4, 5, 6]
  1. It can be used to copy the properties of an existing object into a new object
constobj1={a:1,b:2};constobj2={c:3};constobj3={ ...obj1, ...obj2};console.log(obj3);// output ========> { a: 1, b: 2, c: 3 }

🔝 Scroll to Top

25. Difference between async and defer

async and defer are the attributes used with the script tag in HTML to load javaScript files.

Async - The script is loaded in parallel to the HTML parsing, and executed as soon as it is available i.e., it executes the script immediately after it is loaded. It can be useful for scripts that don't depend on the DOM.

Defer - The script is loaded in parallel to the HTML parsing, and executed after the page is completely loaded i.e., it waits until the page has finished parsing. It can be useful for scripts that depend on the DOM.

🔝 Scroll to Top

26. What is Nullish coalescing operator

  1. The nullish coalescing (??) operator is a logical operator
  2. It allows you to check if a value is either null or undefined
  3. It returns its right-hand side operand if its left-hand side operand is null or undefined, otherwise returns its left-hand side operand
console.log((null||undefined)??"foo");// output ========>  "foo"console.log("hello"??"foo");// output ========>  "hello"

🔝 Scroll to Top

27. What is the difference between a parameter and an argument

Parameter - A parameter is a variable that is defined during a function declaration or definition. It represents a value that the function or method expects to receive as an input.

Argument - An argument is the actual value that is passed to a function or method when it is called.

functionDemo(parameter1,parameter2){something------something------}Demo(argument1,argument2);

🔝 Scroll to Top

28. What is a closure

A closure is a combination of a function and the environment in which it was created(lexical scope). It gives you access to an outer function's scope from an inner function even if the outer function has returned

functionDemo(){letname="Surbhi";functiondisplayName(){console.log(name);}returndisplayName;}constresult=Demo();result();

🔝 Scroll to Top

29. Difference between function declaration and function expression

Function Declaration

  1. A function declaration defines a function using the function keyword, followed by the function name
  2. We can call a function, declared using a function declaration, before it is defined. Because it is hoisted to the top of its scope
  3. It does not require a variable assignment
functionMessage(){console.log("Welcome Message");// output ========> Welcome Message}Message();

Function Expression

  1. A function Expression is similar to a function declaration without the function name
  2. We can not call a function, declared using a function expression, before it is defined
  3. It can be stored in a variable assignment
constMessage=function(){console.log("Welcome Message");// output ========> Welcome Message}Message();

🔝 Scroll to Top

30. What are the different ways to create an array in javascript

  1. Using the array literal notation
constarr=[1,2,3,4,5];
  1. Using the Array() constructor
constarr=newArray(1,2,3,4,5);

🔝 Scroll to Top

31. Difference between window and document in javascript

window object - window is the topmost object. It represents the browser window or tab containing a DOM document. It provides various properties and methods to manipulate the browser window, such as window.alert(), window.confirm(), and window.location.

document object - document represents the HTML document that is being displayed in the window. It provides properties and methods to manipulate the HTML elements in the document, such as document.title, document.getElementById(), and document.createElement().

🔝 Scroll to Top

32. What is strict mode in JavaScript

  1. Strict mode was introduced in ECMAScript 5
  2. It performs additional checks on your code to prevent certain types of bugs and errors that may go unnoticed e.g., using undeclared variables, using duplicate property names in objects
  3. It can be enabled at either the global level or at the function level
  4. It can't be apply to block statements enclosed in {} braces
  5. To invoke strict mode, put the exact statement “use strict”; or ‘use strict’;

🔝 Scroll to Top

33. What are the different ways to empty an array in javaScript

Using length property

letarr=[1,2,3,4,5];arr.length=0;console.log(arr);// output ========> []

Assigning it to a new empty array

letarr=[1,2,3,4,5];arr=[];console.log(arr);// output ========> []

Using the splice() method

letarr=[1,2,3,4,5];arr.splice(0,arr.length);console.log(arr);// output ========> []

🔝 Scroll to Top

34. What is NaN in javascript

  1. In Javascript, NaN stands for "Not a Number"
  2. It is a global property that represents an unrepresentable mathematical result
  3. It is returned when a mathematical operation has no meaningful result. E.g., dividing zero by zero, multiplying/dividing a non-numeric value by a number etc.
console.log(0/0);// output ========> NaNconsole.log("a"*1);// output ========> NaNconsole.log("a"/1)// output ========> NaNconsole.log(Math.sqrt(-1));// output ========> NaNconsole.log(parseInt("blabla"));// output ========> NaN

🔝 Scroll to Top

35. Javascript naming convention

  1. Use camelCase (lowercase for the first word, then uppercase for subsequent words) for variable and function names
  2. Use PascalCase for class names (uppercase for the first letter of each word)
  3. Use "is" or "has" as prefixes for boolean variables
  4. Use UPPERCASE for constants
  5. Use descriptive and meaningful names for your variables, functions, and classes.
//variableletfirstName="Surbhi";//functionfunctiondisplayName(){return"Surbhi Dighe";}displayName();//booleanletisLoading=false;lethasName=true;//constantsletSECONDS=60;//classclassDisplayName{constructor(firstName,lastName){this.firstName=firstName;this.lastName=lastName;}}varname=newDisplayName('Surbhi','Dighe');

🔝 Scroll to Top

36. Difference between call(), apply() and bind()

call(), apply(), and bind() methods are used to attach a function into an object and call the function as if it belonged to that object.

call() - call() is used to invoke a function immediately with a specifiedthis value and allows you to pass the arguments one by one

letperson={name:'Surbhi'};functionprintName(message){console.log(message+' '+this.name);// output ========> "Hello Surbhi"}printName.call(person,'Hello');

apply() - apply() is used to invoke a function immediately with a specifiedthis value and allows you to pass the arguments as an array

letperson={name:'Surbhi'};functionprintName(message){console.log(message+' '+this.name);// output ========> "Hello Surbhi"}printName.apply(person,['Hello']);

bind() - bind() returns a new function (which can be invoked anytime), with a specifiedthis value and allows you to pass in arguments

letperson={name:'Surbhi'};functionprintName(message){console.log(message+' '+this.name);// output ========> "Hello Surbhi"}letsayHello=printName.bind(person,"Hello");sayHello();

🔝 Scroll to Top

37. What is the use of isNaN function

isNaN() is a built-in JavaScript function. It takes a single argument and returns true if the argument is not a number, otherwise it returns false.

letnum1=5;letnum2="hi";console.log(isNaN(num1));// output ========> falseconsole.log(isNaN(num2));// output ========> true

🔝 Scroll to Top

38. What is 'this' keyword in javascript

The value of 'this' is determined by the context in which it is used. In general, 'this' keyword refers to the object it belongs to.The 'this' keyword in JavaScript can have different values depending on where it is used -

  1. If it is used inside a method, then it refers to the object that it belongs to
  2. If it is used inside any function or alone (i.e outside any function or method), then it referes to the global object
  3. If it is used in the context of an event handler, such as a click event, then it refers to the element that triggered the event

🔝 Scroll to Top

39. How do we add comments in javascript

Single-line comments - Add comments using 2 forward slashes //

// this is a single line comment

Multi-line comments - Enclose the text between /* and */

/*This is amultiline commentexample*/

🔝 Scroll to Top

40. What is the use of typeof operator

The typeof operator returns a string that indicates the data type of the variable/value.

letvar1="Surbhi";letvar2=10;console.log(typeofvar1);// output ========> "string"console.log(typeofvar2);// output ========> "number"

🔝 Scroll to Top

41. Is JavaScript case-sensitive

Yes, JavaScript is a case-sensitive language. For e.g., the variables firstName and firstname are considered to be two different variables.

letfirstName="Surbhi";console.log(firstname);// output ========> Uncaught ReferenceError: firstname is not defined

🔝 Scroll to Top

42. Difference between push() and unshift()

Both are used to add elements to an array, but they add elements in different ways.

push() - It adds one or more elements to the end of an array and returns the new length of the array.

letarr=[1,2,3,4];letnewArr=arr.push(5,6,7);console.log(newArr);// output ========> 7console.log(arr);// output ========> [1, 2, 3, 4, 5, 6, 7]

unshift() - It adds one or more elements to the beginning of an array and returns the new length of the array.

letarr=[1,2,3,4];letnewArr=arr.unshift(5,6,7);console.log(newArr);// output ========> 7console.log(arr);// output ========> [5, 6, 7, 1, 2, 3, 4]

🔝 Scroll to Top

43. Difference between pop() and shift()

Both are used to remove elements from an array, but they remove elements in different ways.

pop() - It removes the last element of an array and returns the removed element.

letarr=[1,2,3,4];letnewArr=arr.pop();console.log(newArr);// output ========> 4console.log(arr);// output ========> [1,2,3]

shift() - It removes the first element of an array and returns the removed element.

letarr=[1,2,3,4];letnewArr=arr.shift();console.log(newArr);// output ========> 1console.log(arr);// output ========> [2,3,4]

🔝 Scroll to Top

44. Different ways to access DOM elements in js

getElementById - This method is used to get an element by its ID.

getElementsByClassName - This method is used to get a collection of elements by their class name.

getElementsByTagName - This method is used to get a collection of elements by their tag name.

querySelector - This method is used to get the first element that matches a specified CSS selector.

querySelectorAll - This method is used to get a collection of elements that match a specified CSS selector.

🔝 Scroll to Top

45. What are promises

In JavaScript, promises are used to handle asynchronous operations. The code does not directly or immediately return a value. Instead, it returns a promise that, it will eventually get resolved or rejected.A promise can have three possible states:

Pending - The initial state, before the promise is resolved or rejected.

Resolved - When a promise has been successfully completed and a value is returned.

Rejected - When a promise has been failed and an error is returned.

letpromise=newPromise((resolve,reject)=>{constresult=AsynchronousTaskFunction();if(result){resolve(result);}else{reject(newError('Operation failed'));}});promise.then(result=>{console.log(result,"It is resolved");}).catch(error=>{console.error(error,"It is rejected");});

🔝 Scroll to Top

46. What is a prototype

Every object in JavaScript has a built-in property, which is called its prototype. All JavaScript objects inherit properties and methods from a prototype.

It allows us to add properties and methods to all instances of a given object type.

functionPerson(name,age){this.name=name;this.age=age;}Person.prototype.city="Indore"varperson1=newPerson('John',30);console.log(person1);

🔝 Scroll to Top

47. What is a callback hell

Callback hell is a situation in which callback functions are nested inside each other at several levels, making the code difficult to read, write, and maintain.

asyncFunc1(function(response1){asyncFunc2(response1,function(response2){asyncFunc3(response2,function(response3){asyncFunc4(response3,function(response4){asyncFunc5(response4,function(response5){// ... and so on});});});});});

🔝 Scroll to Top

48. What is an event loop

The event loop is a key mechanism in JavaScript that provides an illusion of being multithreaded despite being single-threaded, allowing for non-blocking, asynchronous processing of events and callbacks.It monitors both the callback queue and the call stack.

If the call stack is not empty, the event loop waits until it is empty

If the call stack is empty it places the next function from the callback queue to the call stack

🔝 Scroll to Top

49. ES6 and its features

ES6 stands for ECMAScript 6, also known as ECMAScript 2015. It is the sixth major version of the ECMAScript language specification for JavaScript. Below are some of the significant features of ES6

Arrow functions, template literals, block-scoped variables (let and const), default function parameters, array and object destructing, promises, rest and spread operators, classes.

🔝 Scroll to Top

50. Difference between function and method

method - A method is a function associated with an object.

letobj={name:"Surbhi",greet:function(){return`Hi${this.name}`}}console.log(obj.greet());

function - A function is a self-contained block of code that can be defined and called independently of any object.

functionsum(a,b){returna+b;}sum(2,4);

🔝 Scroll to Top

51. What is aync and await

async/await is a feature in JavaScript that allows us to write asynchronous code that looks more like synchronous code. "await" works only inside "async" functions

"async" ensures that a function returns a promise and "await" pause the execution of the function until a promise is resolved or rejected.

constgetData=async()=>{constresponse=awaitfetch('https://api.openweathermap.org/data/2.5/weather?q=New%20York&appid=YOUR_API_KEY');constdata=awaitresponse.json();console.log(data);}getData();

🔝 Scroll to Top

52. What is the role of event.preventDefault()

The preventDefault() method is used to stop the default action of an element.

E.g., when a user submits a form, the browser sends the form data to the URL specified in the action attribute. In some cases, we may want to prevent this default behavior.

🔝 Scroll to Top

53. What is the use of JSON.stringify()

JSON.stringify() method is used to convert a JavaScript object or value into an equivalent JSON string.

constobj={firstname:"Surbhi",lastname:"Dighe"};constjsonString=JSON.stringify(obj);console.log(jsonString);// output ========> {"firstname":"Surbhi","lastname":"Dighe"}

🔝 Scroll to Top

54. How can you stop the setTimeout

You can use the clearTimeout method. This method takes the id returned by setTimeout and cancels the timer.

consttimerId=setTimeout(()=>{console.log('setTimeout is done');},5000);clearTimeout(timerId);

🔝 Scroll to Top

55. If Javascript is single threaded, how it supports asynchronous operations

JavaScript is single-threaded, means it can execute only one task at a time. Still, it supports asynchronous operations using the Web API provided by the browser.

🔝 Scroll to Top

56. What is javascript scope

In JavaScript, scope refers to the current context of your code. This context determines visibility and accessibility of variables, functions, and objects within a certain part of the code.Generally, there are two types of scope in JavaScript - global scope and local scope.

🔝 Scroll to Top

57. Difference between global scope and local scope

Global scope - Global scope refers to the variables, functions, and objects that are defined outside of any function or block. They can be accessible from any part of the code.

letname="Surbhi";functionprintName(){console.log(name);// output ========> Surbhi}printName();

Local scope - Local scope refers to the variables, functions, and objects that are defined inside any function or block. They can be accessible only within the function or block where they are defined.

functionprintName(){letname= "Surbhi;console.log(name);// output ========> Surbhi}printName();console.log(name);// ReferenceError: name is not defined

🔝 Scroll to Top

58. What are the different ways to convert a string to an integer

1. parseInt() - This function takes a string and an optional radix (a number between 2 and 36 that represents the base in a numeral system) as its arguments.

console.log(parseInt("20"));// output ========> 20console.log(parseInt("52",8));// output ========> 42

2. unary plus operator (+) - This operator converts a string into a number and it should be placed before the operand.

console.log(+"10");// output ========> 10

3. Number() - It is a built-in function which converts its argument to a number. If the argument is a string that contains non-numeric characters, then it returns NaN.

Number("10");// output ========> 10Number("abc");// output ========> NaN

🔝 Scroll to Top

59. How to find the operating system in the client machine using JavaScript

We can use thenavigator.platform property to find out the operating system of the client machine

console.log(navigator.platform);// output ========> 'Linux x86_64'

🔝 Scroll to Top

60. Name some JavaScript frameworks and libraries

Frameworks - Angular, Ember.js, Vue.js, Meteor, Next.js

Libraries - React, Backbone.js

🔝 Scroll to Top

61. What is event bubbling and event capturing

Event bubbling and Event Capturing are two different mechanisms used for handling event propagation in the HTML DOM API. When an event is triggered on an element which is inside another element, and both elements have an event listener attached to them , the event propagation mode determines the order in which the elements receive the event.

Event Bubbling - The event is first triggered on the innermost element and then propagated/bubbles up to its parent elements and eventually to the outermost element in the DOM hierarchy.

Event Capturing - The event is first triggered on the outermost element and then propagated/bubbles down to its child elements and eventually to the innermost element in the DOM hierarchy.

🔝 Scroll to Top

62. What is the role of event.stopPropagation()

This method is used to stop the event from propagating up or down the DOM hierarchy.

🔝 Scroll to Top

63. How can we change the style of an element using javascript

To change the style of an element using JavaScript, we can use the style property of the element's DOM object.

document.getElementById("myDiv").style.backgroundColor="red";

🔝 Scroll to Top

64. What is object destructuring

Object destructuring allows you to extract properties from an object and assign them to variables.

constfullname={firstName:'Surbhi',lastName:'Dighe',};const{ firstName, lastName}=fullname;console.log(firstName);// output ========> 'Surbhi'console.log(lastName);// output ========> 'Dighe'

🔝 Scroll to Top

65. Difference between an Alert Box and a Confirmation Box

Alert Box - It has only one button, typically labeled "OK" and it is used to display a message to the user.

Confirmation Box - It has two buttons, typically labeled "OK" and "Cancel" and it is used to ask the user to confirm an action.

🔝 Scroll to Top

66. How can we handle exceptions with javascript

In JavaScript, we can handle exceptions using a try-catch block. The try block contains the code that might throw an exception, and the catch block contains the code that handles the exception if it occurs.

try{constname="Surbhi";console.log(firstname)}catch(error){console.log("Error: "+error);// output ========> Error: ReferenceError: firstname is not defined}

🔝 Scroll to Top

67. What are the advantages of using External JavaScript

  • Improve the load time of web pages
  • Ease of editing
  • Code reusability
  • Separation of Code

🔝 Scroll to Top

68. What is an anonymous function

An anonymous function is a function that does not have a name. It is common to assign anonymous functions to a variable or use them as callback functions.

constsayHi=function(){console.log("Hi there!!");};sayHi();

🔝 Scroll to Top

69. What is a first order function

A first order function is a function that does not take any other functions as arguments and does not return any function as its result.

functionsayHello(){console.log("A first order function")}sayHello();

🔝 Scroll to Top

70. Different ways to access object properties in javascript

Dot notation - It uses dot (.) to access the object properties.

object.propertyName

Bracket notation - It uses bracket "[ ]" to access the object properties.

object[propertyName]

Object destructuring - It creates variables that correspond to the object properties.

constobj1={name :"surbhi",designation :"SE"}const{name, designation}=obj1;console.log(name,designation)// output ========> "Surbhi","SE"

🔝 Scroll to Top

71. Difference between slice() and splice()

slice() - This method creates a new array by copying a specified section of an existing array and returns that new array. This operation does not modify the original array in any way.

constarr=[1,2,3,4,5];constresult=arr.slice(2)console.log(arr);// output ========> [1, 2, 3, 4, 5]console.log(result);// output ========> [3, 4, 5]

splice() - This method is used to add or remove elements from an array. It modifies the original array and returns an array containing the removed elements (if any).

constarr=[1,2,3,4,5];constresult=arr.splice(2)console.log(arr);// output ========> [1, 2]console.log(result);// output ========> [3, 4, 5]

🔝 Scroll to Top

72. What are the escape characters in JavaScript

When working with special characters such as ampersands (&), apostrophes ('), double quotes (" "), and single quotes (' '). JavaScript requires the use of escape characters, which are often represented by the backslash (). These escape characters instruct JavaScript to interpret the special characters correctly.Below are some common escape characters in #"auto">

  • \n - Represents a newline character.
  • \t - Represents a tab character.
  • ' - Represents a single quote character.
  • " - Represents a double quote character.
  • \ - Represents a backslash character.
  • \r - Represents a carriage return character.
  • 🔝 Scroll to Top

    73. Different ways to redirect a page in javascript

    location.href - It is used to navigate to a new page and add it to the browser's history.

    window.location.href="https://www.example.com";

    location.replace - It is used to replace the current page with a new page without adding it to the history.

    window.location.replace("https://www.example.com");

    🔝 Scroll to Top

    74. What is the difference between innerHTML and innerText

    innerHTML retrieves or modifies the HTML content of an element, including its tags, while innerText only retrieves or modifies the text content of an element, excluding any HTML tags.

    //HTML code<divid="example">Hello<strong>world</strong>!</div>//Javascript codeletresult=document.getElementById("example").innerHTML;console.log(result);// output ========> "Hello <strong>world</strong>!"
    //HTML code<divid="example">Hello<strong>world</strong>!</div>//Javascript codeletresult=document.getElementById("example").innerText;console.log(result);// output ========> "Hello world!"

    🔝 Scroll to Top

    75. How can you get current time using js

    To get the current time using JavaScript, you can use the built-in Date object.

    letcurrentTime=newDate();lethours=currentTime.getHours();letminutes=currentTime.getMinutes();letseconds=currentTime.getSeconds();console.log(`Current time is${hours}:${minutes}:${seconds}`);// output ========> "Current time is 16:7:22"

    🔝 Scroll to Top

    76. What is currying

    Currying is the process of breaking down a function that takes multiple arguments into a series of functions that take a single argument.

    constadd=(a,b)=>{returna+b;}constcurryingAdd=(a)=>(b)=>a+b;console.log(add(5,4));// output ========> 9console.log(curryingAdd(5)(4));// output ========> 9

    🔝 Scroll to Top

    77. Difference between shallow copy and deep copy

    shallow copy - It creates a new object that points to the same memory location as the original object. Therefore, any changes made to the original object will also be reflected in the shallow copy. It can be done using the spread operator or object.assign() method.

    deep copy - It creates a completely new object with its own memory space. This means that any changes made to the original object will not be reflected in the deep copy. It can be done using the JSON.parse() and JSON.stringify() methods.

    🔝 Scroll to Top

    78. What is a service worker

    A service worker is a kind of web worker that operates in the background of a web page, decoupled from the primary browser thread, and capable of executing diverse tasks. It is essentially a JavaScript file that is associated with a web page and executes independently, without depending on the user interface.

    🔝 Scroll to Top

    79. What is JSON

    JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.

    {"users":[{"name":"Test1","age":"20"},{"name":"Test2","age":"30"},{"name":"Test3","age":"40"}]}

    🔝 Scroll to Top

    80. How can you get all the keys of any object

    The Object.keys() method returns an array containing all the keys of the object

    constobj1={name:'Surbhi',city:'Indore'};constkeys=Object.keys(obj1);console.log(keys);// output ========> ["name", "city"]

    🔝 Scroll to Top

    81. What is a unary function

    A unary function is a function that takes only one argument

    functiongreet(message){console.log(message,"unary function example");}

    🔝 Scroll to Top

    82. What is promise chaining

    Promise chaining is the term used to describe the process of executing a series of asynchronous tasks one after another in a specific order

    fetch('API_URL').then(response=>response.json()).then(data=>printData(data)).then(anotherData=>printAnotherData(anotherData)).then(finalData=>printFinalData(finalData))

    🔝 Scroll to Top

    83. What is eval

    The eval() is a method of the JavaScript global object and it takes a string as an argument and evaluates it.

    console.log("10"+"20");// output ========> 30

    🔝 Scroll to Top

    84. How can you assign default values to variables

    You can assign default values to variables using the || operator. If the variable on the left-hand side of the || operator is falsy (e.g. null, 0, undefined, NaN, empty string, false), the expression on the right-hand side of the || operator will be returned.

    constvar1=undefined||'default value';console.log(var1);// output ========> "default value"
    constvar1="surbhi"||'default value';console.log(var1);// output ========> "surbhi"

    🔝 Scroll to Top

    85. How to determine if an object is extensible or not

    Object.isExtensible() method is used to determine if an object is extensible or not. It returns true if new properties can be added to the object otherwise it returns false.

    constobj1={name:'surbhi'};console.log(Object.isExtensible(obj1));// output ========> true

    🔝 Scroll to Top

    86. In how many ways we can make an object non-extensible

    • Object.preventExtensions()
    • Object.seal()
    • Object.freeze()

    🔝 Scroll to Top

    87. What is object.freeze method

    • Object.freeze makes the object immutable
    • Can not add new properties to existing object
    • Can not delete or modify existing properties
    constobj={property1:'value 1',property2:'value 2',};Object.freeze(obj);obj.property1='new value';// This will not modify the existing propertyobj.property3='value 3';// This will not add new property to the objectconsole.log(obj);// output ========> { property1: "value 1", property2: "value 2" }

    🔝 Scroll to Top

    88. What is object.seal method

    • Object.seal makes the object immutable
    • Can not add new properties or delete existing properties
    • Can modify existing properties.
    constobj={property1:'value 1',property2:'value 2',};Object.seal(obj);obj.property1='new value';// This will modify the existing propertyobj.property3='value 3';// This will not add new property to the objectconsole.log(obj);// output ========> { property1: "new value", property2: "value 2" }

    🔝 Scroll to Top

    89. How can you determine if JavaScript is disabled on a page

    <noscript> tag is used to determine if JavaScript is disabled on a page. It provides alternative content that should be displayed when JavaScript is not supported or disabled in the user's browser.

    <noscript><p>JavaScript is disabled in your browser.</p></noscript><script>console.log("JavaScript is enabled on page");</script>

    🔝 Scroll to Top

    90. How can you compare two date objects

    getTime() method is used to compare two date objects.

    letdate1=newDate();letdate2=newDate(date1);console.log(date1.getTime()<date2.getTime());// output ========> falseconsole.log(date1.getTime()>date2.getTime());// output ========> falseconsole.log(date1.getTime()===date2.getTime());// output ========> true

    🔝 Scroll to Top

    91. Does JavaScript support automatic type conversion

    Yes, JavaScript supports automatic type conversion. It refers to the implicit conversion of one data type to another by the JavaScript engine.

    🔝 Scroll to Top

    92. What is variable shadowing in javascript

    Variable shadowing means a variable declared in a local scope has the same name as a variable declared in an outer scope. The inner variable "shadows" the outer variable and the outer variable is said to be shadowed.

    letx=10;functionDemo(){letx=20;console.log(x);// output ========> 20}myFunction();console.log(x);// output ========> 10

    🔝 Scroll to Top

    93. What is ternary operator

    The ternary operator is a shorthand conditional operator that allows you to write a compact if-else statement in a single line.

    condition ?expression1 :expression2;

    It is evaluated from left to right. If the condition is true, the result of the entire expression is expression1, otherwise it's expression2.

    letnumber=20;letresult=number>=15 ?"output 1" :"output 2";console.log(result);// output ========> output 1

    🔝 Scroll to Top

    94. Difference between Sparse array and Dense array

    Sparse Array - An array that has "holes" i.e some indices are unassigned or missing.

    constsparse=[1,,3];// index 1 is empty

    Dense Array - An array where every index has an assigned value, with no gaps.

    constdense=[1,2,3];

    🔝 Scroll to Top

    95. How does the length property behave in dense vs sparse arrays in Javascript

    Sparse Array - "length" is highest index + 1, even if some spots are empty.

    constsparse=[1,,3];console.log(sparse.length);// output ========> 3ORconstarr=[];arr[100]=5;console.log(arr.length);// output ========> 101 (index 100 has the value 5, while indices 0–99 are empty)

    Dense Array - "length" equals the number of elements.

    constdense=[1,2,3];console.log(dense.length);// output ========> 3

    🔝 Scroll to Top

    Releases

    No releases published

    Packages

    No packages published

    [8]ページ先頭

    ©2009-2025 Movatter.jp