JavaScript Core Language, V8 Engine & Runtime Mechanics Master Interview Bank
V8 engine pipeline (Ignition & TurboFan), Event Loop (microtasks vs macrotasks), closures, prototypal inheritance, lexical scope, garbage collection, and async execution.
Curriculum Roadmap & Learning Path
8 StagesPart 1: Core Objects, Prototypes, Functions & Scope (1 - 53)
53 QuestionsWhat is JavaScript, and what are its core architectural characteristics?
JavaScript is a high-level, dynamically typed, single-threaded, prototype-based, multi-paradigm interpreted (JIT-compiled) programming language.
What are the primitive and reference data types in JavaScript, and how are they stored in memory?
JavaScript divides data types into two primary categories: Primitives (immutable values stored directly by value in Call Stack memory) and Reference Types (mutable objects stored in Heap memory, with stack pointers referencing their heap addresses).
What is the difference between JavaScript and ECMAScript?
ECMAScript (ECMA-262) is the official specification and standardized language definition created and maintained by the Ecma International • JavaScript is a concrete programming language and implementation of the ECMAScript standard, enhanced with host environment APIs.
What are the possible ways to create objects in JavaScript
Object literal syntax.
What is a prototype chain
The prototype chain is a core concept in JavaScript’s inheritance model. It allows objects to inherit properties and methods from other objects. When you try to access a property or method on an object, JavaScript first looks for it on that object itself.
What is the Difference Between call, apply, and bind
In JavaScript, call, apply, and bind are methods that allow you to control the context (this value) in which a function is executed. While their purposes are similar, they differ in how they handle arguments and when the function is invoked.
What is JSON and its common operations
JSON (JavaScript Object Notation) is a lightweight, text-based data format that uses JavaScript object syntax for structuring data. It was popularized by Douglas Crockford and is widely used for transmitting data between a server and a client in web applications.
What is the purpose of the array slice method
The slice() method in JavaScript is used to extract a section of an array, returning a new array containing the selected elements. It does not modify the original array. The method takes two arguments: start: The index at which extraction begins (inclusive) • end (optional): The index before which to end extraction (exclusive).
What is the purpose of the array splice method
The splice() method in JavaScript is used to add, remove, or replace elements within an array. Unlike slice(), which creates a shallow copy and does not alter the original array, splice() modifies the original array in place and returns an array containing the removed elements.
What is the difference between slice and splice
Here are the key differences between slice() and splice() methods in JavaScript arrays.
How do you compare Object and Map
Objects and Maps both allow you to associate keys with values, retrieve those values, delete keys, and check if a key exists. Historically, Objects have been used as Maps, but there are several key differences that make Map a better choice in certain scenarios.
What is the difference between == and === operators
JavaScript provides two types of equality operators: Loose equality (==, !=): Performs type conversion if the types differ, comparing values after converting them to a common type • Strict equality (===, !==): Compares both value and type, without any type conversion.
What are lambda expressions or arrow functions
Arrow functions (also known as "lambda expressions") provide a concise syntax for writing function expressions in JavaScript. Introduced in ES6, arrow functions are often shorter and more readable, especially for simple operations or callbacks.
What is a first class function
In JavaScript, first-class functions(first-class citizens) mean that functions are treated like any other variable. That means: You can assign a function to a variable • You can pass a function as an argument to another function • You can return a function from another function.
What is a first order function
A first-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value. i.e, It's a regular function that works with primitive or non-function values.
What is a higher order function
A higher-order function is a function that either accepts another function as an argument, returns a function as its result, or both. This concept is a core part of JavaScript's functional programming capabilities and is widely used for creating modular, reusable, and expressive code.
What is a unary function
A unary function (also known as a monadic function) is a function that accepts exactly one argument. The term "unary" simply refers to the function's arity—the number of arguments it takes.
What is the currying function
Currying is the process of transforming a function with multiple arguments into a sequence of nested functions, each accepting only one argument at a time.
What is a pure function
A pure function is a function whose output depends only on its input arguments and produces no side effects. This means that given the same inputs, a pure function will always return the same output, and it does not modify any external state or data.
What are the benefits of pure functions
Some of the major benefits of pure functions are listed below: Easier testing: Since output depends only on input, pure functions are simple to test • Predictability: No hidden side effects make behavior easier to reason about.
What is the purpose of the let keyword
The let keyword in JavaScript is used to declare a block-scoped local variable. This means that variables declared with let are only accessible within the block, statement, or expression where they are defined.
What is the difference between let and var
You can list out the differences in a tabular format.
What is the reason to choose the name let as a keyword
The keyword let was chosen because it originates from mathematical notation, where "let" is used to introduce new variables (for example, "let x = 5"). This term was adopted by several early programming languages such as Scheme and BASIC, establishing a tradition in computer science.
How do you redeclare variables in a switch block without an error
When you try to redeclare variables using let or const in multiple case clauses of a switch statement, you will get a SyntaxError. This happens because, in JavaScript, all case clauses within a switch statement share the same block scope. For example.
What is the Temporal Dead Zone
The Temporal Dead Zone (TDZ) refers to the period between the start of a block and the point where a variable declared with let or const is initialized. During this time, the variable exists in scope but cannot be accessed, and attempting to do so results in a ReferenceError.
What is an IIFE (Immediately Invoked Function Expression)
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The signature of it would be as below.
How do you decode or encode a URL in JavaScript?
encodeURI() function is used to encode an URL. This function requires a URL string as a parameter and return that encoded string. decodeURI() function is used to decode an URL. This function requires an encoded URL string as parameter and return that decoded string.
What is memoization
Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function.
What is Hoisting
Hoisting is JavaScript's default behavior where variable and function declarations are moved to the top of their scope before code execution. This means you can access certain variables and functions even before they are defined in the code.
What are classes in ES6
In ES6, JavaScript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below.
What are closures
A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution.
What are modules
Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor.
Why do you need modules
Below are the list of benefits using modules in javascript ecosystem.
What is scope in javascript
Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.
What is a service worker
A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don't need a web page or user interaction.
How do you manipulate DOM using a service worker
Service worker can't access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM.
How do you reuse information across service worker restarts
The problem with service worker is that it gets terminated when not in use, and restarted when it's next needed, so you cannot rely on global state within a service worker's onfetch and onmessage handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.
What is IndexedDB
IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.
What is web storage
Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user's browser, in a much more intuitive fashion than using cookies. The web storage provides two mechanisms for storing data on the client.
What is a post message
Post message is a method that enables cross-origin communication between Window objects.(i.e, between a page and a pop-up that it spawned, or between a page and an iframe embedded within it).
What is a Cookie
A cookie is a piece of data that is stored on your computer to be accessed by your browser. Cookies are saved as key/value pairs. For example, you can create a cookie named username as below.
Why do you need a Cookie
Cookies are used to remember information about the user profile(such as username). It basically involves two steps: When a user visits a web page, the user profile can be stored in a cookie • Next time the user visits the page, the cookie remembers the user profile.
What are the options in a cookie
By default, the cookie is deleted when the browser is closed but you can change this behavior by setting expiry date (in UTC time).
How do you delete a cookie
You can delete a cookie by setting the expiry date as a passed date. You don't need to specify a cookie value in this case. For example, you can delete a username cookie in the current page as below.
What are the differences between cookie, local storage and session storage
Below are some of the differences between cookie, local storage and session storage.
What is the main difference between localStorage and sessionStorage
LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.
How do you access web storage
The Window object implements the WindowLocalStorage and WindowSessionStorage objects which has localStorage(window.localStorage) and sessionStorage(window.sessionStorage) properties respectively.
What are the methods available on session storage
The session storage provided methods for reading, writing and clearing the session data.
What is a storage event and its event handler
The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events. The syntax would be as below.
Why do you need web storage
Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Also, the information is never transferred to the server. Hence this is a more recommended approach than Cookies.
How do you check web storage browser support
You need to check browser support for localStorage and sessionStorage before using web storage.
How do you check web workers browser support
You need to check browser support for web workers before using it.
Give an example of a web worker
You need to follow below steps to start using web workers for counting example.
Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)
50 QuestionsWhat are the restrictions of web workers on DOM
WebWorkers don't have access to below javascript objects since they are defined in an external files.
What is a promise
A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It acts as a placeholder for a value that may not be available yet but will be resolved in the future.
Why do you need a promise
Promises are used to handle asynchronous operations, especially in languages like JavaScript, which often work with non-blocking operations such as network requests, file I/O, and timers. When an operation is asynchronous, it doesn't immediately return a result; instead, it works in the background and provides the result later.
Explain the three states of promise
Promises have three states: Pending: This is an initial state of the Promise before an operation begins • Fulfilled: This state indicates that the specified operation was completed • Rejected: This state indicates that the operation did not complete.
What is a callback function
A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. Let's take a simple example of how to use callback function.
Why do we need callbacks
The callbacks are needed because javascript is an event driven language. That means instead of waiting for a response, javascript will keep executing while listening for other events. Let's take an example with the first function invoking an API call(simulated by setTimeout) and the next function which logs the message.
What is a callback hell
Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below.
What are server-sent events
Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only.
How do you receive server-sent event notifications
The EventSource object is used to receive server-sent event notifications. For example, you can receive messages from server as below.
How do you check browser support for server-sent events
You can perform browser support for server-sent events before using it as below.
What are the events available for server sent events
Below are the list of events available for server sent events.
What are the main rules of promise
A promise must follow a specific set of rules: A promise is an object that supplies a standard-compliant .then() method • A pending promise may transition into either fulfilled or rejected state • A fulfilled or rejected promise is settled and it must not transition into any other state.
What is callback in callback
You can nest one callback inside in another callback to execute the actions sequentially one by one. This is known as callbacks in callbacks. Beware, too many levels of nesting lead to Callback hell.
What is promise chaining
The process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining. Let's take an example of promise chaining for calculating the final result.
What is promise.all
Promise.all() is a built-in JavaScript method used to handle multiple asynchronous operations together. It accepts an iterable of promises (usually an array) and returns a single promise that resolves only when all the input promises have successfully resolved.
Does Promise.all() cancel the other Promises?
No. Promise.all() does not cancel the other promises. It only waits for all of them to finish, and if any one rejects, the overall Promise.all() call rejects immediately.
What is the purpose of the race method in promise
Promise.race() method will return the promise instance which is firstly resolved or rejected. Let's take an example of race() method where promise2 is resolved first.
What is a strict mode in javascript
JavaScript’s "use strict" directive is used to opt into a stricter parsing and error-handling mode for your scripts or functions. It helps catch common bugs, makes your code more secure, and prepares it for future versions of JavaScript.
Why do you need strict mode
Strict mode is useful to write "secure" JavaScript by notifying "bad syntax" into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a...
How do you declare strict mode
The strict mode is declared by adding "use strict"; to the beginning of a script or a function. If declared at the beginning of a script, it has global scope.
What is the purpose of double exclamation
The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, it will be true. For example, you can test IE version using this expression as below.
What is the purpose of the delete operator
The delete operator is used to delete the property as well as its value.
What is typeof operator
You can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression.
What is undefined property
The undefined property indicates that a variable has not been assigned a value, or declared but not initialized at all. The type of undefined value is undefined too.
What is null value
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values. The type of null value is object. You can empty the variable by setting the value to null.
What is the difference between null and undefined
Below are the main differences between null and undefined.
What is eval
The eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements.
What is the difference between window and document
Below are the main differences between window and document.
How do you access history in javascript
The window.history object contains the browser's history. You can load previous and next URLs in the history using back() and next() methods.
How do you detect caps lock key turned on or not
The mouseEvent getModifierState() is used to return a boolean value that indicates whether the specified modifier key is activated or not. The modifiers such as CapsLock, ScrollLock and NumLock are activated when they are clicked, and deactivated when they are clicked again.
What is isNaN
The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false.
What are the differences between undeclared and undefined variables
Below are the major differences between undeclared(not defined) and undefined variables.
What are global variables
Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable.
What are the problems with global variables
The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.
What is NaN property
The NaN property is a global property that represents "Not-a-Number" value. i.e, It indicates that a value is not a legal number. It is very rare to use NaN in a program but it can be used as return value for few cases.
What is the purpose of isFinite function
The isFinite() function is used to determine whether a number is a finite, legal number. It returns false if the value is +infinity, -infinity, or NaN (Not-a-Number), otherwise it returns true.
What is an event flow
Event flow refers to the order in which events are handled in the browser when a user interacts with elements on a webpage like clicking, typing, hovering, etc.
What is event capturing
Event capturing is a phase of event propagation in which an event is first intercepted by the outermost ancestor element, then travels downward through the DOM hierarchy until it reaches the target (innermost) element.
What is event bubbling
Event bubbling is a type of event propagation in which an event first triggers on the innermost target element (the one the user interacted with), and then bubbles up through its ancestors in the DOM hierarchy — eventually reaching the outermost elements, like the document or window.
How do you submit a form using JavaScript
You can submit a form using document.forms[0].submit(). All the form input's information is submitted using onsubmit event handler.
How do you find operating system details
The window.navigator object contains information about the visitor's browser OS details. Some of the OS properties are available under platform property.
What is the difference between document load and DOMContentLoaded events
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).
What is the difference between native, host and user objects
Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math, RegExp, Object, Function etc core objects defined in the ECMAScript spec. Host objects are objects provided by the browser or runtime environment (Node).
What are the tools or techniques used for debugging JavaScript code
You can use below tools or techniques for debugging javascript.
What are the pros and cons of promises over callbacks
Below are the list of pros and cons of promises over callbacks.
What is the difference between an attribute and a property
Attributes are defined on the HTML markup whereas properties are defined on the DOM. For example, the below HTML element has 2 attributes: type and value.
What is same-origin policy
The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number.
What is the purpose of void 0
Void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect, because it will return the undefined primitive value. It is commonly used for HTML documents that use href="JavaScript:Void(0);" within an `` element.
Is JavaScript a compiled or interpreted language
JavaScript is an interpreted language, not a compiled language. An interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. Nowadays modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.
Is JavaScript a case-sensitive language
Yes, JavaScript is a case sensitive language. The language keywords, variables, function & object names, and any other identifiers must always be typed with a consistent capitalization of letters.
Part 3: DOM, Event Flow, Timers & Browser APIs (104 - 173)
70 QuestionsIs there any relation between Java and JavaScript
No, they are entirely two different programming languages and have nothing to do with each other. But both of them are Object Oriented Programming languages and like many other languages, they follow similar syntax for basic features(if, else, for, switch, break, continue etc).
What are events
Events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can react on these events. Some of the examples of HTML events are: Web page has finished loading • Input field was changed • Button was clicked.
Who created javascript
JavaScript was created by Brendan Eich in 1995 during his time at Netscape Communications. Initially it was developed under the name Mocha, but later the language was officially called LiveScript when it first shipped in beta releases of Netscape.
What is the use of preventDefault method
The preventDefault() method cancels the event if it is cancelable, meaning that the default action or behaviour that belongs to the event will not occur. For example, prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyperlink are some common use cases.
What is the use of stopPropagation method
The stopPropagation method is used to stop the event from bubbling up the event chain. For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div(Div1).
What are the steps involved in return false usage
The return false statement in event handlers performs the below steps: First it stops the browser's default action or behaviour • It prevents the event from propagating the DOM • Stops callback execution and returns immediately when called.
What is BOM
The Browser Object Model (BOM) allows JavaScript to "talk to" the browser. It consists of the objects navigator, history, screen, location and document which are children of the window. The Browser Object Model is not standardized and can change based on different browsers.
What is the use of setTimeout
The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds. For example, let's log a message after 2 seconds using setTimeout method.
What is the use of setInterval
The setInterval() method is used to call a function or evaluate an expression at specified intervals (in milliseconds). For example, let's log a message after 2 seconds using setInterval method.
Why is JavaScript treated as Single threaded
JavaScript is a single-threaded language. Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes. Whereas languages like java, go, C++ can make multi-threaded and multi-process programs.
What is an event delegation
Event delegation is a technique where you attach one event listener to a parent element instead of adding listeners to each child element. It works because events bubble up from the target element to its parents.
What is ECMAScript
ECMAScript is the scripting language that forms the basis of JavaScript. ECMAScript standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications. The first edition of ECMAScript was released in 1997.
What is JSON
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language in the way objects are built in JavaScript.
What are the syntax rules of JSON
The data is in name/value pairs • The data is separated by commas • Curly braces hold objects • Square brackets hold arrays.
What is the purpose JSON stringify
When sending data to a web server, the data has to be in a string format. You can achieve this by converting JSON object into a string using stringify() method.
How do you parse JSON string
When receiving the data from a web server, the data is always in a string format. But you can convert this string value to a javascript object using parse() method.
Why do you need JSON
When exchanging data between a browser and a server, the data can only be text. Since JSON is text only, it can easily be sent to and from a server, and used as a data format by any programming language.
What are PWAs
Progressive web applications (PWAs) are a type of mobile app delivered through the web, built using common web technologies including HTML, CSS and JavaScript. These PWAs are deployed to servers, accessible through URLs, and indexed by search engines.
What is the purpose of clearTimeout method
The clearTimeout() function is used in javascript to clear the timeout which has been set by setTimeout()function before that. i.e, The return value of setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer.
What is the purpose of clearInterval method
The clearInterval() function is used in javascript to clear the interval which has been set by setInterval() function. i.e, The return value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval.
How do you redirect new page in javascript
In vanilla javascript, you can redirect to a new page using the location property of window object. The syntax would be as follows.
How do you check whether a string contains a substring
Using includes: ES6 provided String.prototype.includes method to test a string contains a substring.
How do you validate an email in javascript
You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead of the client side. Because the javascript can be disabled on the client side.
How do you get the current url with javascript
You can use window.location.href expression to get the current url path and you can use the same expression for updating the URL too. You can also use document.URL for read-only purposes but this solution has issues in FF.
What are the various url properties of location object
The below Location object properties can be used to access URL components of the page: href - The entire URL • protocol - The protocol of the URL • host - The hostname and port of the URL • hostname - The hostname of the URL.
How do you get query string values in javascript
You can use URLSearchParams to get query string values in javascript. Let's see an example to get the client code value from URL query string.
How do you check if a key exists in an object
You can check whether a key exists in an object or not using three approaches: Using in operator: You can use the in operator whether a key exists in an object or not.
How do you loop through or enumerate javascript object
You can use the for-in loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn't come from the prototype using hasOwnProperty method.
How do you test for an empty object
Using Object entries(ECMA 7+): You can use object entries length along with constructor type.
What is an arguments object
The arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. For example, let's see how to use arguments object inside sum function.
How do you make first letter of the string in an uppercase
You can create a function which uses a chain of string methods such as charAt, toUpperCase and slice methods to generate a string with the first letter in uppercase.
What are the pros and cons of for loops
The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons.
How do you display the current date in javascript
You can use new Date() to generate a new Date object containing the current date and time. For example, let's display the current date in mm/dd/yyyy.
How do you compare two date objects
You need to use date.getTime() method in order to compare unix timestamp values.
How do you check if a string starts with another string
You can use ECMAScript 6's String.prototype.startsWith() method to check if a string starts with another string or not. But it is not yet supported in all browsers. Let's see an example to see this usage.
How do you trim a string in javascript
JavaScript provided a trim method on string types to trim any whitespaces present at the beginning or ending of the string.
How do you add a key value pair in javascript
There are two possible solutions to add new properties to an object.
Is the !-- notation represents a special operator
No,that's not a special operator. But it is a combination of 2 standard operators one after the other: A logical not (!) • A prefix decrement (--).
How do you assign default values to variables
You can use the logical or operator in an assignment expression to provide a default value. The syntax looks like as below.
How do you define multiline strings
You can define multiline string literals using the '\n' character followed by line terminator('\').
What is an app shell model
An application shell (or app shell) architecture is one way to build a Progressive Web App that reliably and instantly loads on your users' screens, similar to what you see in native applications. It is useful for getting some initial HTML to the screen fast without a network.
Can we define properties for functions
Yes, we can define properties for functions because functions are also objects.
What is the way to find the number of parameters expected by a function
You can use function.length syntax to find the number of parameters expected by a function. Let's take an example of sum function to calculate the sum of numbers.
What is a polyfill
A polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it. For example, Silverlight plugin polyfill can be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer 7.
What are break and continue statements
The break statement is used to "jump out" of a loop. i.e, It breaks the loop and continues executing the code after the loop.
What are js labels
The label statement allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later. For example, the below code with labels avoids printing the numbers when they are same.
What are the benefits of keeping declarations at the top
It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are: Gives cleaner code • It provides a single place to look for local variables • Easy to avoid unwanted global variables • It reduces the possibility of unwanted re-declarations.
What are the benefits of initializing variables
It is recommended to initialize variables because of the below benefits: It gives cleaner code • It provides a single place to initialize variables • Avoid undefined values in the code.
What are the recommendations to create new object
It is recommended to avoid creating new objects using new Object(). Instead you can initialize values based on it's type to create the objects.
How do you define JSON arrays
JSON arrays are written inside square brackets and arrays contain javascript objects. For example, the JSON array of users would be as below.
How do you generate random integers
You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10.
Can you write a random integers function to print integers within a range
Yes, you can create a proper random function to return a random number between min and max (both included).
What is tree shaking
Tree shaking is a form of dead code elimination. It means that unused modules will not be included in the bundle during the build process and for that it relies on the static structure of ES2015 module syntax,( i.e. import and export).
What is the need of tree shaking
Tree Shaking can significantly reduce the code size in any application. i.e, The less code we send over the wire the more performant the application will be.
Is it recommended to use eval
No, it allows arbitrary code to be run which causes a security problem. As we know that the eval() function is used to run text as code. In most of the cases, it should not be necessary to use it.
What is a Regular Expression
A regular expression is a sequence of characters that forms a search pattern. You can use this search pattern for searching data in a text. These can be used to perform all types of text search and text replace operations. Let's see the syntax format now.
What are the string methods that accept Regular expression
There are six string methods: search(), replace(), replaceAll(), match(), matchAll(), and split().
What are modifiers in regular expression
Modifiers can be used to perform case-insensitive and global searches. Let's list some of the modifiers.
What are regular expression patterns
Regular Expressions provide a group of patterns in order to match characters. Basically they are categorized into 3 types: Brackets: These are used to find a range of characters • [abc]: Used to find any of the characters between the brackets(a,b,c) • [0-9]: Used to find any of the digits between the brackets.
What is a RegExp object
RegExp object is a regular expression object with predefined properties and methods. Let's see the simple usage of RegExp object.
How do you search a string for a pattern
You can use the test() method of regular expression in order to search a string for a pattern, and return true or false depending on the result.
What is the purpose of exec method
The purpose of exec method is similar to test method but it executes a search for a match in a specified string and returns a result array, or null instead of returning true/false.
How do you change the style of a HTML element
You can change inline style or classname of a HTML element using javascript DOM-manipulation.
What would be the result of 1+2+'3'
The output is going to be 33. Since 1 and 2 are numeric values, the result of the first two digits is going to be a numeric value 3. The next digit is a string type value because of that the addition of numeric value 3 and string type value 3 is just going to be a concatenation value 33.
What is a debugger statement
The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect. For example, in the below function a debugger statement has been inserted.
What is the purpose of breakpoints in debugging
You can set breakpoints in the javascript code once the debugger statement is executed and the debugger window pops up. At each breakpoint, javascript will stop executing, and let you examine the JavaScript values. After examining values, you can resume the execution of code using the play button.
Can I use reserved words as identifiers
No, you cannot use the reserved words as variables, labels, object or function names. Let's see one simple example.
How do you detect a mobile browser
You can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile.
How do you detect a mobile browser without regexp
You can detect mobile browsers by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage.
How do you get the image width and height using JS
You can programmatically get the image and check the dimensions(width and height) using JavaScript.
Part 4: Prototypes, Object Methods & Event Loop (174 - 253)
80 QuestionsHow do you make synchronous HTTP request
Browsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript.
How do you make asynchronous HTTP request
Browsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing the 3rd parameter as true.
How do you convert date to another timezone in javascript
You can use the toLocaleString() method to convert dates in one timezone to another. For example, let's convert current date to British English timezone as below.
What are the properties used to get size of window
You can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window. Let's use a combination of these properties to calculate the size of a window or document.
What is a conditional operator in javascript
The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statements.
Can you apply chaining on conditional operator
Yes, you can apply chaining on conditional operators similar to if … else if … else if … else chain. The syntax is going to be as below.
What are the ways to execute javascript after a page load
You can execute javascript after page load in many different ways: window.onload.
What is the difference between proto and prototype
The proto object is the actual object that is used in the lookup chain to resolve methods, etc. Whereas prototype is the object that is used to build proto when you create an object with the new operator (a special variant of a function call).
Can you give an example of when you really need a semicolon
It is recommended to use semicolons after every statement in JavaScript. For example, in the below case (that is an IIFE = Immediately Invoked Function Expression) it throws an error ".. is not a function" at runtime due to missing semicolon.
What is the freeze method
The freeze() method is used to freeze an object. Freezing an object does not allow adding new properties to an object, prevents removing, and prevents changing the enumerability, configurability, or writability of existing properties. i.e. It returns the passed object and does not create a frozen copy.
What is the purpose of the freeze method
It is used for freezing objects and arrays • It is used to make an object immutable.
Why do I need to use the freeze method
In the Object-oriented paradigm, an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. Hence it works as the final keyword which is used in various languages.
How do you detect a browser language preference
You can use the navigator object to detect a browser language preference as below.
How to convert a string to title case with javascript
Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function.
How do you detect if javascript is disabled on the page
You can use the tag to detect whether JavaScript is disabled or not. The code block inside gets executed when JavaScript is disabled, and is typically used to display alternative content when the page is generated in JavaScript.
What are various operators supported by javascript
Arithmetic Operators: Includes + (Addition), – (Subtraction), \* (Multiplication), / (Division), % (Modulus), ++ (Increment) and – – (Decrement) • Comparison Operators: Includes == (Equal), != (Not Equal), === (Equal with type), > (Greater than), >= (Greater than or Equal to), < (Less.
What is a rest parameter
Rest parameter is an improved way to handle function parameters which allows us to represent an indefinite number of arguments as an array. The syntax would be as below.
What happens if you do not use rest parameter as a last argument
The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. For example, if you define a function like below it doesn’t make any sense and will throw an error.
What are the bitwise operators available in javascript
Below are the list of bitwise logical operators used in JavaScript.
What is a spread operator
Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. Let's take an example to see this behavior.
How do you determine whether object is frozen or not
Object.isFrozen() method is used to determine if an object is frozen or not.An object is frozen if all of the below conditions hold true: If it is not extensible • If all of its properties are non-configurable • If all its data properties are non-writable.
How do you determine two values same or not using object
The Object.is() method determines whether two values are the same value. For example, the usage with different types of values would be.
What is the purpose of using object is method
Some of the applications of Object's is method are follows: It is used for comparison of two strings • It is used for comparison of two numbers • It is used for comparing the polarity of two numbers • It is used for comparison of two objects.
How do you copy properties from one object to other
You can use the Object.assign() method which is used to copy the values and properties from one or more source objects to a target object. It returns the target object which has properties and values copied from the source objects. The syntax would be as below.
What are the applications of the assign method
It is used for cloning an object • It is used to merge objects with the same properties.
What is a proxy object
The Proxy object is used to define custom behavior for fundamental operations such as property lookup, assignment, enumeration, function invocation, etc.
What is the purpose of the seal method
The Object.seal() method is used to seal an object, by preventing new properties from being added to it and marking all existing properties as non-configurable. But values of present properties can still be changed as long as they are writable. The next level of immutability would be the Object.freeze() method.
What are the applications of the seal method
It is used for sealing objects and arrays • It is used to make properties of an object non-configurable.
What are the differences between the freeze and seal methods
If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made in them whereas if an object is sealed using the Object.seal() method then the changes can be made in the existing properties of the object.
How do you determine if an object is sealed or not
The Object.isSealed() method is used to determine if an object is sealed or not. An object is sealed if all of the below conditions hold true.
How do you get enumerable key and value pairs
The Object.entries() method is used to return an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. Let's see the functionality of object.entries() method in an example.
What is the main difference between Object.values and Object.entries method
The Object.values() method's behavior is similar to Object.entries() method but it returns an array of values instead [key,value] pairs.
How can you get the list of keys of any object
You can use the Object.keys() method which is used to return an array of a given object's own property names, in the same order as we get with a normal loop. For example, you can get the keys of a user object.
How do you create an object with a prototype
The Object.create() method is used to create a new object with the specified prototype object and properties. i.e, It uses an existing object as the prototype of the newly created object. It returns a new object with the specified prototype object and properties.
What is a WeakSet
A WeakSet is used to store a collection of weakly(weak references) held objects. The syntax would be as follows.
What are the differences between WeakSet and Set
The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. i.e, An object in WeakSet can be garbage collected if there is no other reference to it. Other differences are: Set can store any value whereas WeakSet can store only collections of objects.
List down the collection of methods available on WeakSet
add(value): A new object is appended with the given value • delete(value): Deletes the value from the collection • has(value): It returns true if the value is present in the collection, otherwise it returns false.
What is a WeakMap
A WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. In this case, keys must be objects and the values can be arbitrary values. The syntax looks like the following.
What are the differences between WeakMap and Map
The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. i.e, A key object in WeakMap can be garbage collected if there is no other reference to it. Other differences are: Map can store any key type whereas WeakMap can store only collections of key objects.
List down the collection of methods available on WeakMap
set(key, value): Sets the value for the key in the WeakMap object • delete(key): Removes any value associated to the key • has(key): Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not • get(key): Returns the value associated to the key, or undefined if there is none.
What is the purpose of uneval
The uneval() is an builtin function which is used to create a string representation of the source code of an Object. It is a top-level function and is not associated with any object. Let's see the below example to know more about it's functionality.
How do you encode an URL
The encodeURI() function is used to encode complete URI which has special characters except (, / ? : @ & = + $ #) characters.
How do you decode an URL
The decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously created by encodeURI().
How do you print the contents of web page
The window object provides a print() method which is used to print the contents of the current window. It opens a Print dialog box which lets you choose between various printing options. Let's see the usage of print method in an example.
What is the difference between uneval and eval
The uneval function returns the source of a given object; whereas the eval function does the opposite, by evaluating that source code in a different memory area. Let's see an example to clarify the difference.
What is an anonymous function
An anonymous function is a function without a name! Anonymous functions are commonly assigned to a variable name or used as a callback function. The syntax would be as below.
What is the precedence order between local and global variables
A local variable takes precedence over a global variable with the same name. Let's see this behavior in an example.
What are javascript accessors
ECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses the get keyword whereas Setters uses the set keyword.
How do you define property on Object constructor
The Object.defineProperty() static method is used to define a new property directly on an object, or modify an existing property on an object, and returns the object. Let's see an example to know how to define property.
What is the difference between get and defineProperty
Both have similar results unless you use classes. If you use get the property will be defined on the prototype of the object whereas using Object.defineProperty() the property will be defined on the instance it is applied to.
What are the advantages of Getters and Setters
They provide simpler syntax • They are used for defining computed properties, or accessors in JS • Useful to provide equivalence relation between properties and methods • They can provide better data quality.
Can I add getters and setters using defineProperty method
Yes, You can use the Object.defineProperty() method to add Getters and Setters. For example, the below counter object uses increment, decrement, add and subtract properties.
What is the purpose of switch-case
The switch case statement in JavaScript is used for decision making purposes. In a few cases, using the switch case statement is going to be more convenient than if-else statements. The syntax would be as below.
What are the conventions to be followed for the usage of switch case
The expression can be of type either number or string • Duplicate values are not allowed for the expression • The default statement is optional • The break statement is used inside the switch to terminate a statement sequence.
What are primitive data types
A primitive data type is data that has a primitive value (which has no properties or methods). There are 7 types of primitive data types.
What are the different ways to access object properties
There are 3 possible ways for accessing the property of an object.
What are the function parameter rules
JavaScript functions follow below rules for parameters: The function definitions do not specify data types for parameters • Do not perform type checking on the passed arguments • Do not check the number of arguments received.
What is an error object
An error object is a built in error object that provides error information when an error occurs. It has two properties: name and message. For example, the below function logs error details.
When do you get a syntax error
A SyntaxError is thrown if you try to evaluate code with a syntax error. For example, the below missing quote for the function parameter throws a syntax error.
What are the different error names from error object
There are 7 different types of error names returned from error object.
What are the various statements in error handling
try: This statement is used to test a block of code for errors • catch: This statement is used to handle the error • throw: This statement is used to create custom errors • finally: This statement is used to execute code after try and catch regardless of the result.
What are the two types of loops in javascript
Entry Controlled loops: In this kind of loop type, the test condition is tested before entering the loop body • Exit Controlled Loops: In this kind of loop type, the test condition is tested or evaluated at the end of the loop body.
What is nodejs
Node.js is a server-side platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. It is an event-based, non-blocking, asynchronous I/O runtime that uses Google's V8 JavaScript engine and libuv library.
What is the Intl object
The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. It provides access to several constructors and language sensitive functions.
How do you perform language specific date and time formatting
You can use the Intl.DateTimeFormat object which is a constructor for objects that enable language-sensitive date and time formatting. Let's see this behavior with an example.
What is an Iterator
An iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a next() method which returns an object with two properties: value (the next value in the sequence) and done (which is true if the last value in the sequence has been consumed).
How does synchronous iteration works
Synchronous iteration was introduced in ES6 and it works with below set of components.
What is the event loop
The event loop is a process that continuously monitors both the call stack and the event queue and checks whether or not the call stack is empty. If the call stack is empty and there are pending events in the event queue, the event loop dequeues the event from the event queue and pushes it to the call stack.
What is the call stack
Call Stack is a data structure for javascript interpreters to keep track of function calls(creates execution context) in the program. It has two major actions: Whenever you call a function for its execution, you are pushing it to the stack • Whenever the execution is completed, the function is popped out of the stack.
What is the event queue
The event queue follows the queue data structure. It stores async callbacks to be added to the call stack. It is also known as the Callback Queue or Macrotask Queue.
What is a decorator
A decorator is an expression that evaluates to a function and that takes the target, name, and decorator descriptor as arguments. Also, it optionally returns a decorator descriptor to install on the target object. Let's define admin decorator for user class at design time.
What are the properties of the Intl object
Collator: These are the objects that enable language-sensitive string comparison • DateTimeFormat: These are the objects that enable language-sensitive date and time formatting • ListFormat: These are the objects that enable language-sensitive list formatting • NumberFormat: Objects that enable language-sensitive number formatting.
What is an Unary operator
The unary(+) operator is used to convert a variable to a number.If the variable cannot be converted, it will still become a number but with the value NaN. Let's see this behavior in an action.
How do you sort elements in an array
The sort() method is used to sort the elements of an array in place and returns the sorted array. The default sort order is ascending, based on the string Unicode order. The example usage would be as below.
What is the purpose of compareFunction while sorting arrays
The compareFunction is used to define the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
How do you reverse an array
You can use the reverse() method to reverse the elements in an array. This method is useful to sort an array in descending order. Let's see the usage of reverse() method in an example.
How do you find the min and max values in an array
You can use Math.min and Math.max methods on array variables to find the minimum and maximum elements within an array. Let's create two functions to find the min and max value with in an array.
How do you find the min and max values without Math functions
You can write functions which loop through an array comparing each value with the lowest value or highest value to find the min and max values. Let's create those functions to find min and max values.
What is an empty statement and purpose of it
The empty statement is a semicolon (;) indicating that no statement will be executed, even if JavaScript syntax requires one. Since there is no action with an empty statement you might think that it's usage is quite less, but the empty statement is occasionally useful when you want to create a loop that has an empty body.
How do you get the metadata of a module
You can use the import.meta object which is a meta-property exposing context-specific meta data to a JavaScript module. It contains information about the current module, such as the module's URL. In browsers, you might get different meta data than NodeJS.
Part 5: ES6+ Modern Syntax, Classes, Modules & Destructuring (254 - 328)
75 QuestionsWhat is the comma operator
The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand. This is totally different from comma usage within arrays, objects, and function arguments and parameters. For example, the usage for numeric expressions would be as below.
What is the advantage of the comma operator
It is normally used to include multiple expressions in a location that requires a single expression. One of the common usages of this comma operator is to supply multiple parameters in a for loop. For example, the below for loop uses multiple expressions in a single location using comma operator.
What is typescript
TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes and many other features, and compiles to plain JavaScript. Angular is built entirely in TypeScript and it is used as the primary language there. You can install it globally as.
What are the differences between javascript and typescript
Below are the list of differences between javascript and typescript.
What are the advantages of typescript over javascript
TypeScript is able to find compile time errors at the development time only and it makes sures less runtime errors • TypeScript is strongly-typed or supports static typing which allows for checking type correctness at compile time.
What is an object initializer
An object initializer is an expression that describes the initialization of an Object. The syntax for this expression is represented as a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). This is also known as literal notation.
What is a constructor method
The constructor method is a special method for creating and initializing an object created within a class. If you do not specify a constructor method, a default constructor is used. The example usage of constructor would be as below.
What happens if you write constructor more than once in a class
The "constructor" in a class is a special method and it should be defined only once in a class. i.e, If you write a constructor method more than once in a class it will throw a SyntaxError error.
How do you call the constructor of a parent class
You can use the super keyword to call the constructor of a parent class. Remember that super() must be called before using this reference. Otherwise it will cause a reference error. Let's the usage of it.
How do you get the prototype of an object
You can use the Object.getPrototypeOf(obj) method to return the prototype of the specified object. i.e. The value of the internal prototype property. If there are no inherited properties then null value is returned.
What happens If I pass string type for getPrototype method
In ES5, it will throw a TypeError exception if the obj parameter isn't an object. Whereas in ES2015, the parameter will be coerced to an Object.
How do you set the prototype of one object to another
You can use the Object.setPrototypeOf() method that sets the prototype (i.e., the internal Prototype property) of a specified object to another object or null. For example, if you want to set prototype of a square object to rectangle object would be as follows.
How do you check whether an object can be extended or not
The Object.isExtensible() method is used to determine if an object is extendable or not. i.e, Whether it can have new properties added to it or not.
How do you prevent an object from being extend
The Object.preventExtensions() method is used to prevent new properties from ever being added to an object. In other words, it prevents future extensions to the object. Let's see the usage of this property.
What are the different ways to make an object non-extensible
You can mark an object non-extensible in 3 ways: Object.preventExtensions • Object.seal • Object.freeze.
How do you define multiple properties on an object
The Object.defineProperties() method is used to define new or modify existing properties directly on an object and returning the object. Let's define multiple properties on an empty object.
What is the MEAN stack
The MEAN (MongoDB, Express, AngularJS, and Node.js) stack is the most popular open-source JavaScript software tech stack available for building dynamic web apps where you can write both the server-side and client-side halves of the web project entirely in JavaScript.
What is obfuscation in javascript
Obfuscation is the deliberate act of creating obfuscated javascript code(i.e, source or machine code) that is difficult for humans to understand. It is something similar to encryption, but a machine can understand the code and execute it. Let's see the below function before Obfuscation.
Why do you need Obfuscation
The Code size will be reduced • It hides the business logic from outside world and protects the code from others • Reverse engineering is highly difficult • The download time will be reduced.
What is Minification
Minification is the process of removing all unnecessary characters(empty spaces are removed) and variables will be renamed without changing it's functionality. It is also a type of obfuscation .
What are the advantages of minification
Normally it is recommended to use minification for heavy traffic and intensive requirements of resources. It reduces file sizes with below benefits: Decreases loading times of a web page • Saves bandwidth usages.
What are the differences between obfuscation and Encryption
Below are the main differences between obfuscation and encryption.
What are the common tools used for minification
Google's Closure Compiler • UglifyJS2 • jsmin • javascript-minifier.com/.
How do you perform form validation using javascript
JavaScript can be used to perform HTML form validation. For example, if the form field is empty, the function needs to notify, and return false, to prevent the form being submitted. Let's perform user login in an html form.
How do you perform form validation without javascript
You can perform HTML form validation automatically without using javascript. The validation enabled by applying the required attribute to prevent form submission when the input is empty.
What are the DOM methods available for constraint validation
The below DOM methods are available for constraint validation on an invalid input: checkValidity(): It returns true if an input element contains valid data • setCustomValidity(): It is used to set the validationMessage property of an input element.
What are the available constraint validation DOM properties
validity: It provides a list of boolean properties related to the validity of an input element • validationMessage: It displays the message when the validity is false • willValidate: It indicates if an input element will be validated or not.
What are the validity properties
The validity property of an input element provides a set of properties related to the validity of data.
Give an example usage of the rangeOverflow property
If an element's value is greater than its max attribute then the rangeOverflow property is true. For example, the below form submission throws an error if the value is more than 100.
Are enums available in javascript
No, javascript does not natively support enums. But there are different kinds of solutions to simulate them even though they may not provide exact equivalents. For example, you can use freeze or seal on object.
What is an enum
An enum is a type restricting variables to one value from a predefined set of constants. JavaScript has no enums but typescript provides built-in enum support.
How do you list all properties of an object
You can use the Object.getOwnPropertyNames() method which returns an array of all properties found directly in a given object. Let's see the usage of this in an example below.
How do you get property descriptors of an object
You can use the Object.getOwnPropertyDescriptors() method which returns all own property descriptors of a given object. The example usage of this method is below.
What are the attributes provided by a property descriptor
A property descriptor is a record which has the following attributes.
How do you extend classes
The extends keyword is used in class declarations/expressions to create a class which is a child of another class. It can be used to subclass custom classes as well as built-in objects. The syntax would be as below.
How do I modify the url without reloading the page
The window.location.href property will be helpful to modify the url but it reloads the page. HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively. For example, you can use pushState as below.
How do you check whether or not an array includes a particular value
The Array#includes() method is used to determine whether an array includes a particular value among its entries by returning either true or false. Let's see an example to find an element(numeric and string) within an array.
How do you compare scalar arrays
You can use length and every method of arrays to compare two scalars (compared directly using ===) arrays. The combination of these expressions can give the expected result.
How to get the value from get parameters
The new URL() object accepts the url string and searchParams property of this object can be used to access the get parameters.
How do you print numbers with commas as thousand separators
You can use the Number.prototype.toLocaleString() method which returns a string with a language-sensitive representation such as thousand separator, currency etc. of this number.
What is the difference between java and javascript
Both are totally unrelated programming languages and no relation between them. Java is statically typed, compiled, runs on its own VM. Whereas JavaScript is dynamically typed, interpreted, and runs in a browser and nodejs environments. Let's see the major differences in a tabular format.
Does JavaScript support namespaces
JavaScript doesn’t support namespaces by default. So if you create any element (function, method, object, variable) then it becomes global and pollutes the global namespace. Let's take an example of defining two functions without any namespace.
How do you declare a namespace
Even though JavaScript lacks namespaces, we can use Objects, an IIFE (Immediately Invoked Function Expression) or let/const to create namespaces.
How do you invoke javascript code in an iframe from the parent page
Initially iFrame needs to be accessed using either document.getElementBy or window.frames. After that contentWindow property of iFrame gives the access for targetFunction.
How do you get the timezone offset of a date object
You can use the getTimezoneOffset method of the date object. This method returns the time zone difference, in minutes, from current locale (host system settings) to UTC.
How do you load CSS and JS files dynamically
You can create both link and script elements in the DOM and append them as child to head tag. Let's create a function to add script and style resources as below.
What are the different methods to find HTML elements in DOM
If you want to access any element in an HTML page, you need to start with accessing the document object. Later you can use any of the below methods to find the HTML element: document.getElementById(id): It finds an element by Id • document.getElementsByTagName(name): It finds an element by tag name (returns an node list).
What is jQuery
jQuery is a popular cross-browser JavaScript library that provides Document Object Model (DOM) traversal, event handling, animations and AJAX interactions by minimizing the discrepancies across browsers. It is widely famous with its philosophy of “Write less, do more”.
What is V8 JavaScript engine
V8 is an open source high-performance JavaScript engine used by the Google Chrome browser, written in C++. It is also being used in the node.js project. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors.
Why do we call javascript as dynamic language
JavaScript is a loosely typed or a dynamic language because variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned/reassigned with values of all types.
What is a void operator
The void operator evaluates the given expression and then returns undefined (i.e, without returning value). The syntax would be as below.
How to set the cursor to wait
The cursor can be set to wait in JavaScript by using the property cursor. Let's perform this behavior on page load using the below function.
How do you create an infinite loop
You can create infinite loops using for and while loops without using any expressions. The for loop construct or syntax is better approach in terms of ESLint and code optimizer tools.
Why do you need to avoid with statement
JavaScript's with statement was intended to provide a shorthand for writing recurring accesses to objects. So it can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. Let's take an example where it is used to avoid redundancy when accessing an object several times.
What is the output of the following for loops
The output of the above for loops is 4 4 4 4 and 0 1 2 3.
List down some of the features of ES6
Support for constants or immutable variables • Block-scope support for variables, constants and functions • Arrow functions • Default parameters.
What is ES6
ES6 is the sixth edition of the javascript language and it was released in June 2015. It was initially known as ECMAScript 6 (ES6) and later renamed to ECMAScript 2015. Almost all the modern browsers support ES6 but for the old browsers there are many transpilers, like Babel.js etc.
Can I redeclare let and const variables
No, you cannot redeclare let and const variables. If you do, it throws below error.
Does the const variable make the value immutable
No, the const variable doesn't make the value immutable. But it disallows subsequent assignments(i.e, You can declare with assignment but can't assign another value later).
What are default parameters
In ES5, we need to depend on logical OR operators to handle default values of function parameters. Whereas in ES6, Default function parameters feature allows parameters to be initialized with default values if no value or undefined is passed. Let's compare the behavior with an examples.
What are template literals
Template literals or template strings are string literals allowing embedded expressions. These are enclosed by the back-tick (`) character instead of double or single quotes. In ES6, this feature enables using dynamic expressions as below.
How do you write multi-line strings in template literals
In ES5, you would have to use newline escape characters('\\n') and concatenation symbols(+) in order to get multi-line strings.
What are nesting templates
The nesting template is a feature supported within template literals syntax to allow inner backticks inside a placeholder ${ } within the template. For example, the below nesting template is used to display the icons based on user permissions whereas outer template checks for platform type.
What are tagged templates
Tagged templates are the advanced form of templates in which tags allow you to parse template literals with a function. The tag function accepts the first parameter as an array of strings and remaining parameters as expressions. This function can also return manipulated strings based on parameters.
What are raw strings
ES6 provides a raw strings feature using the String.raw() method which is used to get the raw string form of template strings. This feature allows you to access the raw strings as they were entered, without processing escape sequences. For example, the usage would be as below.
What is destructuring assignment
The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment.
What are default values in destructuring assignment
A variable can be assigned a default value when the value unpacked from the array or object is undefined during destructuring assignment. It helps to avoid setting default values separately for each assignment. Let's take an example for both arrays and object use cases.
How do you swap variables in destructuring assignment
If you don't use destructuring assignment, swapping two values requires a temporary variable. Whereas using a destructuring feature, two variable values can be swapped in one destructuring expression. Let's swap two number variables in array destructuring assignment.
What are enhanced object literals
Object literals make it easy to quickly create objects with properties inside the curly braces. For example, it provides shorter syntax for common object property definition as below.
What are dynamic imports
The dynamic imports using import() function syntax allows us to load modules on demand by using promises or the async/await syntax. Currently this feature is in stage4 proposal.
What are the use cases for dynamic imports
Import a module on-demand or conditionally.
What are typed arrays
Typed arrays are array-like objects from ECMAScript 6 API for handling binary data. JavaScript provides 12 Typed array types: Int8Array: An array of 8-bit signed integers • Uint8Array: An array of 8-bit unsigned integers • Uint8ClampedArray: An array of 8-bit unsigned integers clamped to 0-255.
What are the advantages of module loaders
The module loaders provides the below features: Dynamic loading • State isolation • Global namespace isolation • Compilation hooks.
What is collation
Collation is used for sorting a set of strings and searching within a set of strings. It is parameterized by locale and aware of Unicode. Let's take comparison and sorting features: Comparison.
What is for...of statement
The for...of statement creates a loop iterating over iterable objects or elements such as built-in String, Array, Array-like objects (like arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. The basic usage of for...of statement on arrays would be as below.
Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)
75 QuestionsWhat is the output of below spread operator array
The output of the array is ['J', 'o', 'h', 'n', ' ', 'R', 'e', 's', 'i', 'g'].
Is PostMessage secure
Yes, postMessages can be considered very secure as long as the programmer/developer is careful about checking the origin and source of an arriving message. But if you try to send/receive a message without verifying its source will create cross-site scripting attacks.
What are the problems with postmessage target origin as wildcard
The second argument of postMessage method specifies which origin is allowed to receive the message. If you use the wildcard “\*” as an argument then any origin is allowed to receive the message. In this case, there is no way for the sender window to know if the target window is at the target origin when sending the message.
How do you avoid receiving postMessages from attackers
Since the listener listens for any message, an attacker can trick the application by sending a message from the attacker’s origin, which gives an impression that the receiver received the message from the actual sender’s window.
Can I avoid using postMessages completely
You cannot avoid using postMessages completely(or 100%). Even though your application doesn’t use postMessage considering the risks, a lot of third party scripts use postMessage to communicate with the third party service. So your application might be using postMessage without your knowledge.
Is postMessages synchronous
The postMessages are synchronous in IE8 browser but they are asynchronous in IE9 and all other modern browsers (i.e, IE9+, Firefox, Chrome, Safari).Due to this asynchronous behaviour, we use a callback mechanism when the postMessage is returned.
What paradigm is Javascript
JavaScript is a multi-paradigm language, supporting imperative/procedural programming, Object-Oriented Programming and functional programming. JavaScript supports Object-Oriented Programming with prototypical inheritance.
What is the difference between internal and external javascript
Internal JavaScript: It is the source code within the script tag. External JavaScript: The source code is stored in an external file(stored with .js extension) and referred with in the tag.
Is JavaScript faster than server side script
Yes, JavaScript is faster than server side scripts. Because JavaScript is a client-side script it does not require any web server’s help for its computation or calculation. So JavaScript is always faster than any server-side script like ASP, PHP, etc.
How do you get the status of a checkbox
You can apply the checked property on the selected checkbox in the DOM. If the value is true it means the checkbox is checked, otherwise it is unchecked. For example, the below HTML checkbox element can be access using javascript as below.
What is the purpose of double tilde operator
The double tilde operator(~~) is known as double NOT bitwise operator. This operator is a slightly quicker substitute for Math.floor().
How do you convert character to ASCII code
You can use the String.prototype.charCodeAt() method to convert string characters to ASCII numbers. For example, let's find ASCII code for the first letter of 'ABC' string.
What is ArrayBuffer
An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You can create it as below.
What is the output of below string expression
The output of the above expression is "W". Explanation: The bracket notation with specific index on a string returns the character at a specific location. Hence, it returns the character "W" of the string. Since this is not supported in IE7 and below versions, you may need to use the .charAt() method to get the desired result.
What is the purpose of Error object
The Error constructor creates an error object and the instances of error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. The syntax of error object would be as below.
What is the purpose of EvalError object
The EvalError object indicates an error regarding the global eval() function. Even though this exception is not thrown by JavaScript anymore, the EvalError object remains for compatibility. The syntax of this expression would be as below.
What are the list of cases error thrown from non-strict mode to strict mode
When you apply 'use strict'; syntax, some of the below cases will throw a SyntaxError before executing the script.
Do all objects have prototypes
No. All objects have prototypes except two exceptions: Object.prototype itself — This is the base object in the prototype chain, and its prototype is null • Objects created with Object.create(null) — These are deliberately created with no prototype, so they don’t inherit from Object.prototype.
What is the difference between a parameter and an argument
Parameter is the variable name of a function definition whereas an argument represents the value given to a function when it is invoked. Let's explain this with a simple function.
What is the purpose of some method in arrays
The some() method is used to test whether at least one element in the array passes the test implemented by the provided function. The method returns a boolean value. Let's take an example to test for any odd elements.
How do you combine two or more arrays
The concat() method is used to join two or more arrays by returning a new array containing all the elements. The syntax would be as below.
What is the difference between Shallow and Deep copy
There are two ways to copy an object.
How do you create specific number of copies of a string
The repeat() method is used to construct and return a new string which contains the specified number of copies of the string on which it was called, concatenated together. Remember that this method has been added to the ECMAScript 2015 specification. Let's take an example of Hello string to repeat it 4 times.
How do you return all matching strings against a regular expression
The matchAll() method can be used to return an iterator of all results matching a string against a regular expression. For example, the below example returns an array of matching string results against a regular expression.
How do you trim a string at the beginning or ending
The trim method of string prototype is used to trim on both sides of a string. But if you want to trim especially at the beginning or ending of the string then you can use trimStart/trimLeft and trimEnd/trimRight methods. Let's see an example of these methods on a greeting message.
What is the output of below console statement with unary operator
Let's take console statement with unary operator as given below.
Does javascript uses mixins
JavaScript does not have built-in support for mixins as a formal language feature. However, developers commonly implement mixins using various patterns to enable code reuse and composition.
Mixin Example using Object composition
Mixins in JavaScript allow objects to borrow methods from multiple source objects without using rigid class inheritance hierarchies. By utilizing Object.assign() or object composition, behaviors can be mixed into target prototypes dynamically.
Benefits
Avoids deep inheritance hierarchies • Encourages composition over inheritance • Promotes reusable and modular code.
What is a thunk function
A thunk is just a function which delays the evaluation of the value. It doesn’t take any arguments but gives the value whenever you invoke the thunk. i.e, It is used not to execute now but it will be sometime in the future. Let's take a synchronous example.
What are asynchronous thunks
The asynchronous thunks are useful to make network requests. Let's see an example of network requests.
What is the output of below function calls
Code snippet.
How to remove all line breaks from a string
The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.
What is the difference between reflow and repaint
A repaint occurs when changes are made which affect the visibility of an element, but not its layout. Examples of this include outline, visibility, or background color. A reflow involves changes that affect the layout of a portion of the page (or the whole page).
What happens with negating an array
Negating an array with ! character will coerce the array into a boolean. Since Arrays are considered to be truthy So negating it will return false.
What happens if we add two arrays
If you add two arrays together, it will convert them both to strings and concatenate them. For example, the result of adding arrays would be as below.
What is the output of prepend additive operator on falsy values
If you prepend the additive(+) operator on falsy values(null, undefined, NaN, false, ""), the falsy value converts to a number value zero. Let's display them on browser console as below.
How do you create self string using special characters
The self string can be formed with the combination of []()!+ characters. You need to remember the below conventions to achieve this pattern.
How do you remove falsy values from an array
You can apply the filter method on the array by passing Boolean as a parameter. This way it removes all falsy values(0, undefined, null, false and "") from the array.
How do you get unique values of an array
You can get unique values of an array with the combination of Set and rest expression/spread(...) syntax.
What is destructuring aliases
Sometimes you would like to have a destructured variable with a different name than the property name. In that case, you'll use a : newName to specify a name for the variable. This process is called destructuring aliases.
How do you map the array values without using map method
You can map the array values without using the map method by just using the from method of Array. Let's map city names from Countries array.
How do you empty an array
You can empty an array quickly by setting the array length to zero.
How do you round numbers to certain decimals
You can round numbers to a certain number of decimals using toFixed method from native javascript.
What is the easiest way to convert an array to an object
You can convert an array to an object with the same data using spread(...) operator.
How do you create an array with some data
You can create an array with some data or an array with the same values using fill method.
What are the placeholders from console object
%o — It takes an object • %s — It takes a string • %d — It is used for a decimal or integer.
Is it possible to add CSS to console messages
Yes, you can apply CSS styles to console messages similar to html text on the web page.
What is the purpose of dir method of console object
The console.dir() is used to display an interactive list of the properties of the specified JavaScript object as JSON.
Is it possible to debug HTML elements in console
Yes, it is possible to get and debug HTML elements in the console just like inspecting elements.
How do you display data in a tabular format using console object
The console.table() is used to display data in the console in a tabular format to visualize complex arrays or objects.
How do you verify that an argument is a Number or not
The combination of IsNaN and isFinite methods are used to confirm whether an argument is a number or not.
How do you create copy to clipboard button
You need to select the content(using .select() method) of the input element and execute the copy command with execCommand (i.e, execCommand('copy')). You can also execute other system commands like cut and paste.
What is the shortcut to get timestamp
You can use new Date().getTime() to get the current timestamp. There is an alternative shortcut to get the value.
How do you flattening multi dimensional arrays
Flattening bi-dimensional arrays is trivial with Spread operator.
What is the easiest multi condition checking
You can use indexOf to compare input with multiple values instead of checking each value as one condition.
How do you capture browser back button
The beforeunload event is triggered when the window, the document and its resources are about to be unloaded. This event is helpful to warn users about losing the current data and detect back button event.
How do you disable right click in the web page
The right click on the page can be disabled by returning false from the oncontextmenu attribute on the body element.
What are wrapper objects
Primitive Values like string,number and boolean don't have properties and methods but they are temporarily converted or coerced to an object(Wrapper object) when you try to perform actions on them. For example, if you apply toUpperCase() method on a primitive string value, it does not throw an error but returns uppercase of the string.
What is AJAX
AJAX stands for Asynchronous JavaScript and XML and it is a group of related technologies(HTML, CSS, JavaScript, XMLHttpRequest API etc) used to display data asynchronously. i.e. We can send data to the server and get data from the server without reloading the web page.
What are the different ways to deal with Asynchronous Code
Below are the list of different ways to deal with Asynchronous code.
How to cancel a fetch request
Until a few days back, One shortcoming of native promises is no direct way to cancel a fetch request. But the new AbortController from js specification allows you to use a signal to abort one or multiple fetch calls. The basic flow of cancelling a fetch request would be as below: Create an AbortController instance.
What is web speech API
Web speech API is used to enable modern browsers recognize and synthesize speech(i.e, voice data into web apps). This API was introduced by W3C Community in the year 2012.
What is minimum timeout throttling
Both browser and NodeJS javascript environments throttles with a minimum delay that is greater than 0ms. That means even though setting a delay of 0ms will not happen instantaneously. Browsers: They have a minimum delay of 4ms.
How do you implement zero timeout in modern browsers
You can't use setTimeout(fn, 0) to execute the code immediately due to minimum delay of greater than 0ms. But you can use window.postMessage() to achieve this behavior.
What are tasks in event loop
When a new javascript program is executed directly from console or running by the `` element, the task will be added to the task queue • When an event fires, the event callback added to task queue.
What is microtask
A microtask is a type of JavaScript callback that is scheduled to run immediately after the currently executing script and before the next event loop tick. Microtasks are executed after the current task completes and before any new tasks (macrotasks) are run. This ensures a fast and predictable update cycle.
What are different event loops
The Browser Event Loop • The Node.js Event Loop.
What is the purpose of queueMicrotask
The queueMicrotask function is used to schedule a microtask, which is a function that will be executed asynchronously in the microtask queue. The purpose of queueMicrotask is to ensure that a function is executed after the current task has finished, but before the browser performs any rendering or handles user events.
How do you use javascript libraries in typescript file
It is known that not all JavaScript libraries or frameworks have TypeScript declaration files. But if you still want to use libraries or frameworks in your TypeScript files without getting compilation errors, the only solution is declare keyword along with a variable declaration.
What are the differences between promises and observables
Some of the major difference in a tabular form.
What is heap
Heap(Or memory heap) is the memory location where objects are stored when we define variables. i.e, This is the place where all the memory allocations and de-allocation take place. Both heap and call-stack are two containers of JS runtime.
What is an event table
Event Table is a data structure that stores and keeps track of all the events which will be executed asynchronously like after some time interval or after the resolution of some API requests. i.e Whenever you call a setTimeout function or invoke async operation, it is added to the Event Table.
What is a microTask queue
Microtask Queue is the new queue where all the tasks initiated by promise objects get processed before the callback queue. The microtasks queue are processed before the next rendering and painting jobs. But if these microtasks are running for a long time then it leads to visual degradation.
What is the difference between shim and polyfill
A shim is a library that brings a new API to an older environment, using only the means of that environment. It isn't necessarily restricted to a web application. For example, es5-shim.js is used to emulate ES5 features on older browsers (mainly pre IE9).
Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)
60 QuestionsHow do you detect primitive or non primitive value type
In JavaScript, primitive types include boolean, string, number, BigInt, null, Symbol and undefined. Whereas non-primitive types include the Objects. But you can easily identify them with the below function.
What is babel
Babel is a JavaScript transpiler to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Some of the main features are listed below: Transform syntax • Polyfill features that are missing in your target environment (using @babel/polyfill).
Is Node.js completely single threaded
Node is a single thread, but some of the functions included in the Node.js standard library(e.g, fs module functions) are not single threaded. i.e, Their logic runs outside of the Node.js single thread to improve the speed and performance of a program.
What are the common use cases of observables
Some of the most common use cases of observables are web sockets with push notifications, user input changes, repeating intervals, etc.
What is RxJS
RxJS (Reactive Extensions for JavaScript) is a library for implementing reactive programming using observables that makes it easier to compose asynchronous or callback-based code. It also provides utility functions for creating and working with observables.
What is the difference between Function constructor and function declaration
The functions which are created with Function constructor do not create closures to their creation contexts but they are always created in the global scope. i.e, the function can access its own local variables and global scope variables only. Whereas function declarations can access outer function variables(closures) too.
What is a Short circuit condition
Short circuit conditions are meant for condensed way of writing simple if statements. Let's demonstrate the scenario using an example. If you would like to login to a portal with an authentication condition, the expression would be as below.
What is the easiest way to resize an array
The length property of an array is useful to resize or empty an array quickly. Let's apply length property on number array to resize the number of elements from 5 to 2.
What is an observable
An Observable is basically a function that can return a stream of values either synchronously or asynchronously to an observer over time. The consumer can get the value by calling subscribe() method. Let's look at a simple example of an Observable.
What is the difference between function and class declarations
The main difference between function declarations and class declarations is hoisting. The function declarations are hoisted but not class declarations.
What is an async function
An async function is a function declared with the async keyword which enables asynchronous, promise-based behavior to be written in a cleaner style by avoiding promise chains. These functions can contain zero or more await expressions.
How do you prevent promises swallowing errors
While using asynchronous code, JavaScript’s ES6 promises can make your life a lot easier without having callback pyramids and error handling on every second line. But Promises have some pitfalls and the biggest one is swallowing errors by default.
What is deno
The file system • The network • Execution of other scripts • The environment variables.
How do you make an object iterable in javascript
By default, plain objects are not iterable. But you can make the object iterable by defining a Symbol.iterator property on it.
What is a Proper Tail Call
First, we should know about tail call before talking about "Proper Tail Call". A tail call is a subroutine or function call performed as the final action of a calling function.
How do you check an object is a promise or not
If you don't know if a value is a promise or not, wrapping the value as Promise.resolve(value) which returns a promise.
How to detect if a function is called as constructor
You can use new.target pseudo-property to detect whether a function was called as a constructor(using the new operator) or as a regular function call.
What are the differences between arguments object and rest parameter
There are three main differences between arguments object and rest parameters.
What are the differences between spread operator and rest parameter
Rest parameter collects all remaining elements into an array. Whereas Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. i.e, Rest parameter is opposite to the spread operator.
What are the different kinds of generators
Generator function declaration.
What are the built-in iterables
Arrays and TypedArrays • Strings: Iterate over each character or Unicode code-points • Maps: iterate over its key-value pairs • Sets: iterates over their elements.
What are the differences between for...of and for...in statements
Both for...in and for...of statements iterate over js data structures. The only difference is over what they iterate: for..in iterates over all enumerable property keys of an object • for..of iterates over the values of an iterable object.
How do you define instance and non-instance properties
The Instance properties must be defined inside of class methods. For example, name and age properties defined inside constructor as below.
What is the difference between isNaN and Number.isNaN?
isNaN: The global function isNaN converts the argument to a Number and returns true if the resulting value is NaN • Number.isNaN: This method does not convert the argument.
How to invoke an IIFE without any extra brackets?
Immediately Invoked Function Expressions(IIFE) requires a pair of parenthesis to wrap the function which contains set of statements.
Is that possible to use expressions in switch cases?
You might have seen expressions used in switch condition but it is also possible to use for switch cases by assigning true value for the switch condition. Let's see the weather condition based on temperature as an example.
What is the easiest way to ignore promise errors?
The easiest and safest way to ignore promise errors is void that error. This approach is ESLint friendly too.
How do style the console output using CSS?
You can add CSS styling to the console output using the CSS format content specifier %c. The console string message can be appended after the specifier and CSS style in another argument. Let's print the red color text using console.log and CSS specifier as below.
What is nullish coalescing operator (??)?
It is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This can be contrasted with the logical OR () operator, which returns the right-hand side operand if the left operand is any falsy value, not only null or undefined.
How do you group and nest console output?
The console.group() can be used to group related log messages to be able to easily read the logs and use console.groupEnd()to close the group. Along with this, you can also nest groups which allows to output message in hierarchical manner.
What is the difference between dense and sparse arrays?
An array contains items at each index starting from first(0) to last(array.length - 1) is called as Dense array. Whereas if at least one item is missing at any index, the array is called as sparse.
What are the different ways to create sparse arrays?
There are 4 different ways to create sparse arrays in JavaScript.
What is the difference between setTimeout, setImmediate and process.nextTick?
Set Timeout: setTimeout() is to schedule execution of a one-time callback after delay milliseconds • Set Immediate: The setImmediate function is used to execute a function right after the current event loop finishes.
How do you reverse an array without modifying original array?
The reverse() method reverses the order of the elements in an array but it mutates the original array. Let's take a simple example to demonistrate this case.
How do you create custom HTML element?
The creation of custom HTML elements involves two main steps: Define your custom HTML element: First you need to define some custom class by extending HTMLElement class • Use custom element just like other HTML element: Declare your custom element as a HTML tag.
What is global execution context?
The global execution context is the default or first execution context that is created by the JavaScript engine before any code is executed(i.e, when the file first loads in the browser). All the global code that is not inside a function or object will be executed inside this global execution context.
What is function execution context?
Whenever a function is invoked, the JavaScript engine creates a different type of Execution Context known as a Function Execution Context (FEC) within the Global Execution Context (GEC) to evaluate and execute the code within that function.
What is debouncing?
Debouncing is a programming technique used to limit how often a function is executed. Specifically, it ensures that a function is only triggered after a certain amount of time has passed since it was last invoked.
What is throttling?
Throttling is a programming technique used to control the rate at which a function is executed. When an event is triggered continuously—such as during window resizing, scrolling, or mouse movement—throttling ensures that the associated event handler is not called more often than a specified interval.
What is optional chaining?
According to MDN official docs, the optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.
What is an environment record?
According to ECMAScript specification 262 (9.1).
How to verify if a variable is an array?
It is possible to check if a variable is an array instance using 3 different ways: Array.isArray() method.
What is pass by value and pass by reference?
Pass-by-value creates a new space in memory and makes a copy of a value. Primitives such as string, number, boolean etc will actually create a new copy. Hence, updating one value doesn't impact the other value. i.e, The values are independent of each other.
What are the differences between primitives and non-primitives?
JavaScript language has both primitives and non-primitives but there are few differences between them as below.
How do you create your own bind method using either call or apply method?
The custom bind function needs to be created on Function prototype inorder to use it as other builtin functions. This custom function should return a function similar to original bind method and the implementation of inner function needs to use apply method call.
What are the differences between pure and impure functions?
Some of the major differences between pure and impure function are as below.
What is referential transparency?
An expression in javascript that can be replaced by its value without affecting the behaviour of the program is called referential transparency. Pure functions are referentially transparent.
What are the possible side-effects in javascript?
Making an HTTP request • DOM manipulations • Mutating the input data • Printing to a screen or console: For example, console.log() and alert().
What are compose and pipe functions?
The "compose" and "pipe" are two techniques commonly used in functional programming to simplify complex operations and make code more readable. They are not native to JavaScript and higher-order functions. the compose() applies right to left any number of functions to the output of the previous function.
What is module pattern?
Module pattern is a designed pattern used to wrap a set of variables and functions together in a single scope returned as an object. JavaScript doesn't have access specifiers similar to other languages(Java, Python, etc) to provide private scope. It uses IIFE (Immediately invoked function expression) to allow for private scopes.
What is Function Composition?
It 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.
How to use await outside of async function prior to ES2022?
Prior to ES2022, if you attempted to use an await outside of an async function resulted in a SyntaxError.
What is the purpose of the this keyword in JavaScript?
The this keyword in JavaScript refers to the object that is executing the current function. Its value is determined by how a function is called, not where it is defined. this is essential for writing object-oriented and event-driven code, as it allows methods to interact with the data of the object they belong to.
What are the uses of closures?
Data Privacy: Closures can be used to create private variables and methods.
What are the phases of execution context?
The execution context in JavaScript is a data structure that stores the information necessary for executing a piece of code. It includes the code itself, the values of the variables used in the code, and the scope chain. The scope chain is a list of objects that are used to resolve variable names.
What are the possible reasons for memory leaks?
Memory leaks can lead to poor performance, slow loading times and even crashes in web applications. Some of the common causes of memory leaks are listed below: The execessive usage of global variables or omitting the var keyword in local scope • Forgetting to clear the timers set up by setTimeout or setInterval.
What are the optimization techniques of V8 engine?
V8 engine uses the below optimization techniques.: Inline expansion: It is a compiler optimization by replacing the function calls with the corresponding function blocks • Copy elision: This is a compiler optimization method to prevent expensive extra objects from being duplicated or copied.
What are the examples of built-in higher order functions?
arrays: map, filter, reduce, sort, forEach, some etc • DOM: The DOM method element.addEventListener(type, handler) also accepts the function handler as a second argument • Strings: replace() method.
What are the benefits higher order functions?
The main benefits of higher order functions are: Abstraction • Reusability • Immutability • Modularity.
How do you create polyfills for map, filter and reduce methods?
The polyfills for array methods such as map, filter and reduce methods can be created using array prototype.
Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)
73 QuestionsWhat is the difference between map and forEach functions?
Both map and forEach functions are used to iterate over an arrays but there are some differences in their functionality.
Give an example of statements affected by automatic semicolon insertion?
The javascript parser will automatically add a semicolon while parsing the source code. For example, the below common statements affected by Automatic Semicolon Insertion(ASI).
What are the event phases of a browser?
Capturing phase: This phase goes down gradually from the top of the DOM tree to the target element when a nested element clicked.
What are the real world use cases of proxy?
Proxies are not used in regular day to day JavaScript work but they enabled many exciting programming patterns. Some of the real world use cases are listed below: Vue3 used proxy concept to implement reactive state • SolidJS implemented reactive stores • Immerjs built upon proxy to track updates to immutable updates.
What are hidden classes?
Since JavaScript is a dynamic programming language, you can add or remove properties and methods from objects on the fly at runtime. This nature of JavaScript increases the dynamic dictionary lookups(because objects implemented as HashTables in memory) for retrieving a property on an object.
What is inline caching?
Inline caching is an optimization technique based on the observation that repeated calls to same function tends to occur on same type of objects. The V8 compiler stores a cache of the type of objects that were passed as a parameter in recent method calls.
What are the different ways to execute external scripts?
async: The script is downloaded in parallel to parsing the page, and executed as soon as it is available even before parsing completes.
What is Lexical Scope?
Lexical scope is the ability for a function scope to access variables from the parent scope.
How to detect system dark mode in javascript?
The combination of Window.matchMedia() utility method along with media query is used to check if the user has selected a dark color scheme in their operating system settings or not. The CSS media query prefers-color-scheme needs to be passed to identify system color theme.
What is the purpose of requestAnimationFrame method?
The requestAnimationFrame() method in JavaScript is used to schedule a function to be called before the next repaint of the browser window, allowing you to create smooth, efficient animations.
What is the difference between substring and substr methods?
Both substring and substr are used to extract parts of a string, but there are subtle differences between the substring() and substr() methods in terms of syntax and behavior.
How to find the number of parameters expected by a function?
The function's object has a length property which tells you how many formal parameters expected by a function. This is a static value defined by the function, not the number of arguments the function is called with(arguments.length). The basic usage of length propery is.
What is globalThis, and what is the importance of it?
Nowadays JavaScript language is used in a wide variety of environments and each environment has its own object model. Due to this fact, there are different ways(syntax) to access the global object.
What are the array mutation methods?
JavaScript array methods can be categorized into two groups: Mutating methods: These are the methods that directly modify the original array • Non-mutating methods: These methods return a new array without altering the original one.
What is module scope in JavaScript?
Module scope is a feature introduced with ES6 (ES2015) modules that creates a scope specific to a module file, isolating variables and functions declared within it from the global scope and other modules.
What are shadowing and illegal shadowing?
Both shadowing and illegal shadowing refer to how variable names can "hide" or override others within nested scopes.
Why is it important to remove event listeners after use?
In JavaScript, you need to be mindful of removing event listeners to avoid memory leaks — especially in long-lived apps like single-page applications (SPAs) or when working with frameworks/libraries.
What is structuredClone and how is it used for deep copying objects?
In JavaScript, structuredClone() is a built-in method used to create a deep copy of a value. It safely clones nested objects, arrays, Maps, Sets, Dates, TypedArrays, and even circular references — without sharing references to the original value.
What is the difference between const and Object.freeze
The main difference is that const applies to variables (bindings), while Object.freeze() applies to values (objects).
What is Promise.any and when should it be used?
Promise.any() is a Promise combinator method introduced in ES2021 that takes an iterable of promises and returns a single promise that fulfills as soon as any of the input promises fulfills. It resolves with the value of the first promise that successfully resolves.
What is BigInt and how is it different from Number?
BigInt is a built-in JavaScript object (introduced in ES2020) that provides a way to represent whole numbers larger than 2^53 - 1 (the largest number JavaScript can reliably represent with the Number primitive).
What are private class fields in JavaScript?
Private class fields (introduced in ES2022) are class properties that are only accessible within the class itself. They are prefixed with a hash symbol (#) and provide true encapsulation in JavaScript classes.
What is the Array.prototype.at() method and why is it useful?
The at() method (introduced in ES2022) allows you to access array elements using both positive and negative indices. It provides a simpler and more intuitive way to access elements from the end of an array.
What is top-level await in JavaScript modules?
Top-level await is a feature (introduced in ES2022) that allows you to use the await keyword at the top level of ES modules, outside of async functions. This enables modules to act as asynchronous functions themselves.
What are WeakRef and FinalizationRegistry used for?
WeakRef and FinalizationRegistry are advanced features (introduced in ES2021) for managing memory and object lifecycles in JavaScript. They provide low-level control over garbage collection behavior.
What are logical assignment operators?
Logical assignment operators (introduced in ES2021) combine logical operations (&&, , ??) with assignment (=). They provide a concise way to assign values based on logical conditions.
What is the Temporal API and why is it proposed as a replacement for Date?
The Temporal API is a modern proposal (Stage 3) to replace JavaScript's problematic Date object. It provides a better, more intuitive way to work with dates and times in JavaScript.
What is the difference between for loop and forEach
Both are used to iterate over arrays, but they differ in performance, flexibility, and purpose.
What are Symbols and what are their use cases?
Symbol is a primitive data type introduced in ES6 that creates unique and immutable values. Each Symbol value is guaranteed to be unique, even if they have the same description.
What is the difference between Object.create() and Object.assign()?
Object.create() and Object.assign() serve completely different purposes.
What are generator functions and how do they work?
Generator functions are special functions that can pause execution and resume later, allowing them to produce a sequence of values over time instead of computing them all at once.
What is the Reflect API and when should you use it?
The Reflect API is a built-in object that provides methods for interceptable JavaScript operations. It mirrors many Object methods but with some improvements.
How does JavaScript handle floating point precision issues?
JavaScript uses IEEE 754 double-precision (64-bit) floating-point format, which can cause precision issues with decimal numbers.
What are tagged template literals and their practical uses?
Tagged template literals allow you to parse template literals with a function, giving you full control over the interpolation process.
What is the difference between Object.keys(), Object.values(), and Object.entries()?
These three methods extract different parts of an object's own enumerable properties.
What is the Intl.NumberFormat API and how is it used?
The Intl.NumberFormat API provides language-sensitive number formatting, allowing you to format numbers according to locale-specific conventions.
How do you implement method chaining in JavaScript?
Method chaining is a pattern where multiple methods are called on the same object sequentially by returning this from each method.
What are the differences between Map and Object for storing key-value pairs?
While both Map and Object store key-value pairs, they have significant differences.
What is the purpose of Symbol.iterator and how do you use it?
Symbol.iterator is a well-known symbol that specifies the default iterator for an object, making it iterable with for...of loops and spread operators.
How does the Intersection Observer API work?
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or the viewport.
What are async iterators and how are they different from regular iterators?
Async iterators allow you to iterate over asynchronous data sources using for await...of loops, where each iteration can wait for a Promise to resolve.
What is the purpose of Object.getOwnPropertyDescriptors()?
Object.getOwnPropertyDescriptors() returns all own property descriptors of an object, including their attributes (value, writable, enumerable, configurable, get, set).
How does Promise.allSettled() differ from Promise.all()?
Promise.allSettled() and Promise.all() both handle multiple promises, but they behave differently when promises are rejected.
What are the performance implications of using try-catch in JavaScript?
Try-catch blocks have performance implications, especially when used in hot code paths or when exceptions are frequently thrown.
What is the AbortController API and how is it used?
The AbortController API provides a way to abort one or more asynchronous operations, particularly useful for canceling fetch requests.
How do you implement a custom error class in JavaScript?
Custom error classes allow you to create specific error types with additional properties and methods, making error handling more precise.
What is the difference between synchronous and asynchronous generators?
Synchronous and asynchronous generators differ in how they produce values and handle asynchronous operations.
What are Proxy traps and what operations can they intercept?
Proxy traps are handler methods that intercept fundamental operations on objects, allowing you to customize their behavior.
How does the Mutation Observer API work?
The MutationObserver API provides a way to watch for changes to the DOM tree, replacing the deprecated mutation events.
What is tail call optimization and does JavaScript support it?
Tail call optimization (TCO) is a technique where a function call in tail position (the last operation before returning) reuses the current stack frame instead of creating a new one, preventing stack overflow in recursive functions.
What are the different ways to handle circular references in JSON?
Circular references occur when an object references itself directly or indirectly, causing JSON.stringify() to throw an error.
How do you implement a singleton pattern in JavaScript?
The singleton pattern ensures a class has only one instance and provides a global access point to it.
What is the Performance API and how is it used for measuring performance?
The Performance API provides high-precision timing information for measuring web application performance.
What are the differences between SharedArrayBuffer and ArrayBuffer?
SharedArrayBuffer and ArrayBuffer are both fixed-length binary data buffers, but SharedArrayBuffer allows sharing memory between multiple workers/threads.
How do you prevent prototype pollution attacks in JavaScript?
Prototype pollution is a security vulnerability where attackers inject properties into Object.prototype, affecting all objects in the application.
What is the Atomics API and when should it be used?
The Atomics API provides atomic operations on SharedArrayBuffer, ensuring thread-safe access to shared memory in multi-threaded JavaScript (workers).
How do you implement a lazy loading pattern for modules?
Lazy loading defers module loading until they're actually needed, reducing initial bundle size and improving load time.
What are the best practices for optimizing JavaScript bundle size?
Optimizing bundle size improves load times, reduces bandwidth usage, and enhances user experience, especially on slow networks.
How do you convert the digits of a number into words in JavaScript?
A common practical coding interview problem is to convert an integer into its digit-by-digit word representation (e.g., input 1234 → output "one two three four").
How do you convert an integer into full English words with place values in JavaScript?
Unlike digit-by-digit transliteration (1234 → "one two three four"), this problem requires converting a non-negative integer into standard conversational English words with place values (e.g., 1234 → "One Thousand Two Hundred Thirty Four"). This is the classic LeetCode 273 (Integer to English Words) interview question.
How do you convert between Roman Numerals and Integers in JavaScript?
Converting between Roman numerals and integers is one of the most frequently asked practical coding interview challenges.
How do you convert strings between camelCase, snake_case, and kebab-case in JavaScript?
Fullstack and frontend engineers frequently receive snake_case payloads from backends (Python, Go, PostgreSQL) and need to transform them to camelCase for client models, or transform them to kebab-case for CSS class names and URL slugs.
How do you implement Run-Length Encoding (RLE) string compression and decompression?
Run-Length Encoding (RLE) is a lossless data compression algorithm where consecutive repeated characters are replaced by the character and its frequency count (e.g., "aabcccccaaa" → "a2b1c5a3").
How do you deeply flatten and unflatten a nested JavaScript object with dot notation?
A classic frontend machine-coding interview question testing recursion, object traversal, and nested reference construction.
How do you format large numbers with compact metric suffixes (e.g., 1.2K, 3.4M) without external libraries?
Social platforms (YouTube views, GitHub stars, Twitter followers) display abbreviated numbers (e.g., 1200 → "1.2K", 1500000 → "1.5M").
How do you implement a custom EventEmitter (Event Bus) with memory leak prevention and once subscriptions?
An EventEmitter (Event Bus) is a publish-subscribe design pattern implementation that enables decoupled communication between components by registering listener functions to named event keys and broadcasting arguments when those events trigger.
How do you implement polyfills for Promise.all, Promise.allSettled, Promise.any, and Promise.race from scratch?
Promise combinators coordinate multiple concurrent asynchronous operations: Promise.all fails fast on first rejection, Promise.allSettled always waits for all promises to finish, Promise.any returns the first fulfilled promise or an AggregateError, and Promise.race settles as soon as the first promise...
How do you implement a robust deepClone function handling circular references, Dates, RegExps, Sets, and Maps?
A robust deep clone recursively duplicates nested objects and arrays while using a WeakMap to track visited object references to prevent infinite call stack overflows on circular structures, and explicitly reconstructs special types like Date, RegExp, Map, and Set.: JSON.parse(JSON.stringify(obj)): Fails on circular...
How do you implement advanced debounce and throttle functions with leading/trailing edge execution and cancellation?
Debounce postpones execution until a specified delay has elapsed since the last invocation, while throttle guarantees that a function executes at most once per defined time window, both optionally supporting immediate (leading) and delayed (trailing) edge triggers. #### 1. Advanced Debounce with Immediate (Leading) & Cancellation.
How do you implement a concurrency-limited asynchronous task runner (Parallel Worker Pool)?
A concurrency-limited task runner (asyncPool) processes a large collection of asynchronous tasks with an upper bound on simultaneous active executions (e.g. at most 3 requests concurrently), preserving the original result order without overloading servers or rate limits.
How do you implement an O(1) Least Recently Used (LRU) Cache in JavaScript?
An LRU (Least Recently Used) Cache is a fixed-capacity data structure that evicts the least recently accessed item when capacity is reached, achieving O(1) time complexity for both get and put operations by leveraging ES6 Map insertion-order properties or a doubly linked list with a hash map.
How do you implement a deep object diff function to detect added, modified, and deleted properties?
A deep object diff algorithm recursively compares two JSON trees to generate a patch summary identifying newly added keys, deleted keys, and modified values with their before-and-after states, essential for state synchronization, undo/redo stacks, and UI reconciliation. #### Implementation.
How do you implement polyfills for Array.prototype.flat and flatMap supporting custom and infinite recursion depth?
Array.prototype.flat recursively concatenates sub-array elements up to a specified depth (defaulting to 1, or Infinity for complete flattening), which can be implemented either recursively with array reduction or iteratively using a stack to prevent call stack overflow on deeply nested arrays. #### 1.