Spaces:
Runtime error
Runtime error
| What are the possible ways to create objects in JavaScript | |
| Possible ways to create objects in JavaScript include object literals ({}), the new Object() constructor, constructor functions, ES6 classes, and Object.create(). | |
| What is a prototype chain | |
| The prototype chain is a mechanism in JavaScript where objects inherit properties and methods from other objects, forming a chain that is traversed when a property is accessed. | |
| What is the Difference Between call, apply, and bind | |
| call and apply execute a function immediately, setting the this value, with call taking arguments individually and apply taking arguments as an array; bind returns a new function with the this value permanently set. | |
| What is JSON and its common operations | |
| JSON (JavaScript Object Notation) is a lightweight data-interchange format, and its common operations include parsing (JSON.parse()) to convert a JSON string to a JavaScript object and stringifying (JSON.stringify()) to convert a JavaScript object to a JSON string. | |
| What is the purpose of the array slice method | |
| The array slice() method returns a shallow copy of a portion of an array into a new array object, selecting elements from a start to an end index (not inclusive), without modifying the original array. | |
| What is the purpose of the array splice method | |
| The array splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place, and it returns the removed elements. | |
| What is the difference between slice and splice | |
| slice() returns a new array containing a copy of a portion of the original array and does not modify the original, while splice() modifies the original array by adding, removing, or replacing elements. | |
| How do you compare Object and Map | |
| An Object is the most basic building block, where keys must be strings or Symbols, and it doesn't maintain insertion order; a Map is a collection of keyed data items where keys can be of any data type, and it maintains insertion order. | |
| What is the difference between == and === operators | |
| The == (equality) operator compares values, performing type coercion if the operands are of different types; the === (strict equality) operator compares values and checks if the operands are of the same type, with no type coercion. | |
| What are lambda expressions or arrow functions | |
| Lambda expressions or arrow functions (=>) provide a concise syntax for writing functions and do not have their own this, arguments, super, or new.target bindings. | |
| What is a first class function | |
| A first-class function means that functions in that language are treated like any other variable: they can be assigned to variables, passed as arguments to other functions, and returned as values from other functions. | |
| What is a first order function | |
| A first-order function is a function that does not take another function as an argument and does not return a function. | |
| What is a higher order function | |
| A higher-order function is a function that either takes one or more functions as arguments or returns a function as its result. | |
| What is a unary function | |
| A unary function (or monad) is a function that accepts exactly one argument. | |
| What is the currying function | |
| Currying is a functional programming technique of transforming a function that takes multiple arguments into a sequence of functions, each taking a single argument. | |
| What is a pure function | |
| A pure function is a function that, given the same input, will always return the same output and has no side effects (it does not modify anything outside its scope). | |
| What are the benefits of pure functions | |
| Benefits of pure functions include predictability (easier to test and reason about), referential transparency (can replace function call with its result), and they enable caching/memoization. | |
| What is the purpose of the let keyword | |
| The let keyword is used to declare block-scoped local variables, meaning the variable is only accessible within the block of code where it is defined. | |
| What is the difference between let and var | |
| let declares variables that are block-scoped and cannot be redeclared within the same scope, whereas var declares variables that are function-scoped (or global) and can be redeclared. | |
| What is the reason to choose the name let as a keyword | |
| The name let was chosen to indicate that it provides a way to declare a lexically-scoped variable, similar to how it's used in mathematical assertions and other programming languages. | |
| How do you redeclare variables in a switch block without an error | |
| You can redeclare variables inside a switch block without an error by wrapping the case block contents in curly braces ({}), which creates a new block scope for the variable declaration. | |
| What is the Temporal Dead Zone | |
| The Temporal Dead Zone (TDZ) is the time span between a variable's creation by the JavaScript engine and its initialization (where it's assigned a value), during which accessing the variable (declared with let or const) will result in a ReferenceError. | |
| What is an IIFE (Immediately Invoked Function Expression) | |
| An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined, often used to create a private scope for variables and avoid polluting the global namespace. | |
| How do you decode or encode a URL in JavaScript? | |
| To decode a URL, you use decodeURI() or decodeURIComponent(); to encode a URL, you use encodeURI() or encodeURIComponent(). | |
| What is memoization | |
| Memoization is an optimization technique used primarily to speed up computer programs by caching the results of expensive function calls and returning the cached result when the same inputs occur again. | |
| What is Hoisting | |
| Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase, but only the declaration, not the assignment, is hoisted. | |
| What are classes in ES6 | |
| Classes in ES6 are primarily syntactic sugar over JavaScript's existing prototype-based inheritance model, providing a cleaner, more conventional way to create objects and deal with inheritance. | |
| What are closures | |
| Closures are a combination of a function and the lexical environment (scope) within which that function was declared, allowing the inner function to access variables from its outer function's scope even after the outer function has finished execution. | |
| What are modules | |
| Modules are self-contained pieces of code that export specific values (functions, variables, classes) and import values from other modules, helping to organize code into smaller, reusable chunks. | |
| Why do you need modules | |
| You need modules to achieve better code organization, prevent global scope pollution, and facilitate code reuse and dependency management. | |
| What is scope in javascript | |
| Scope in JavaScript refers to the accessibility of variables, functions, and objects in some particular part of your code; it determines where you can access a variable. | |
| What is a service worker | |
| A Service Worker is a type of web worker that acts as a proxy between the web browser and the network, enabling features like offline support, network request interception, and push notifications. | |
| How do you manipulate DOM using a service worker | |
| You cannot manipulate the DOM directly from a Service Worker because it runs in a separate thread; manipulation must be done by sending messages to the pages it controls, which then handle the DOM updates. | |
| How do you reuse information across service worker restarts | |
| Information can be reused across Service Worker restarts by storing it persistently using browser APIs like IndexedDB or the Cache Storage API. | |
| What is IndexedDB | |
| IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs, and is an asynchronous database system. | |
| What is web storage | |
| Web Storage refers to APIs that let web applications store data locally within the user's browser, typically including localStorage and sessionStorage. | |
| What is a post message | |
| A postMessage is a method used to securely communicate between different origins, windows, or web workers in a browser, allowing for cross-origin communication. | |
| What is a Cookie | |
| A Cookie is a small piece of text data that a server sends to a user's web browser, which the browser may store and then send back with subsequent requests to the same server. | |
| Why do you need a Cookie | |
| You need a Cookie primarily for session management (logging in), personalization (user preferences), and tracking (user behavior). | |
| What are the options in a cookie | |
| Options in a cookie include Expires or Max-Age (when it expires), Domain, Path, Secure (HTTPS only), HttpOnly (prevents client-side access), and SameSite. | |
| How do you delete a cookie | |
| To delete a cookie, you must set its Expires date to a past date or set its Max-Age to 0, ensuring the Domain and Path attributes match those used when the cookie was created. | |
| What are the differences between cookie, local storage and session storage | |
| Cookies are small (max $\approx 4$ KB), sent with every HTTP request, and have an expiration date; localStorage and sessionStorage are larger ($\approx 5$-$10$ MB), client-side only, and not sent with requests. | |
| What is the main difference between localStorage and sessionStorage | |
| The main difference is that localStorage persists data even after the browser is closed (no expiration), whereas sessionStorage data is cleared when the browser tab/window is closed. | |
| How do you access web storage | |
| You access Web Storage by using the localStorage and sessionStorage objects on the window object, with methods like .setItem(key, value) and .getItem(key). | |
| What are the methods available on session storage | |
| The methods available on sessionStorage are .setItem(key, value), .getItem(key), .removeItem(key), .key(index), and .clear(). | |
| What is a storage event and its event handler | |
| A storage event fires on other browser windows/tabs from the same origin when a storage area is modified; its event handler receives a StorageEvent object with details about the change. | |
| Why do you need web storage | |
| You need Web Storage to provide client-side data persistence, allowing web applications to store user-specific data or state locally for a faster and richer user experience. | |
| How do you check web storage browser support | |
| You check Web Storage browser support by testing if the localStorage and sessionStorage properties exist on the window object: if (window.localStorage). | |
| How do you check web workers browser support | |
| You check Web Workers browser support by testing for the existence of the Worker property on the global object: if (window.Worker). | |
| Give an example of a web worker | |
| An example of a web worker involves creating a new worker with const myWorker = new Worker('worker.js'); and then communicating using postMessage() and listening with onmessage. | |
| What are the restrictions of web workers on DOM | |
| The main restriction of web workers is that they do not have direct access to the DOM (Document Object Model) of the main page, nor access to the global window, document, or parent objects. | |
| What is a promise | |
| A Promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value. | |
| Why do you need a promise | |
| You need a Promise to manage asynchronous operations in a more structured, readable, and less error-prone way than traditional callbacks, helping to avoid callback hell. | |
| Explain the three states of promise | |
| The three states of a Promise are pending (initial state), fulfilled (operation completed successfully), and rejected (operation failed). | |
| What is a callback function | |
| A callback function is a function passed as an argument to another function, which is then executed (called back) inside the outer function to complete an action. | |
| Why do we need callbacks | |
| We need callbacks to handle code execution after an asynchronous operation (like a network request or a timer) has completed, ensuring that logic runs at the correct time. | |
| What is a callback hell | |
| Callback hell (or the pyramid of doom) is a term used to describe deeply nested, hard-to-read, and difficult-to-maintain code that results from using multiple asynchronous operations executed with traditional callbacks. | |
| What are server-sent events | |
| Server-Sent Events (SSE) are a mechanism that allows a web application to efficiently receive automatic updates (pushed data) from a server over a single, long-lived HTTP connection. | |
| How do you receive server-sent event notifications | |
| You receive server-sent event notifications by creating a new EventSource object and listening for messages using the onmessage event handler. | |
| How do you check browser support for server-sent events | |
| You check browser support for server-sent events by checking for the existence of the EventSource object on the global window object: if (window.EventSource). | |
| What are the events available for server sent events | |
| The events available for server-sent events are open (connection established), message (data received), and error (connection failure or error). | |
| What are the main rules of promise] | |
| The main rules of a Promise are that it is immutable once settled (fulfilled or rejected), and it can only transition from pending to either fulfilled or rejected only once. | |
| What is callback in callback | |
| Callback in callback refers to the pattern of passing a callback function as an argument to an asynchronous function, and then, within that callback, passing *another* callback to *another* asynchronous function, leading to nesting. | |
| What is promise chaining | |
| Promise chaining is the process of linking multiple asynchronous operations together using the .then() method, where the return value of one promise becomes the input for the next one, resulting in sequential execution. | |
| What is promise.all | |
| Promise.all() takes an iterable of promises and returns a single promise that fulfills when all of the promises have fulfilled, or rejects immediately upon the first promise that rejects. | |
| What is the purpose of the race method in promise | |
| The purpose of the Promise.race() method is to take an iterable of promises and return a single promise that settles (fulfills or rejects) with the same outcome as the first promise in the iterable that settles. | |
| What is a strict mode in javascript | |
| Strict mode is a way to opt in to a restricted variant of JavaScript, which disallows certain actions and throws more exceptions, making code safer and easier to debug. | |
| Why do you need strict mode | |
| You need strict mode to eliminate some silent errors by changing them to throw errors, fix mistakes that make it difficult for JavaScript engines to perform optimizations, and prohibit confusing or dangerous syntax. | |
| How do you declare strict mode | |
| You declare strict mode by placing the string literal "use strict"; at the very beginning of a script or a function. | |
| What is the purpose of double exclamation | |
| The purpose of the double exclamation mark (!!) is to explicitly convert any value to a boolean (true or false). | |
| What is the purpose of the delete operator | |
| The purpose of the delete operator is to remove a property from an object or an element from an array. | |
| What is typeof operator | |
| The typeof operator returns a string indicating the data type of its operand (e.g., "string", "number", "object", "undefined"). | |
| What is undefined property | |
| The undefined property is a primitive value that indicates that a variable has been declared but has not been assigned a value. | |
| What is null value | |
| The null value is a primitive value that represents the intentional absence of any object value or is used to denote an empty value. | |
| What is the difference between null and undefined | |
| undefined means a variable has been declared but not assigned a value (default value), while null is a value that can be explicitly assigned to a variable to indicate the intentional absence of a value. | |
| What is eval | |
| eval() is a function that executes JavaScript code represented as a string in the current scope. | |
| What is the difference between window and document | |
| The window object represents the browser window itself and is the global object; the document object is a property of the window object and represents the DOM (HTML content) loaded within the window. | |
| How do you access history in javascript | |
| You access history in JavaScript using the history object, which is a property of the window object, and methods like history.back(), history.forward(), and history.go(n). | |
| How do you detect caps lock key turned on or not | |
| You can detect if the Caps Lock key is turned on by checking the getModifierState('CapsLock') method on the keyboard event object. | |
| What is isNaN | |
| isNaN() is a global function that determines whether a value is the special value NaN (Not-a-Number) after converting the argument to a number. | |
| What are the differences between undeclared and undefined variables | |
| Undeclared variables are those that have not been formally created and accessing them throws a ReferenceError; undefined variables are those that have been declared but not assigned a value. | |
| What are global variables | |
| Global variables are variables declared outside of any function or those declared without var, let, or const inside a function, making them accessible from anywhere in the code. | |
| What are the problems with global variables | |
| The problems with global variables include naming collisions (especially with third-party libraries), making code harder to maintain and debug, and making it difficult to use modules effectively. | |
| What is NaN property | |
| The NaN property (Not-a-Number) is a special numeric value that represents a value that is not a legal number; it is unique because NaN === NaN is false. | |
| What is the purpose of isFinite function | |
| The purpose of the isFinite() function is to determine whether a value is a finite number; it returns false if the argument is $\pm \infty$ or NaN. | |
| What is an event flow | |
| Event flow is the order in which events are processed from the top-most ancestor element down to the target element (capturing phase) and then from the target element up to the top-most ancestor (bubbling phase). | |
| What is event capturing | |
| Event capturing is the phase of the event flow where an event is first captured by the outermost ancestor element and propagates down to the target element. | |
| What is event bubbling | |
| Event bubbling is the phase of the event flow where an event propagates up from the target element to its immediate parent and subsequently up through all ancestors to the root of the document. | |
| How do you submit a form using JavaScript | |
| You submit a form using JavaScript by calling the .submit() method on the HTMLFormElement object (e.g., document.getElementById('myForm').submit()). | |
| How do you find operating system details | |
| You find operating system details by checking the navigator.platform or navigator.userAgent properties of the window.navigator object. | |
| What is the difference between document load and DOMContentLoaded events | |
| document.load (on the window) fires when the entire page has loaded, including all dependent resources; DOMContentLoaded fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets and images. | |
| What is the difference between native, host and user objects | |
| Native objects are standard, built-in JavaScript objects (like String, Date); host objects are provided by the environment (e.g., window, document in browsers); and user objects are those defined by the script writer. | |
| What are the tools or techniques used for debugging JavaScript code | |
| Tools/techniques used for debugging JavaScript code include the browser's developer tools (Sources/Debugger tab), using the console.log() method, setting breakpoints, and using the debugger statement. | |
| What are the pros and cons of promises over callbacks | |
| Promises provide a cleaner, more structured way to handle asynchronous code (pros) but can have a slightly steeper learning curve (cons) than simple callbacks. | |
| What is the difference between an attribute and a property | |
| An attribute is the initial defined property in the HTML markup; a property is the value on the DOM object in memory, which is a live value and can be changed in JavaScript. | |
| What is same-origin policy | |
| The Same-Origin Policy (SOP) is a critical security mechanism that restricts how a document or script loaded from one origin (protocol, domain, port) can interact with resources from another origin. | |
| What is the purpose of void 0 | |
| The purpose of void 0 is to explicitly get the primitive undefined value, often used to ensure the value is actually undefined or in place of undefined in older browsers. | |
| Is JavaScript a compiled or interpreted language | |
| JavaScript is primarily an interpreted language (traditionally), though modern engines use Just-In-Time (JIT) compilation. | |
| Is JavaScript a case-sensitive language | |
| Yes, JavaScript is a case-sensitive language, meaning keywords, variables, and function names must be consistently capitalized. | |
| Is there any relation between Java and JavaScript | |
| There is no relation between Java and JavaScript other than a marketing decision to name the language 'JavaScript' to capitalize on the popularity of Java at the time of its release. | |
| What are events | |
| Events are actions or occurrences that happen in the system (like a user click or a page load), which the system tells you about so you can respond to them. | |
| Who created javascript | |
| JavaScript was created by Brendan Eich while he was working at Netscape Communications in 1995. | |
| What is the use of preventDefault method | |
| The use of the preventDefault() method is to stop the browser's default action from occurring for a given event, such as preventing a form from submitting or a link from navigating. | |
| What is the use of stopPropagation method | |
| The use of the stopPropagation() method is to prevent the event from propagating further up or down the event flow (stopping either the bubbling or capturing phase). | |
| What are the steps involved in return false usage | |
| The steps involved in return false usage in an event handler are equivalent to calling both event.preventDefault() and event.stopPropagation(). | |
| What is BOM | |
| BOM (Browser Object Model) is a collection of browser-specific objects (e.g., window, navigator, screen, location) that allows JavaScript to interact with the web browser. | |
| What is the use of setTimeout | |
| The use of setTimeout() is to execute a function or a piece of code once after a specified delay (in milliseconds). | |
| What is the use of setInterval | |
| The use of setInterval() is to repeatedly execute a function or a piece of code at specified intervals (in milliseconds) until stopped by clearInterval(). | |
| Why is JavaScript treated as Single threaded | |
| JavaScript is treated as Single-threaded because it has only one call stack, meaning it can execute only one piece of code at a time in the main thread. | |
| What is an event delegation | |
| Event delegation is a pattern where you attach a single event listener to a common ancestor element, and then use event bubbling to handle events for all its descendant elements. | |
| What is ECMAScript | |
| ECMAScript is the standard that JavaScript is based on, defining the language specification; JavaScript is the most common implementation of the standard. | |
| What is JSON | |
| JSON (JavaScript Object Notation) is a lightweight, text-based data-interchange format derived from a subset of the JavaScript language. | |
| What are the syntax rules of JSON | |
| The syntax rules of JSON dictate that data is in name/value pairs separated by commas, curly braces hold objects, and square brackets hold arrays. | |
| What is the purpose JSON stringify | |
| The purpose of JSON.stringify() is to convert a JavaScript value (object, array, etc.) into a JSON string. | |
| How do you parse JSON string | |
| You parse a JSON string using the JSON.parse() method, which converts the JSON string back into a JavaScript object. | |
| Why do you need JSON | |
| You need JSON because it is a human-readable, platform-independent, and lightweight format that is widely used for data interchange (sending data between a server and a web application). | |
| What are PWAs | |
| PWAs (Progressive Web Apps) are web applications that use modern web capabilities to deliver an app-like experience to users, leveraging Service Workers for offline support. | |
| What is the purpose of clearTimeout method | |
| The purpose of the clearTimeout() method is to cancel a timeout previously established by a call to setTimeout(), preventing the function from executing. | |
| What is the purpose of clearInterval method | |
| The purpose of the clearInterval() method is to cancel an interval previously established by a call to setInterval(), stopping the repeated execution of the function. | |
| How do you redirect new page in javascript | |
| You redirect to a new page in JavaScript by setting the window.location.href property to the new URL (e.g., window.location.href = 'new-page.html';). | |
| How do you check whether a string contains a substring | |
| You check whether a string contains a substring using the .includes() method (ES6+), the .indexOf() method (returns $-1$ if not found), or a Regular Expression with the .test() method. | |
| How do you validate an email in javascript | |
| You validate an email in JavaScript most commonly by using a Regular Expression to check if the string matches the typical email format structure. | |
| How do you get the current url with javascript | |
| You get the current URL with JavaScript by accessing the window.location.href property. | |
| What are the various url properties of location object | |
| The various URL properties of the location object include href (full URL), protocol, host, pathname, search (query string), and hash (fragment). | |
| How do get query string values in javascript | |
| You get query string values in JavaScript by accessing the window.location.search property and then either manually parsing the string or using the URLSearchParams API. | |
| How do you check if a key exists in an object | |
| You check if a key exists in an object using the in operator, the .hasOwnProperty() method, or by checking if Object.keys(obj).includes(key). | |
| How do you loop through or enumerate javascript object | |
| You loop through or enumerate a JavaScript object using a for...in loop (enumerates enumerable properties) or by iterating over the results of Object.keys(), Object.values(), or Object.entries(). | |
| How do you test for an empty object | |
| You test for an empty object by checking if the array returned by Object.keys(obj) has a length of 0 (e.g., Object.keys(obj).length === 0). | |
| 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. | |
| How do you make first letter of the string in an uppercase | |
| You make the first letter of the string uppercase by taking the first character using .charAt(0) and converting it to uppercase with .toUpperCase(), then concatenating it with the rest of the string using .slice(1). | |
| What are the pros and cons of for loops | |
| The for loop is fast and versatile (pros) but can be verbose and less expressive for iterating over data structures than methods like forEach or map (cons). | |
| How do you display the current date in javascript | |
| You display the current date in JavaScript by creating a new Date object (new Date()) and then using methods like .toLocaleDateString() or .toString(). | |
| How do you compare two date objects | |
| You compare two date objects by converting them to their numeric timestamp values using .getTime() and then comparing the numbers. | |
| How do you check if a string starts with another string | |
| You check if a string starts with another string using the .startsWith() method (ES6+) or by checking if the result of .indexOf(substring) is 0. | |
| How do you trim a string in javascript | |
| You trim a string in JavaScript using the .trim() method, which removes whitespace from both ends of a string. | |
| How do you add a key value pair in javascript | |
| You add a key-value pair to a JavaScript object by using dot notation (obj.key = value) or bracket notation (obj['key'] = value). | |
| Is the !-- notation represents a special operator | |
| The !-- notation is not a special operator; it’s a combination of the logical NOT (!) and decrement (--) operators, often used together in specific contexts. | |
| How do you assign default values to variables | |
| Default values can be assigned using the = operator in function parameters (e.g., function foo(a = 10)) or with the logical OR (||) or nullish coalescing (??) operators for variables. | |
| How do you define multiline strings | |
| Multiline strings are defined using template literals with backticks ( ), allowing line breaks within the string, or by concatenating strings with \n. | |
| What is an app shell model | |
| The app shell model is a design pattern for progressive web apps, where a minimal HTML, CSS, and JS structure is cached to ensure fast loading and offline functionality. | |
| Can we define properties for functions | |
| Yes, functions are objects in JavaScript, so you can define properties on them using dot notation (e.g., func.prop = value). | |
| What is the way to find the number of parameters expected by a function | |
| Use the function.length property to get the number of parameters a function expects. | |
| What is a polyfill | |
| A polyfill is a piece of code that provides modern functionality for older browsers that lack native support. | |
| What are break and continue statements | |
| break exits a loop or switch statement, while continue skips the current iteration and proceeds to the next one. | |
| What are js labels | |
| Labels are identifiers followed by a colon (e.g., label:) used to mark a statement, allowing break or continue to target specific loops. | |
| What are the benefits of keeping declarations at the top | |
| Keeping declarations at the top improves code readability, avoids hoisting-related errors, and ensures variables are defined before use. | |
| What are the benefits of initializing variables | |
| Initializing variables prevents undefined errors, improves code clarity, and ensures predictable behavior. | |
| What are the recommendations to create new object | |
| Use object literals ({}), Object.create(), or classes for clear, maintainable object creation, avoiding new Object(). | |
| How do you define JSON arrays | |
| JSON arrays are defined as comma-separated values enclosed in square brackets, e.g., [1, "text", { "key": "value" }]. | |
| How do you generate random integers | |
| Use Math.floor(Math.random() * max) to generate random integers between 0 and max - 1. | |
| Can you write a random integers function to print integers within a range | |
| javascript | |
| function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } | |
| What is tree shaking | |
| Tree shaking is a bundling technique that eliminates unused code from the final JavaScript bundle to optimize performance. | |
| What is the need of tree shaking | |
| Tree shaking reduces bundle size, improves load times, and enhances application performance by removing dead code. | |
| Is it recommended to use eval | |
| Using eval is not recommended due to security risks, performance issues, and difficulty in debugging. | |
| What is a Regular Expression | |
| A Regular Expression (regex) is a pattern used to match and manipulate strings based on specific rules. | |
| What are the string methods that accept Regular expression | |
| String methods like match(), replace(), search(), and split() accept regular expressions. | |
| What are modifiers in regular expression | |
| Modifiers like (case-insensitive), (global), and (multiline) alter regex behavior. | |
| What are regular expression patterns | |
| Regex patterns are sequences of characters defining a search pattern, using literals, metacharacters, and quantifiers. | |
| What is a RegExp object | |
| A RegExp object is a JavaScript object for creating and managing regular expressions to match patterns in strings. | |
| How do you search a string for a pattern | |
| Use string.search(regex) to find the index of the first match or regex.test(string) to check if a pattern exists. | |
| What is the purpose of exec method | |
| The exec() method tests for matches in a string and returns an array with match details or null. | |
| How do you change the style of a HTML element | |
| Modify an element’s style using element.style.property = "value" (e.g., element.style.color = "blue"). | |
| What would be the result of 1+2+'3' | |
| The result is "33", as numbers are coerced to strings when concatenated with a string. | |
| What is a debugger statement | |
| The debugger statement pauses code execution, invoking the browser’s debugging tool if available. | |
| What is the purpose of breakpoints in debugging | |
| Breakpoints pause code execution at specific lines, allowing developers to inspect variables and control flow. | |
| Can I use reserved words as identifiers | |
| Reserved words cannot be used as identifiers in strict mode; in non-strict mode, it’s possible but not recommended. | |
| How do you detect a mobile browser | |
| Check the navigator.userAgent string with a regex like /Mobi|Android/i to detect mobile browsers. | |
| How do you detect a mobile browser without regexp | |
| Check for specific substrings in navigator.userAgent (e.g., userAgent.includes("Mobile")). | |
| How do you get the image width and height using JS | |
| Use image.width and image.height properties or naturalWidth and naturalHeight for original dimensions. | |
| How do you make synchronous HTTP request | |
| Use XMLHttpRequest with open("GET", url, false) for synchronous requests, though it’s discouraged. | |
| How do you make asynchronous HTTP request | |
| Use fetch() or XMLHttpRequest with async: true to make asynchronous HTTP requests. | |
| How do you convert date to another timezone in javascript | |
| Use toLocaleString() with the timeZone option (e.g., date.toLocaleString("en-US", { timeZone: "America/New_York" })). | |
| What are the properties used to get size of window | |
| Use window.innerWidth and window.innerHeight for viewport size, or screen.width and screen.height for screen size. | |
| What is a conditional operator in javascript | |
| The conditional (ternary) operator (condition ? expr1 : expr2) evaluates a condition and returns one of two expressions. | |
| Can you apply chaining on conditional operator | |
| Yes, ternary operators can be nested for chaining (e.g., condition1 ? expr1 : condition2 ? expr2 : expr3). | |
| What are the ways to execute javascript after a page load | |
| Use window.onload, DOMContentLoaded event, or defer/async script attributes to run JavaScript after page load. | |
| What is the difference between proto and prototype | |
| __proto__ is an object’s prototype reference, while prototype is a property of constructor functions for inheritance. | |
| Can you give an example of when you really need a semicolon | |
| Semicolons are needed when two statements are on the same line or to prevent ASI issues, e.g., let x = 1; [1,2].forEach(). | |
| What is the freeze method | |
| Object.freeze() makes an object immutable, preventing property additions, deletions, or modifications. | |
| What is the purpose of the freeze method | |
| The freeze method ensures an object’s state cannot be changed, useful for constants or secure data. | |
| Why do I need to use the freeze method | |
| Use Object.freeze() to protect critical data from unintended changes or ensure immutability in functional programming. | |
| How do you detect a browser language preference | |
| Check navigator.language or navigator.languages to get the browser’s preferred language. | |
| How to convert a string to title case with javascript | |
| Split the string, capitalize each word’s first letter, and join: str.toLowerCase().replace(/(^|\s)\w/g, c => c.toUpperCase()). | |
| How do you detect if javascript is disabled on the page | |
| Use a <noscript> tag in HTML to display content when JavaScript is disabled. | |
| What are various operators supported by javascript | |
| JavaScript supports arithmetic (+, -), comparison (==, ===), logical (&&, ||), bitwise (&, |), etc. | |
| What is a rest parameter | |
| The rest parameter (...param) collects all remaining function arguments into an array. | |
| What happens if you do not use rest parameter as a last argument | |
| A rest parameter must be the last parameter; otherwise, a SyntaxError is thrown. | |
| What are the bitwise operators available in javascript | |
| Bitwise operators include & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift), and >>> (unsigned right shift). | |
| What is a spread operator | |
| The spread operator (...) expands elements of an iterable (like arrays) or object properties into individual elements. | |
| How do you determine whether object is frozen or not | |
| Use Object.isFrozen(obj) to check if an object is frozen (immutable). | |
| How do you determine two values same or not using object | |
| Use Object.is(value1, value2) to check if two values are identical, handling edge cases like NaN and -0. | |
| What is the purpose of using object is method | |
| Object.is() provides a precise equality check, distinguishing edge cases like NaN === NaN and -0 !== +0. | |
| How do you copy properties from one object to other | |
| Use Object.assign(target, source) or the spread operator ({ ...source }) to copy properties. | |
| What are the applications of the assign method | |
| Object.assign() is used for cloning objects, merging objects, or setting default properties. | |
| What is a proxy object | |
| A Proxy object wraps another object to intercept and customize operations like property access or assignment. | |
| What is the purpose of the seal method | |
| Object.seal() prevents adding or removing properties but allows modifying existing ones. | |
| What are the applications of the seal method | |
| Object.seal() is used to enforce a fixed structure while allowing value changes, useful for configuration objects. | |
| What are the differences between the freeze and seal methods | |
| freeze() makes an object fully immutable; seal() prevents structural changes but allows property value updates. | |
| How do you determine if an object is sealed or not | |
| Use Object.isSealed(obj) to check if an object is sealed (no new properties, existing ones configurable). | |
| How do you get enumerable key and value pairs | |
| Use Object.entries(obj) to get an array of [key, value] pairs for enumerable properties. | |
| What is the main difference between Object.values and Object.entries method | |
| Object.values() returns an array of enumerable property values, while Object.entries() returns an array of [key, value] pairs. | |
| How can you get the list of keys of any object | |
| Use Object.keys(obj) to get an array of an object’s enumerable property names. | |
| How do you create an object with a prototype | |
| Use Object.create(proto) or set __proto__ in an object literal to define an object with a specific prototype. | |
| What is a WeakSet | |
| A WeakSet is a collection of unique objects where references are weakly held, allowing garbage collection. | |
| What are the differences between WeakSet and Set | |
| WeakSet only stores objects, allows garbage collection, and lacks iteration methods, unlike Set. | |
| List down the collection of methods available on WeakSet | |
| WeakSet methods: add(), delete(), has(). | |
| What is a WeakMap | |
| A WeakMap is a key-value collection where keys are objects, and weak references allow garbage collection. | |
| What are the differences between WeakMap and Map | |
| WeakMap uses objects as keys, allows garbage collection, and lacks iteration methods, unlike Map. | |
| List down the collection of methods available on WeakMap | |
| WeakMap methods: set(), get(), delete(), has(). | |
| What is the purpose of uneval | |
| uneval() (non-standard, deprecated) serializes a JavaScript value into a string representation. | |
| How do you encode an URL | |
| Use encodeURI() or encodeURIComponent() to encode a URL, escaping special characters. | |
| How do you decode an URL | |
| Use decodeURI() or decodeURIComponent() to decode an encoded URL back to its original form. | |
| How do you print the contents of web page | |
| Use window.print() to trigger the browser’s print dialog for the current page. | |
| What is the difference between uneval and eval | |
| uneval() serializes a value to a string, while eval() executes a string as JavaScript code. | |
| What is an anonymous function | |
| An anonymous function is a function without a name, often used as a callback or immediately invoked. | |
| What is the precedence order between local and global variables | |
| Local variables take precedence over global variables with the same name due to scope chain resolution. | |
| What are javascript accessors | |
| Accessors are getter (get) and setter (set) methods that control property access and assignment. | |
| How do you define property on Object constructor | |
| Use Object.defineProperty(Object.prototype, "prop", { value: val }) to add a property to all objects. | |
| What is the difference between get and defineProperty | |
| get defines a getter function for a property, while defineProperty sets detailed property attributes like value or writability. | |
| What are the advantages of Getters and Setters | |
| Getters and setters provide controlled property access, validation, and encapsulation without direct exposure. | |
| Can I add getters and setters using defineProperty method | |
| Yes, use Object.defineProperty(obj, "prop", { get() {}, set(v) {} }) to define getters and setters. | |
| What is the purpose of switch-case | |
| The switch statement evaluates an expression and executes code blocks based on matching cases. | |
| What are the conventions to be followed for the usage of switch case | |
| Use break to prevent fall-through, include a default case, and keep cases simple and consistent. | |
| What are primitive data types | |
| Primitive types are undefined, null, boolean, number, bigint, string, and symbol. | |
| What are the different ways to access object properties | |
| Access properties using dot notation (obj.prop), bracket notation (obj["prop"]), or destructuring. | |
| What are the function parameter rules | |
| Parameters are optional, can have defaults, must be last for rest parameters, and are passed by value (primitives) or reference (objects). | |
| What is an error object | |
| An Error object represents a runtime error, with properties like name, message, and stack. | |
| When do you get a syntax error | |
| A SyntaxError occurs when code violates JavaScript syntax rules, like missing brackets or invalid tokens. | |
| What are the different error names from error object | |
| Common error names: SyntaxError, ReferenceError, TypeError, RangeError, URIError, EvalError. | |
| What are the various statements in error handling | |
| Error handling uses try, catch, finally, and throw statements to manage exceptions. | |
| What are the two types of loops in javascript | |
| The two main loop types are for (including for...in and for...of) and while (including do...while). | |
| What is nodejs | |
| Node.js is a runtime environment that allows JavaScript to run server-side, built on Chrome’s V8 engine. | |
| What is the Intl object | |
| The Intl object provides internationalization features like date, time, and number formatting. | |
| How do you perform language specific date and time formatting | |
| Use Intl.DateTimeFormat(locale, options) to format dates and times for specific languages or regions. | |
| What is an Iterator | |
| An iterator is an object with a next() method that returns { value, done } for iterating over sequences. | |
| How does synchronous iteration works | |
| Synchronous iteration uses iterators with for...of or manual next() calls to process values sequentially. | |
| What is the event loop | |
| The event loop manages asynchronous operations by processing the call stack and event queue in a loop. | |
| What is the call stack | |
| The call stack is a structure that tracks function execution, pushing and popping calls as they start and finish. | |
| What is the event queue | |
| The event queue holds asynchronous tasks (like callbacks or promises) to be processed by the event loop. | |
| What is a decorator | |
| A decorator is a proposed JavaScript feature (not standard) to modify or annotate classes and methods. | |
| What are the properties of the Intl object | |
| Intl properties include Collator, DateTimeFormat, NumberFormat, PluralRules, and Locale. | |
| What is an Unary operator | |
| A unary operator operates on a single operand, like ! (logical NOT), - (negation), or typeof. | |
| How do you sort elements in an array | |
| Use array.sort([compareFunction]) to sort array elements, optionally with a comparison function. | |
| What is the purpose of compareFunction while sorting arrays | |
| The compareFunction(a, b) defines sorting order by returning a negative, zero, or positive value. | |
| How do you reverse an array | |
| Use array.reverse() to reverse the order of elements in an array in place. | |
| How do you find the min and max values in an array | |
| Use Math.min(...array) and Math.max(...array) to find the minimum and maximum values. | |
| How do you find the min and max values without Math functions | |
| Iterate through the array, tracking the smallest and largest values with comparisons. | |
| What is an empty statement and purpose of it | |
| An empty statement (;) does nothing, used as a placeholder in loops or conditionals. | |
| How do you get the metadata of a module | |
| Use import.meta to access metadata like the module’s URL or custom properties. | |
| What is the comma operator | |
| The comma operator (,) evaluates multiple expressions and returns the last one’s value. | |
| What is the advantage of the comma operator | |
| The comma operator allows multiple expressions in a single statement, useful in loops or concise code. | |
| What is typescript | |
| TypeScript is a superset of JavaScript that adds static types and enhanced tooling. | |
| What are the differences between javascript and typescript | |
| TypeScript adds static typing, interfaces, and advanced tooling, while JavaScript is dynamically typed. | |
| What are the advantages of typescript over javascript | |
| TypeScript offers type safety, better IDE support, and early error detection, improving code quality. | |
| What is an object initializer | |
| An object initializer is a syntax to create objects using { key: value } notation. | |
| What is a constructor method | |
| A constructor method is a special class method (constructor) used to initialize new object instances. | |
| What happens if you write constructor more than once in a class | |
| Multiple constructors in a class cause a SyntaxError, as only one constructor is allowed. | |
| How do you call the constructor of a parent class | |
| Use super() in a subclass constructor to call the parent class’s constructor. | |
| How do you get the prototype of an object | |
| Use Object.getPrototypeOf(obj) to get an object’s prototype. | |
| What happens If I pass string type for getPrototype method | |
| Passing a string to Object.getPrototypeOf() throws a TypeError, as it expects an object. | |
| How do you set the prototype of one object to another | |
| Use Object.setPrototypeOf(obj, proto) to set an object’s prototype to another object. | |
| How do you check whether an object can be extended or not | |
| Use Object.isExtensible(obj) to check if an object can have new properties added. | |
| How do you prevent an object from being extend | |
| Use Object.preventExtensions(obj) to make an object non-extensible, blocking new property additions. | |
| What are the different ways to make an object non-extensible | |
| Use Object.preventExtensions(), Object.seal(), or Object.freeze() to restrict extensibility. | |
| How do you define multiple properties on an object | |
| Use Object.defineProperties(obj, { prop1: { value: val1 }, prop2: { value: val2 } }) for multiple properties. | |
| What is the MEAN stack | |
| The MEAN stack is a JavaScript-based framework using MongoDB, Express.js, Angular, and Node.js for web development. | |
| What is obfuscation in javascript | |
| Obfuscation is the process of making JavaScript code hard to read to protect it from reverse engineering. | |
| Why do you need Obfuscation | |
| Obfuscation protects intellectual property, reduces code readability, and deters unauthorized use. | |
| What is Minification | |
| Minification removes unnecessary characters (spaces, comments) from JavaScript code to reduce file size. | |
| What are the advantages of minification | |
| Minification reduces file size, improves load times, and enhances website performance. | |
| What are the differences between obfuscation and Encryption | |
| Obfuscation obscures code for readability, while encryption secures data with a key for confidentiality. | |
| What are the common tools used for minification | |
| Common minification tools include UglifyJS, Terser, and Webpack’s built-in minifiers. | |
| How do you perform form validation using javascript | |
| Use event listeners and DOM methods like checkValidity() or custom logic to validate form inputs. | |
| How do you perform form validation without javascript | |
| Use HTML5 attributes like required, pattern, or type for client-side form validation. | |
| What are the DOM methods available for constraint validation | |
| DOM methods: checkValidity(), reportValidity(), setCustomValidity(). | |
| What are the available constraint validation DOM properties | |
| Properties: validity, validationMessage, willValidate. | |
| What are the validity properties | |
| Validity properties include valueMissing, typeMismatch, patternMismatch, tooLong, tooShort, etc. | |
| Give an example usage of the rangeOverflow property | |
| input.validity.rangeOverflow returns true if an input's value exceeds its max attribute, e.g., <input type="number" max="10" value="15">. | |
| Are enums available in JavaScript | |
| JavaScript does not have built-in enums, but they can be emulated using objects or TypeScript's enum. | |
| What is an enum | |
| An enum is a data type that defines a set of named constants, often used to represent fixed values. | |
| How do you list all properties of an object | |
| Use Object.keys(obj) for enumerable own properties or Object.getOwnPropertyNames(obj) for all own properties. | |
| How do you get property descriptors of an object | |
| Use Object.getOwnPropertyDescriptor(obj, "prop") for a single property or Object.getOwnPropertyDescriptors(obj) for all. | |
| What are the attributes provided by a property descriptor | |
| Attributes include value, writable, enumerable, configurable, get, and set. | |
| How do you extend classes | |
| Use the extends keyword in a class declaration, e.g., class Child extends Parent {}. | |
| How do I modify the URL without reloading the page | |
| Use window.history.pushState(state, "", url) to modify the URL without reloading. | |
| How do you check whether or not an array includes a particular value | |
| Use array.includes(value) to check if an array contains a specific value. | |
| How do you compare scalar arrays | |
| Use array1.every((val, i) => val === array2[i]) and check lengths to compare scalar arrays. | |
| How to get the value from get parameters | |
| Use new URLSearchParams(window.location.search).get("param") to retrieve a GET parameter value. | |
| How do you print numbers with commas as thousand separators | |
| Use number.toLocaleString() or Intl.NumberFormat().format(number) for comma-separated numbers. | |
| What is the difference between Java and JavaScript | |
| Java is a compiled, object-oriented language; JavaScript is a dynamic, interpreted scripting language for web. | |
| Does JavaScript support namespaces | |
| JavaScript does not have built-in namespaces but emulates them using objects or modules. | |
| How do you declare a namespace | |
| Use an object or ES6 module, e.g., const MyNamespace = { func: () => {} }. | |
| How do you invoke JavaScript code in an iframe from the parent page | |
| Use iframe.contentWindow.postMessage() or iframe.contentWindow.functionName() to invoke code. | |
| How do you get the timezone offset of a date object | |
| Use date.getTimezoneOffset() to get the offset in minutes from UTC. | |
| How do you load CSS and JS files dynamically | |
| Create <link> or <script> elements with document.createElement() and append to document.head. | |
| What are the different methods to find HTML elements in DOM | |
| Methods include getElementById, querySelector, getElementsByClassName, getElementsByTagName. | |
| What is jQuery | |
| jQuery is a JavaScript library for simplifying DOM manipulation, event handling, and AJAX. | |
| What is V8 JavaScript engine | |
| V8 is Google's open-source JavaScript engine used in Chrome and Node.js for executing code. | |
| Why do we call JavaScript as dynamic language | |
| JavaScript is dynamic due to its flexible typing, runtime evaluation, and ability to modify objects. | |
| What is a void operator | |
| The void operator evaluates an expression and returns undefined, often used in hyperlinks. | |
| How to set the cursor to wait | |
| Set document.body.style.cursor = "wait" to change the cursor to a loading state. | |
| How do you create an infinite loop | |
| Use while (true) {} or for (;;) {} to create an infinite loop. | |
| Why do you need to avoid with statement | |
| The with statement is discouraged due to ambiguity, performance issues, and strict mode prohibition. | |
| What is the output of the following for loops | |
| Please provide the specific loop code to determine the output. | |
| List down some of the features of ES6 | |
| ES6 features include let, const, arrow functions, template literals, destructuring, and modules. | |
| What is ES6 | |
| ES6 (ECMAScript 2015) is a major JavaScript update introducing modern syntax and features. | |
| Can I redeclare let and const variables | |
| No, let and const cannot be redeclared in the same scope; it causes a SyntaxError. | |
| Does the const variable make the value immutable | |
| const prevents reassignment but does not make object or array values immutable. | |
| What are default parameters | |
| Default parameters allow functions to assign default values to parameters, e.g., function fn(a = 1) {}. | |
| What are template literals | |
| Template literals are strings using backticks ( ) supporting interpolation and multiline text. | |
| How do you write multi-line strings in template literals | |
| Write multiline strings within backticks, e.g., line1\nline2 . | |
| What are nesting templates | |
| Nesting templates involve embedding template literals inside expressions, e.g., ${outer ${inner}} . | |
| What are tagged templates | |
| Tagged templates are functions that process template literals, e.g., tagstr${expr}. | |
| What are raw strings | |
| Raw strings in tagged templates (e.g., String.raw) treat backslashes literally, ignoring escape sequences. | |
| What is destructuring assignment | |
| Destructuring assignment unpacks values from arrays or objects into variables, e.g., const {a, b} = obj. | |
| What are default values in destructuring assignment | |
| Default values in destructuring provide fallbacks, e.g., const {a = 10} = obj. | |
| How do you swap variables in destructuring assignment | |
| Swap variables using [a, b] = [b, a]. | |
| What are enhanced object literals | |
| Enhanced object literals allow shorthand property names, methods, and computed keys, e.g., { prop, method() {} }. | |
| What are dynamic imports | |
| Dynamic imports load modules asynchronously using import(modulePath) returning a promise. | |
| What are the use cases for dynamic imports | |
| Dynamic imports are used for lazy loading, conditional module loading, and reducing initial bundle size. | |
| What are typed arrays | |
| Typed arrays are array-like objects for handling binary data, e.g., Int32Array, Float64Array. | |
| What are the advantages of module loaders | |
| Module loaders improve modularity, dependency management, and lazy loading for better performance. | |
| What is collation | |
| Collation is the process of sorting and comparing strings based on locale-specific rules. | |
| What is for...of statement | |
| The for...of statement iterates over iterable objects like arrays or strings. | |
| What is the output of below spread operator array | |
| Please provide the specific spread operator code to determine the output. | |
| Is PostMessage secure | |
| postMessage is secure if used with proper origin checks; otherwise, it’s vulnerable to attacks. | |
| What are the problems with postmessage target origin as wildcard | |
| Using targetOrigin as * allows any domain to receive messages, risking data leaks. | |
| How do you avoid receiving postMessages from attackers | |
| Validate the event.origin in the message event listener to accept only trusted domains. | |
| Can I avoid using postMessages completely | |
| Yes, use alternatives like direct function calls or shared workers if cross-origin communication isn’t needed. | |
| Is postMessages synchronous | |
| No, postMessage is asynchronous; messages are queued and processed by the event loop. | |
| What paradigm is JavaScript | |
| JavaScript supports multiple paradigms: object-oriented, functional, and imperative. | |
| What is the difference between internal and external JavaScript | |
| Internal JavaScript is embedded in <script> tags; external JavaScript is loaded from separate .js files. | |
| Is JavaScript faster than server-side script | |
| JavaScript speed depends on the engine and context; V8 is fast, but server-side scripts vary by language. | |
| How do you get the status of a checkbox | |
| Use checkbox.checked to get the boolean state of a checkbox (true for checked). | |
| What is the purpose of double tilde operator | |
| The double tilde (~~) truncates decimals, converting a number to its integer part. | |
| How do you convert character to ASCII code | |
| Use string.charCodeAt(index) to get the ASCII code of a character. | |
| What is ArrayBuffer | |
| An ArrayBuffer is a fixed-length raw binary data buffer used with typed arrays. | |
| What is the output of below string expression | |
| Please provide the specific string expression to determine the output. | |
| What is the purpose of Error object | |
| The Error object captures runtime errors, providing details like message and stack. | |
| What is the purpose of EvalError object | |
| EvalError represents errors in eval() usage, though rarely used in modern JavaScript. | |
| What are the list of cases error thrown from non-strict mode to strict mode | |
| Strict mode throws errors for undeclared variables, duplicate parameters, and with statements. | |
| Do all objects have prototypes | |
| Yes, all objects have a prototype except null and objects created with Object.create(null). | |
| What is the difference between a parameter and an argument | |
| Parameters are variables in a function definition; arguments are values passed to the function. | |
| What is the purpose of some method in arrays | |
| array.some(callback) checks if at least one element satisfies the callback condition. | |
| How do you combine two or more arrays | |
| Use array.concat(array2) or the spread operator [...array1, ...array2]. | |
| What is the difference between Shallow and Deep copy | |
| Shallow copy duplicates top-level properties; deep copy recursively copies nested objects. | |
| How do you create specific number of copies of a string | |
| Use string.repeat(count) to create a specific number of string copies. | |
| How do you return all matching strings against a regular expression | |
| Use string.match(regex) with the g flag to return all matches as an array. | |
| How do you trim a string at the beginning or ending | |
| Use string.trim(), string.trimStart(), or string.trimEnd() to remove whitespace. | |
| What is the output of below console statement with unary operator | |
| Please provide the specific console statement to determine the output. | |
| Does JavaScript use mixins | |
| JavaScript doesn’t have built-in mixins but emulates them using object composition or prototypes. | |
| Mixin Example using Object composition | |
| const mixin = { method() {} }; Object.assign(target.prototype, mixin); | |
| Benefits | |
| Mixins enable code reuse, modularity, and composition without deep inheritance hierarchies. | |
| What is a thunk function | |
| A thunk is a function that wraps an expression to delay its evaluation, often used in async code. | |
| What are asynchronous thunks | |
| Asynchronous thunks return promises or handle async operations, often used in Redux. | |
| What is the output of below function calls | |
| Please provide the specific function calls to determine the output. | |
| How to remove all line breaks from a string | |
| Use string.replace(/\n/g, "") to remove all line breaks from a string. | |
| What is the difference between reflow and repaint | |
| Reflow recalculates layout (costly); repaint updates visuals without layout changes. | |
| What happens with negating an array | |
| Negating an array (!array) coerces it to a boolean, returning false if non-empty. | |
| What happens if we add two arrays | |
| Adding arrays (array1 + array2) coerces them to strings and concatenates them. | |
| What is the output of prepend additive operator on falsy values | |
| Please provide the specific expression to determine the output. | |
| How do you create self string using special characters | |
| Use escape sequences like \n, \t, or Unicode \uXXXX in strings. | |
| How do you remove falsy values from an array | |
| Use array.filter(Boolean) to remove falsy values from an array. | |
| How do you get unique values of an array | |
| Use new Set(array) or array.filter((v, i, a) => a.indexOf(v) === i). | |
| What is destructuring aliases | |
| Destructuring aliases rename variables, e.g., const { prop: alias } = obj. | |
| How do you map the array values without using map method | |
| Use a for loop or forEach to transform array values into a new array. | |
| How do you empty an array | |
| Set array.length = 0 or assign array = [] to empty an array. | |
| How do you round numbers to certain decimals | |
| Use number.toFixed(decimals) or Math.round(number * 10 decimals) / 10 decimals. | |
| What is the easiest way to convert an array to an object | |
| Use Object.fromEntries(array.map((v, i) => [i, v])) or { ...array }. | |
| How do you create an array with some data | |
| Use array literals, e.g., const arr = [1, 2, 3], or Array.of(1, 2, 3). | |
| What are the placeholders from console object | |
| Placeholders include %s (string), %d (number), %o (object), and %c (CSS). | |
| Is it possible to add CSS to console messages | |
| Yes, use %c in console.log with CSS, e.g., console.log("%cStyled", "color: blue"). | |
| What is the purpose of dir method of console object | |
| console.dir(obj) displays an interactive object representation in the console. | |
| Is it possible to debug HTML elements in console | |
| Yes, use console.dir(element) to inspect DOM element properties. | |
| How do you display data in a tabular format using console object | |
| Use console.table(data) to display arrays or objects in a table format. | |
| How do you verify that an argument is a Number or not | |
| Use typeof arg === "number" && !isNaN(arg) to verify a number. | |
| How do you create copy to clipboard button | |
| Use navigator.clipboard.writeText(text) on a button click event. | |
| What is the shortcut to get timestamp | |
| Use Date.now() to get the current timestamp in milliseconds. | |
| How do you flattening multi dimensional arrays | |
| Use array.flat(depth) or recursive array.reduce() for flattening arrays. | |
| What is the easiest multi condition checking | |
| Use logical operators (&&, ||) or switch for multiple condition checks. | |
| How do you capture browser back button | |
| Use window.onpopstate to handle browser back/forward navigation events. | |
| How do you disable right click in the web page | |
| Use document.addEventListener("contextmenu", e => e.preventDefault()). | |
| What are wrapper objects | |
| Wrapper objects (Number, String, Boolean) wrap primitives for method access. | |
| What is AJAX | |
| AJAX (Asynchronous JavaScript and XML) enables asynchronous data exchange with a server. | |
| What are the different ways to deal with Asynchronous Code | |
| Use callbacks, promises, async/await, or event listeners for asynchronous code. | |
| How to cancel a fetch request | |
| Use AbortController and controller.abort() to cancel a fetch request. | |
| What is web speech API | |
| The Web Speech API enables speech recognition and synthesis in web applications. | |
| What is minimum timeout throttling | |
| Minimum timeout throttling limits setTimeout delays (e.g., 4ms) to prevent CPU overload. | |
| How do you implement zero timeout in modern browsers | |
| Use setTimeout(fn, 0) or queueMicrotask(fn) for near-immediate execution. | |
| What are tasks in event loop | |
| Tasks are queued operations (e.g., timers, I/O) processed by the event loop. | |
| What is microtask | |
| Microtasks are high-priority tasks (e.g., promises) executed before regular tasks. | |
| What are different event loops | |
| Browsers and Node.js have distinct event loops handling tasks and microtasks differently. | |
| What is the purpose of queueMicrotask | |
| queueMicrotask(fn) schedules a microtask for execution after the current task. | |
| How do you use JavaScript libraries in TypeScript file | |
| Import libraries with type definitions or declare them using declare module. | |
| What are the differences between promises and observables | |
| Promises handle single async values; observables handle streams of values over time. | |
| What is heap | |
| The heap is a memory area for storing objects and complex data in JavaScript. | |
| What is an event table | |
| The event table maps events to callbacks, used by the event loop for processing. | |
| What is a microTask queue | |
| The microtask queue holds high-priority tasks like promise resolutions, processed before tasks. | |
| What is the difference between shim and polyfill | |
| A shim adds missing functionality; a polyfill specifically emulates modern APIs for older browsers. | |
| How do you detect primitive or non-primitive value type | |
| Use typeof for primitives; check instanceof Object or Array.isArray for non-primitives. | |
| What is Babel | |
| Babel is a JavaScript transpiler that converts modern code to compatible older syntax. | |
| Is Node.js completely single threaded | |
| Node.js is single-threaded for JavaScript execution but uses threads for I/O operations. | |
| What are the common use cases of observables | |
| Observables are used for event streams, async data handling, and reactive programming. | |
| What is RxJS | |
| RxJS is a library for reactive programming using observables to handle asynchronous data. | |
| What is the difference between Function constructor and function declaration | |
| Function constructor creates functions dynamically; function declarations are static and hoisted. | |
| What is a Short circuit condition | |
| Short-circuiting occurs when logical operators (&&, ||) skip evaluation based on initial conditions. | |
| What is the easiest way to resize an array | |
| Set array.length = newLength to resize an array, truncating or extending it. | |
| What is an observable | |
| An observable is a data stream that emits multiple values over time, used in reactive programming. | |
| What is the difference between function and class declarations | |
| Function declarations create functions; class declarations define blueprints for objects with methods. | |
| What is an async function | |
| An async function returns a promise and allows await for asynchronous operations. | |
| How do you prevent promises swallowing errors | |
| Use .catch() or try/catch with await to handle promise rejections. | |
| What is Deno | |
| Deno is a secure JavaScript/TypeScript runtime with built-in utilities and no node_modules. | |
| How do you make an object iterable in JavaScript | |
| Add a [Symbol.iterator] method returning an iterator object to make an object iterable. | |
| What is a Proper Tail Call | |
| A Proper Tail Call is a function call in the tail position optimized to reuse the stack frame. | |
| How do you check an object is a promise or not | |
| Check if obj instanceof Promise or verify then method existence. | |
| How to detect if a function is called as constructor | |
| Check if this is an instance of the function using instanceof in the function body. | |
| What are the differences between arguments object and rest parameter | |
| arguments is an array-like object for all arguments; rest (...args) is a true array. | |
| What are the differences between spread operator and rest parameter | |
| Spread (...) expands iterables; rest (...args) collects arguments into an array. | |
| What are the different kinds of generators | |
| Generators include function generators (function*) and async generators (async function*). | |
| What are the built-in iterables | |
| Built-in iterables include arrays, strings, maps, sets, and typed arrays. | |
| What are the differences between for...of and for...in statements | |
| for...of iterates over values of iterables; for...in iterates over enumerable object keys. | |
| How do you define instance and non-instance properties | |
| Instance properties are defined in constructors or classes; non-instance (static) use static. | |
| What is the difference between isNaN and Number.isNaN? | |
| isNaN coerces values; Number.isNaN strictly checks for NaN without coercion. | |
| How to invoke an IIFE without any extra brackets? | |
| Use void function() {}() or !function() {}() to invoke an IIFE without parentheses. | |
| Is that possible to use expressions in switch cases? | |
| Yes, case can use expressions if they resolve to values matching the switch expression. | |
| What is the easiest way to ignore promise errors? | |
| Use .catch(() => {}) to silently ignore promise rejections. | |
| How do style the console output using CSS? | |
| Use %c in console.log, e.g., console.log("%cText", "color: red; font-size: 20px"). | |
| What is nullish coalescing operator (??)? | |
| The ?? operator returns the right operand if the left is null or undefined. | |
| How do you group and nest console output? | |
| Use console.group() and console.groupEnd() to create nested console output groups. | |
| What is the difference between dense and sparse arrays? | |
| Dense arrays have all indices defined; sparse arrays have gaps (undefined indices). | |
| What are the different ways to create sparse arrays? | |
| Create sparse arrays using new Array(length), array[length] = value, or deleting elements. | |
| What is the difference between setTimeout, setImmediate and process.nextTick? | |
| setTimeout delays tasks; setImmediate (Node.js) runs after I/O; process.nextTick runs before microtasks. | |
| How do you reverse an array without modifying original array? | |
| Use [...array].reverse() or array.slice().reverse() to reverse without mutating. | |
| How do you create custom HTML element? | |
| Extend HTMLElement and use customElements.define("name", Class) to create a custom element. | |
| What is global execution context? | |
| The global execution context is the base context for global code, managing global variables and functions. | |
| What is function execution context? | |
| A function execution context is created for each function call, managing its scope and variables. | |
| What is debouncing? | |
| Debouncing delays function execution until after a set time of inactivity to prevent rapid calls. | |
| What is throttling? | |
| Throttling limits function execution to a fixed rate, ensuring it runs at most once per interval. | |
| What is optional chaining? | |
| Optional chaining (?.) safely accesses properties/methods, returning undefined if nullish. | |
| What is an environment record? | |
| An environment record stores variable bindings and scope information in an execution context. | |
| How to verify if a variable is an array? | |
| Use Array.isArray(var) to check if a variable is an array. | |
| What is pass by value and pass by reference? | |
| Primitives are passed by value (copied); objects are passed by reference (shared). | |
| What are the differences between primitives and non-primitives? | |
| Primitives are immutable and stored by value; non-primitives are mutable and stored by reference. | |
| How do you create your own bind method using either call or apply method? | |
| javascript | |
| Function.prototype.customBind = function(context, ...args) { | |
| return (...innerArgs) => this.call(context, ...args, ...innerArgs); | |
| }; | |
| What are the differences between pure and impure functions? | |
| Pure functions have no side effects and consistent outputs; impure functions modify state or depend on external data. | |
| What is referential transparency? | |
| Referential transparency means a function’s output is predictable and replaceable with its result without changing behavior. | |
| What are the possible side-effects in JavaScript? | |
| Side effects include modifying external state, DOM changes, I/O operations, and global variable mutations. | |
| What are compose and pipe functions? | |
| Compose applies functions right-to-left; pipe applies them left-to-right for function composition. | |
| What is module pattern? | |
| The module pattern uses IIFEs or ES6 modules to encapsulate private data and expose a public API. | |
| What is Function Composition? | |
| Function composition combines multiple functions where the output of one is the input of another. | |
| How to use await outside of async function prior to ES2022? | |
| Use an IIFE, e.g., (async () => { await promise })() to use await outside async functions. | |
| What is the purpose of the this keyword in JavaScript? | |
| The this keyword refers to the context object of a function, determined by how it’s called. | |
| What are the uses of closures? | |
| Closures enable private variables, data encapsulation, and function factories in JavaScript. | |
| What are the phases of execution context? | |
| Execution context phases are creation (variable setup) and execution (code running). | |
| What are the possible reasons for memory leaks? | |
| Memory leaks occur from unremoved event listeners, global variables, or retained closures. | |
| What are the optimization techniques of V8 engine? | |
| V8 uses JIT compilation, inline caching, hidden classes, and garbage collection for optimization. | |
| What are the examples of built-in higher order functions? | |
| Examples include map, filter, reduce, forEach, and some. | |
| What are the benefits higher order functions? | |
| Higher-order functions promote reusability, abstraction, and functional programming patterns. | |
| How do you create polyfills for map, filter and reduce methods? | |
| javascript | |
| Array.prototype.myMap = function(cb) { let arr = []; for (let i = 0; i < this.length; i++) arr.push(cb(this[i], i, this)); return arr; }; | |
| Array.prototype.myFilter = function(cb) { let arr = []; for (let i = 0; i < this.length; i++) if (cb(this[i], i, this)) arr.push(this[i]); return arr; }; | |
| Array.prototype.myReduce = function(cb, initial) { let acc = initial; for (let i = 0; i < this.length; i++) acc = cb(acc, this[i], i, this); return acc; }; | |
| What is the difference between map and forEach functions? | |
| map returns a new array with transformed values; forEach executes a function without returning. | |
| Give an example of statements affected by automatic semicolon insertion? | |
| return\nvalue becomes return; value; due to automatic semicolon insertion. | |
| What are the event phases of a browser? | |
| Event phases are capturing, target, and bubbling during event propagation. | |
| What are the real world use cases of proxy? | |
| Proxies are used for data validation, logging, access control, and lazy loading. | |
| What are hidden classes? | |
| Hidden classes are V8’s internal structures for optimizing object property access. | |
| What is inline caching? | |
| Inline caching optimizes function calls by caching property lookup results in V8. | |
| What are the different ways to execute external scripts? | |
| Use <script src="file.js">, dynamic <script> creation, or import for external scripts. | |
| What is Lexical Scope? | |
| Lexical scope determines variable accessibility based on where functions are defined. | |
| How to detect system dark mode in JavaScript? | |
| Use window.matchMedia("(prefers-color-scheme: dark)").matches to detect dark mode. | |
| What is the purpose of requestAnimationFrame method? | |
| requestAnimationFrame schedules animations to sync with the browser’s refresh rate. | |
| What is the difference between substring and substr methods? | |
| substring(start, end) uses start/end indices; substr(start, length) uses start and length. | |
| How to find the number of parameters expected by a function? | |
| Use function.length to get the number of expected parameters. | |
| What is globalThis, and what is the importance of it? | |
| globalThis provides a universal reference to the global object across environments. | |
| What are the array mutation methods? | |
| Mutation methods include push, pop, shift, unshift, splice, sort, reverse. | |
| What is module scope in JavaScript? | |
| Module scope isolates variables in ES6 modules, accessible only via imports/exports. | |
| What are shadowing and illegal shadowing? | |
| Shadowing redeclares a variable in a nested scope; illegal shadowing occurs with let in strict mode. | |
| Why is it important to remove event listeners after use? | |
| Removing event listeners prevents memory leaks and unintended behavior in long-running apps. |