JavaScript & TypeScript Interview Questions
1. What is EC6 (ES6)?
ES6 (ECMAScript 2015) is the 6th major version of the ECMAScript language specification standard. It brought significant changes and new features to JavaScript, making it more robust and easier to write.
* Key features: let/const, Arrow functions, Template Literals, Classes, Modules, Promises, Destructuring.
2. What is Hoisting?
Hoisting is a JavaScript mechanism where variable and function declarations are moved ("hoisted") to the top of their scope (global or function) during the compilation phase, before code execution.
* Functions: Fully hoisted (can be called before definition).
* var: Hoisted but initialized with undefined.
* let and const: Hoisted but stay in the Temporal Dead Zone (TDZ). Accessing them before declaration throws a ReferenceError.
3. What are the differences between Var, Let, and Const?
| Feature | var |
let |
const |
|---|---|---|---|
| Scope | Function Scope | Block Scope ({}) |
Block Scope ({}) |
| Hoisting | Yes (initialized undefined) |
Yes (TDZ) | Yes (TDZ) |
| Reassignable | Yes | Yes | No (immutable reference) |
| Redeclarable | Yes | No | No |
4. What is the difference between == and ===?
==(Loose Equality): Compares values after performing type coercion (converting types to match). E.g.,5 == "5"istrue.===(Strict Equality): Compares both value and type without coercion. E.g.,5 === "5"isfalse. Always prefer===.
5. How does JavaScript compile?
JavaScript is an interpreted (or JIT compiled) language. 1. Parsing: The engine parses code into an AST (Abstract Syntax Tree). 2. Compilation (JIT): Modern engines (like V8) compile AST to Bytecode and optimize "hot" functions into machine code on the fly during execution. 3. Execution: The machine code/bytecode is executed within the Call Stack.
6. What does “this” refer to?
this refers to the object that is executing the current function. Its value depends on how the function is called:
1. Method call: Refers to the object (obj.func() -> this is obj).
2. Simple function call: Refers to Global Object (window) or undefined (in strict mode).
3. Arrow function: Inherits this from the enclosing lexical scope (does not have its own this).
4. Event listener: Refers to the element that received the event.
5. new keyword: Refers to the newly created instance.
7. What are JavaScript Scopes?
Scope determines the accessibility (visibility) of variables.
1. Global Scope: Accessible everywhere.
2. Function Scope: Accessible only within the function.
3. Block Scope (ES6): Accessible only within the block {} (for let and const).
8. What is closure in JavaScript?
A Closure is a function bundled together with references to its surrounding state (the lexical environment). * In simple terms, a closure gives a function access to variables from its outer (enclosing) function, even after the outer function has finished executing. * Use cases: Data privacy (emulating private methods), memoization, currying.
9. What is Callback Hell?
Callback Hell is a situation where callbacks are nested within other callbacks several levels deep, making the code difficult to read and maintain (Pyramid of Doom). * Solution: Use Promises or Async/Await.
10. What is a Promise?
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
* States: Pending, Fulfilled (Resolved), Rejected.
* Usage: .then(), .catch(), .finally().
11. What are some new features introduced with ES6?
letandconst- Arrow Functions
() => {} - Template Literals
`Hello ${name}` - Destructuring Assignment
const {name} = obj - Default Parameters
function(a=1) - Rest/Spread Operator
... - Classes
- Modules (import/export)
- Promises
12. What is Event Propagation?
The mechanism that defines how events travel through the DOM tree to arrive at its target and what happens afterwards. 1. Capturing Phase: Event goes down from Window -> Target. 2. Target Phase: Event reaches the target element. 3. Bubbling Phase: Event bubbles up from Target -> Window.
13. What is event.preventDefault?
It prevents the browser's default behavior associated with the event. * Example: Prevents a form from submitting (reloading page) or a link from navigating to a URL.
14. Is JavaScript a single or multithreaded language?
JavaScript is Single-Threaded. It has one Call Stack and can do one thing at a time. * However, it handles asynchronous operations (like Web APIs, Timers, Fetch) using the Event Loop and Callback Queue, giving the illusion of multitasking.
15. What is the Event Loop?
The Event Loop is a mechanism that constantly monitors the Call Stack and the Callback Queue. * If the Call Stack is empty, it takes the first event from the Callback Queue and pushes it to the Call Stack to be executed. This allows non-blocking I/O.
16. What do call stack and callback queue do?
- Call Stack: Tracks function calls. It's LIFO (Last In, First Out). Where the actual code execution happens.
- Callback Queue (Task Queue): Holds callback functions (from setTimeout, API calls) that are ready to be executed, waiting for the Call Stack to be empty.
17. How does JavaScript compile? (Repeated)
(See Question 5). To elaborate: JavaScript engines (V8, SpiderMonkey) use a technique called JIT (Just-In-Time) compilation. * It doesn't compile ahead of time (like C++) nor interpret line-by-line purely (like old JS). * It compiles JS to machine code just before execution and optimizes frequently used code paths.
18. What does it mean when we say that JavaScript is a Dynamically Typed Language?
It means that variable types are associated with values, not variables.
* You don't need to specify the type (int, string) when declaring a variable.
* The same variable can hold a number, then a string, then an object. (e.g., let x = 5; x = "hello";).
19. What are some benefits of using Typescript?
- Static Typing: Catches type-related errors at compile-time (before running code).
- Better Tooling: Intelligent code completion (IntelliSense), navigation, and refactoring.
- Readability: Explicit types serve as documentation.
- Maintainability: Easier to manage large codebases.
20. What is Static Type Checking?
A process where the type of a variable is known at compile time. If you try to assign the wrong type or perform an invalid operation (e.g., multiplying a string), the compiler throws an error before the code runs.
21. What is an Interface in Typescript?
An Interface is a structure that defines the shape (contract) of an object. It specifies property names and their types but includes no implementation. * Used for type-checking objects and classes.
22. What is the difference between type “any” and type “unknown”?
any: Disables type checking. You can do anything with it (access properties, call methods) without errors. It's basically "opting out" of TypeScript.unknown: A safer counterpart toany. You can assign anything to it, BUT you cannot perform operations on it (like calling methods) until you explicitly check/narrow its type (Type Guard).