0% found this document useful (0 votes)
3 views

JS Interview

The document provides a comprehensive overview of JavaScript, covering its basics, variables, functions, objects, asynchronous programming, DOM manipulation, error handling, ES6 features, and advanced concepts. It includes explanations of key topics such as prototypes, promises, event handling, performance optimization, and security measures. Additionally, it discusses functional programming, web APIs, and various JavaScript engines and their roles.

Uploaded by

Patel Anshu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JS Interview

The document provides a comprehensive overview of JavaScript, covering its basics, variables, functions, objects, asynchronous programming, DOM manipulation, error handling, ES6 features, and advanced concepts. It includes explanations of key topics such as prototypes, promises, event handling, performance optimization, and security measures. Additionally, it discusses functional programming, web APIs, and various JavaScript engines and their roles.

Uploaded by

Patel Anshu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1.

JavaScript Basics
1. What is JavaScript?
A lightweight, interpreted scripting language used to create dynamic content on
websites.

1. What are the key features of JavaScript?


Dynamic typing, object-oriented, asynchronous programming support, and platform
independence.

2. What is the difference between var, let, and const?


var has function scope, let and const have block scope; const is for immutable
bindings.

3. What are JavaScript data types?


Six primitives: String, Number, Boolean, Null, Undefined, Symbol; and Objects.

4. What is typeof?
A JavaScript operator that returns the type of a given variable or value.

2. Variables and Scope


1. What is hoisting in JavaScript?
Variables and functions are moved to the top of their scope before code execution.

1. What is the difference between function scope and block scope?


Function scope applies to var, block scope applies to let and const.

2. Explain closures in JavaScript.


Functions that "remember" the scope in which they were created, even if executed
outside.

3. What is the Temporal Dead Zone (TDZ)?


A phase where let and const variables cannot be accessed before their declaration.

4. What is a global variable?


A variable declared outside any function, accessible from any part of the code.

3. Functions
1. What are the different types of functions in JavaScript?
Named, anonymous, arrow, IIFE (Immediately Invoked Function Expressions).

1. What is the difference between function declaration and function expression?


Declarations are hoisted, expressions are not.
2. What is an arrow function?
A concise syntax for functions that does not bind its own this.

3. How do default parameters work in functions?


Default values are used when no argument or undefined is passed.

4. What is the difference between call, apply, and bind?


call and apply invoke functions immediately; bind creates a new function with
this set.

4. Objects and Arrays


1. How do you create objects in JavaScript?
Using object literals {}, constructors, or Object.create().

1. What is the difference between shallow and deep copy of objects?


Shallow copies duplicate references; deep copies duplicate nested structures.

2. What are JavaScript array methods?


Examples: push(), pop(), slice(), splice(), map(), reduce(), filter().

3. What is object destructuring?


A syntax to extract values from objects into variables.

4. What is the spread operator (...)?


Expands an array or object into individual elements or properties.

5. Prototypes and Inheritance


1. What is a prototype in JavaScript?
An object from which other objects inherit properties.

1. How does inheritance work in JavaScript?


Using prototypes, objects can share methods and properties.

2. What is the difference between __proto__ and prototype?


__proto__ is an object's prototype; prototype is a property of constructor
functions.

3. What is a constructor function?


A special function used to initialize new objects.

4. What is ES6 class syntax?


A cleaner way to implement constructor functions and inheritance.
6. Asynchronous JavaScript
1. What is the Event Loop?
The mechanism handling asynchronous operations in JavaScript.

1. What are Promises in JavaScript?


Objects representing a value that may be available now, in the future, or never.

2. What is async/await?
Syntactic sugar for writing asynchronous code more synchronously.

3. What is the difference between setTimeout and setInterval?


setTimeout executes once; setInterval repeats at specified intervals.

4. What are callback functions?


Functions passed as arguments to be executed later.

7. DOM Manipulation
1. What is the DOM?
A programming interface for HTML and XML documents.

1. How do you select elements in the DOM?


Using methods like getElementById, querySelector, and getElementsByClassName.

2. What is the difference between innerHTML and textContent?


innerHTML includes HTML tags; textContent does not.

3. How do you add an element to the DOM?


Use createElement, then append with appendChild or append.

4. What is event delegation?


Attaching a single event listener to a parent element for multiple child elements.

8. Error Handling
1. How do you handle errors in JavaScript?
Using try, catch, finally blocks or Promise.catch.

1. What is throw in JavaScript?


A statement to generate custom errors.

2. What are JavaScript error types?


SyntaxError, ReferenceError, TypeError, RangeError, EvalError.
3. What is the purpose of finally block?
Executes code after try and catch, regardless of an error.

4. How do you debug JavaScript?


Use browser developer tools, console.log, or breakpoints.

9. ES6 and Beyond


1. What are template literals?
String literals allowing embedded expressions using backticks.

1. What are JavaScript modules?


Reusable pieces of code exported and imported using export and import.

2. What are generators in JavaScript?


Functions that can be paused and resumed using yield.

3. What are symbols in JavaScript?


Unique, immutable identifiers useful as object keys.

4. What is the difference between for...of and for...in?


for...of iterates values, for...in iterates keys.

10. Advanced Concepts


1. What is currying in JavaScript?
Transforming a function with multiple arguments into a sequence of functions with
one argument each.

1. What is memoization?
Caching function results to optimize performance for repetitive calls with the same
input.

2. What is the difference between synchronous and asynchronous code?


Synchronous code executes sequentially; asynchronous code allows other tasks to
run while waiting.

3. What are JavaScript decorators?


Functions that modify the behavior of other functions, often used in classes.

4. What is the difference between deep and shallow comparison?


Shallow comparison checks references; deep comparison checks actual values
recursively.
11. Type Conversion
1. What is implicit type coercion?
JavaScript automatically converts values to a common type during operations.

1. What is NaN in JavaScript?


A special value representing "Not-a-Number", e.g., result of invalid math operations.

2. What is the difference between == and ===?


== allows type coercion; === checks both value and type equality.

3. What is type casting in JavaScript?


Explicit conversion of one data type to another, e.g., String() or Number().

4. How do you check if a value is a number?


Use typeof value === 'number' && !isNaN(value) for accurate checks.

12. Events
1. What are event listeners?
Functions triggered when an event occurs, added with addEventListener.

1. What is the difference between event.preventDefault() and


event.stopPropagation()?
preventDefault stops default browser behavior; stopPropagation prevents event
bubbling.

2. What are bubbling and capturing?


Phases of event propagation: bubbling (child to parent), capturing (parent to child).

3. How do you remove an event listener?


Use removeEventListener with the same function reference.

4. What are custom events?


User-defined events created and dispatched using CustomEvent and dispatchEvent.

13. Performance and Optimization


1. How do you optimize JavaScript code?
Minify code, cache variables, use lazy loading, and avoid memory leaks.

1. What is debounce in JavaScript?


A technique to delay execution of a function until after a specified period.

2. What is throttling?
Limiting the execution of a function to once in a specified interval.
3. What are web workers?
JavaScript scripts that run in the background, separate from the main thread.

4. How do you prevent memory leaks?


Manage DOM references, use WeakMap/WeakSet, and clear timers or event listeners.

14. Promises and Async/Await


1. What are the states of a Promise?
Pending, Fulfilled, and Rejected.

1. What is the difference between .then() and .catch()?


.then() handles fulfilled Promises; .catch() handles rejections.

2. What is Promise.all()?
Resolves when all Promises in an array resolve or rejects if one fails.

3. What is Promise.race()?
Resolves or rejects as soon as the first Promise in an array resolves or rejects.

4. How does async/await handle errors?


Use try and catch blocks to handle rejected Promises.

15. Regular Expressions


1. What are regular expressions?
Patterns used to match strings or perform text-based operations.

1. What does the g flag in regular expressions mean?


Indicates a global search, matching all instances in a string.

2. How do you test a string against a regex?


Use the test method, e.g., /pattern/.test(string).

3. What is the exec method in regex?


Returns the first match along with capturing groups for more details.

4. What does the i flag in regular expressions mean?


Indicates a case-insensitive match.

16. Miscellaneous Topics


1. What is the difference between window and document?
window is the global browser object; document represents the HTML page.

1. What is strict mode in JavaScript?


A mode that enforces stricter parsing and error handling, enabled by "use strict".
2. What is the this keyword?
Refers to the object that is executing the current function.

3. How do you create a module in JavaScript?


Use export to define and import to consume modules.

4. What is the difference between mutable and immutable objects?


Mutable objects can be changed; immutable objects cannot.

17. Security in JavaScript


1. What is Cross-Site Scripting (XSS)?
An attack where malicious scripts are injected into web pages.

1. How do you prevent XSS in JavaScript?


Sanitize user inputs and use proper encoding.

2. What is Cross-Site Request Forgery (CSRF)?


An attack forcing a user to perform actions without their consent.

3. How do you prevent CSRF?


Use CSRF tokens and validate requests.

4. What is the Content Security Policy (CSP)?


A browser feature to prevent certain types of attacks by restricting resources
loaded.

18. ES6+ Features


1. What are iterators in JavaScript?
Objects enabling traversal of collections with a next() method.

1. What is the purpose of Map and Set?


Map stores key-value pairs; Set stores unique values.

2. What is destructuring assignment?


A syntax for unpacking values from arrays or objects into variables.

3. What is the difference between Object.freeze() and Object.seal()?


freeze makes objects immutable; seal prevents adding/removing properties.

4. What is optional chaining (?.)?


A syntax to safely access deeply nested properties.
19. JavaScript Engines and Runtime
1. What is a JavaScript engine?
A program that executes JavaScript code, e.g., Google’s V8, SpiderMonkey.

1. What is the difference between JIT and AOT compilation?


JIT compiles code during runtime; AOT compiles before runtime.

2. How does the JavaScript runtime environment work?


It combines the call stack, Web APIs, and the event loop to execute code.

3. What is the role of V8 in JavaScript?


V8 is a high-performance JavaScript engine used by Chrome and Node.js.

4. What are Web APIs in JavaScript?


Browser-provided features, e.g., DOM, Fetch API, and Geolocation API.

20. Error Types and Debugging


1. What is a SyntaxError?
An error caused by invalid JavaScript syntax.

1. What is a ReferenceError?
An error raised when trying to access an undefined variable.

2. What is a TypeError?
An error caused by using a value in an invalid operation for its type.

3. How can you debug a JavaScript program?


Use console.log, browser dev tools, and breakpoints.

4. What is the purpose of console.error()?


To log errors to the console for debugging purposes.

21. Event Handling


1. What is the difference between onclick and addEventListener?
onclick overrides existing handlers; addEventListener allows multiple listeners.

1. What is an event object in JavaScript?


A representation of the event, passed automatically to event handlers.

2. What is the target property in an event?


Refers to the element that triggered the event.
3. How do you stop an event from propagating?
Use stopPropagation() to prevent bubbling or capturing.

4. What are passive event listeners?


Event listeners optimized for scroll performance by declaring they won't call
preventDefault.

22. Modules and Imports


1. What is the difference between named and default exports?
Named exports have specific names; default exports can be imported with any
name.

1. How do you import a default export?


Use import name from './module.js';.

2. What is the purpose of import.meta?


Provides metadata about the current module, e.g., URL or environment.

3. What are dynamic imports in JavaScript?


Importing modules dynamically using import() when needed.

4. How do you use multiple named exports?


Import them using {}: import { a, b } from './module.js';.

23. Functional Programming in JavaScript


1. What is functional programming?
A programming paradigm emphasizing immutability and pure functions.

1. What are pure functions?


Functions with no side effects that return the same output for the same input.

2. What is the purpose of Array.prototype.map()?


To create a new array by transforming each element in an array.

3. What is the purpose of reduce()?


To accumulate values into a single result from an array.

4. What is immutability in JavaScript?


The principle of avoiding changes to objects and arrays.

24. Advanced Array Concepts


1. What is the difference between map() and forEach()?
map() returns a new array; forEach() processes elements without returning.
1. What is the flat() method in arrays?
Flattens nested arrays into a single-level array.

2. How does filter() work?


Creates a new array with elements that satisfy the given condition.

3. What is the some() method in JavaScript?


Tests if at least one element in the array satisfies the condition.

4. What does find() do?


Returns the first array element that satisfies the condition.

25. Web APIs and Storage


1. What is the Fetch API?
A modern interface for making HTTP requests.

1. What is localStorage?
A browser storage feature for key-value pairs with no expiration.

2. What is sessionStorage?
A storage feature that persists data only during a page session.

3. What is the difference between cookies and localStorage?


Cookies are sent with requests; localStorage is not.

4. How do you set and get items from localStorage?


Use localStorage.setItem(key, value) and localStorage.getItem(key).

26. Performance and Rendering


1. What is lazy loading?
Deferring the loading of resources until needed.

1. What is the purpose of the defer attribute in <script>?


Defers script execution until the HTML is fully parsed.

2. What is DOMContentLoaded?
An event fired when the initial HTML document is fully loaded and parsed.

3. What are repaint and reflow?


Repaint updates appearance; reflow recalculates layout, both impacting
performance.

4. What is a virtual DOM?


An abstraction of the DOM for efficient updates in libraries like React.
27. Miscellaneous Concepts
1. What is an IIFE?
An Immediately Invoked Function Expression executed as soon as it’s defined.

1. What are tagged template literals?


Template literals with a tag function to process the string and substitutions.

2. What is the difference between undefined and null?


undefined means a variable is declared but not assigned; null is explicitly empty.

3. What are bitwise operators in JavaScript?


Operators performing operations on binary representations, e.g., &, |.

4. What is the purpose of Object.assign()?


Copies properties from one or more objects to a target object.

28. Testing JavaScript


1. What are unit tests in JavaScript?
Tests for individual functions or components.

1. What are common JavaScript testing libraries?


Jest, Mocha, Jasmine, and Cypress.

2. What is TDD in JavaScript?


Test-Driven Development, writing tests before writing actual code.

3. What is mocking in testing?


Creating fake functions or objects to simulate real ones during tests.

4. How do you test asynchronous code?


Use async/await or callbacks in your test frameworks.

29. Error Handling and Logging


1. What is the purpose of try-catch in JavaScript?
To handle errors gracefully during runtime.

1. What is the finally block?


Executes code after try and catch, regardless of the outcome.

2. What are custom errors in JavaScript?


User-defined error types created using class extending Error.
3. What is stack trace in JavaScript errors?
A report of the call stack showing where an error occurred.

4. How do you log errors to an external system?


Use HTTP requests or APIs to send error details to logging systems.

30. Generators and Iterators


1. What are generator functions?
Functions that yield multiple values using function* and yield.

1. What does the next() method do in generators?


Resumes execution of a generator and returns { value, done }.

2. How are iterators implemented in JavaScript?


By defining an object with a next method returning { value, done }.

3. What is the purpose of yield* in generators?


Delegates to another generator or iterable, yielding all its values.

4. What is the difference between a generator and an async function?


Generators use yield for synchronous steps; async functions use await for
asynchronous operations.

31. JavaScript Classes


1. What are ES6 classes in JavaScript?
Syntactic sugar over JavaScript's prototype-based inheritance.

1. What is the difference between class and function constructors?


class constructors require new and are stricter; function constructors are more
flexible.

2. What is the super keyword?


Refers to the parent class and is used to call parent constructors or methods.

3. What is the difference between static and instance methods?


Static methods belong to the class, while instance methods belong to class objects.

4. What is the purpose of private fields in JavaScript classes?


To encapsulate data, denoted by #, accessible only within the class.

32. Prototypes and Inheritance


1. What is the prototype chain in JavaScript?
A chain of objects used for inheritance and property lookup.
1. How do you define inheritance in JavaScript?
Use extends in classes or Object.create() for objects.

2. What is Object.create() used for?


Creates an object with a specific prototype.

3. What is the __proto__ property?


A reference to the object's prototype, deprecated in modern usage.

4. What is the Object.getPrototypeOf() method?


Retrieves the prototype of an object safely.

33. Promises and Async/Await


1. What is Promise.allSettled()?
Resolves after all Promises are settled, regardless of success or failure.

1. What is Promise.any()?
Resolves when the first Promise is fulfilled, ignoring rejections.

2. What is the difference between async functions and Promises?


Async functions are syntactic sugar over Promises, making them easier to work
with.

3. What is chaining in Promises?


Connecting multiple .then() calls to sequence asynchronous tasks.

4. How do you handle multiple async tasks in sequence?


Use async/await or chain Promises using .then().

34. Advanced Regular Expressions


1. What does the ^ symbol do in regex?
Matches the start of a string.

1. What does the $ symbol do in regex?


Matches the end of a string.

2. What is a capturing group in regex?


A part of a pattern enclosed in parentheses to extract matched substrings.

3. What does the \d pattern match?


Matches any digit (0–9).

4. How do you make a regex non-capturing?


Use (?:...) for the non-capturing group.
35. ES6+ Features
1. What is the spread operator (...)?
Expands arrays or objects into individual elements or properties.

1. What are rest parameters?


Collects multiple arguments into a single array, denoted by ....

2. What is the Symbol type in JavaScript?


A unique and immutable primitive value, often used as object keys.

3. What are computed property names?


Dynamically define object property names using expressions within [].

4. What is the purpose of WeakMap and WeakSet?


Collections of objects with no strong references, preventing memory leaks.

36. Asynchronous Patterns


1. What is a callback hell?
Nested callbacks leading to unreadable and difficult-to-maintain code.

1. What is the solution to callback hell?


Use Promises or async/await to flatten asynchronous code.

2. What is the difference between microtasks and macrotasks?


Microtasks (e.g., Promises) execute before macrotasks (e.g., setTimeout) in the
event loop.

3. How does setImmediate work in Node.js?


Schedules a callback to execute immediately after I/O events are processed.

4. What is the queueMicrotask function?


Schedules a microtask to be executed at the earliest opportunity.

37. Networking and APIs


1. What is the difference between GET and POST?
GET retrieves data; POST sends data to the server.

1. What is CORS?
Cross-Origin Resource Sharing, a policy controlling resource sharing between
origins.

2. How do you handle CORS errors in JavaScript?


Configure server-side headers like Access-Control-Allow-Origin.
3. What is the difference between XMLHttpRequest and fetch()?
fetch() is modern and promise-based; XMLHttpRequest is older and callback-based.

4. What is JSON?
A lightweight data format for storing and exchanging data, commonly used in APIs.

38. Browser-Specific Concepts


1. What is the history API in JavaScript?
Allows manipulation of browser history using pushState and replaceState.

1. What is the difference between sessionStorage and cookies?


sessionStorage stores data for a session; cookies are sent with every HTTP
request.

2. What is the navigator object?


Represents the state and identity of the browser, e.g., user agent, geolocation.

3. What is the location object in JavaScript?


Represents the URL of the current page and allows redirection.

4. What is the Screen object in JavaScript?


Provides information about the user's screen dimensions and settings.

39. Miscellaneous Questions


1. What is event delegation?
Leveraging a parent element to manage events for its children.

1. What is a polyfill in JavaScript?


Code that provides modern functionality in older environments.

2. How does Object.entries() work?


Returns an array of key-value pairs from an object.

3. What is the Reflect API in JavaScript?


Provides static methods for interceptable operations on objects.

4. What is the difference between delete and null?


delete removes a property from an object; null resets its value.

40. Interview-Specific
1. What is hoisting?
Variables and functions are moved to the top of their scope during compilation.
1. How do you implement a debounce function?
Use setTimeout to delay a function call until after the user stops triggering it.

2. What are weak references in JavaScript?


References that don't prevent garbage collection, e.g., in WeakMap.

3. How do you shallow clone an object?


Use Object.assign() or the spread operator ({ ...obj }).

4. How do you deep clone an object?


Use JSON.parse(JSON.stringify(obj)) or libraries like Lodash.

You might also like