0% found this document useful (0 votes)
66 views6 pages

JavaScript Interview Notes Overview

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views6 pages

JavaScript Interview Notes Overview

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript Interview Notes with Real-Time Examples

1. Data Types

JavaScript has two types of data types:

Primitive: String, Number, Boolean, Null, Undefined, Symbol, BigInt

Non-Primitive: Object, Array, Function

Example:

let name = "Alice"; // string

let age = 25; // number

let isStudent = false; // boolean

let user = { name, age }; // object

2. Functions

Functions are blocks of code designed to perform tasks.

Example:

function greet(name) {

return "Hello " + name;

Arrow function:

const add = (a, b) => a + b;

3. Hoisting

Hoisting moves declarations to the top. Only declarations are hoisted, not initializations.

Example:

[Link](a); // undefined

var a = 5;
JavaScript Interview Notes with Real-Time Examples

4. Closures

A closure is a function having access to the parent scope, even after the parent function has closed.

Example:

function outer() {

let count = 0;

return function() {

return ++count;

const counter = outer();

counter(); // 1

5. Scope

Scope determines variable access. Types:

- Global Scope

- Function Scope

- Block Scope (let, const)

Example:

if (true) {

let a = 10; // accessible only inside block

6. Asynchronous JS

JavaScript handles async with Callbacks, Promises, and async/await.

Example with Promise:

fetch(url)
JavaScript Interview Notes with Real-Time Examples

.then(res => [Link]())

.then(data => [Link](data));

Example with async/await:

async function loadData() {

const res = await fetch(url);

const data = await [Link]();

[Link](data);

7. Array Methods

Common methods: map, filter, reduce, find, some

Example:

const nums = [1, 2, 3];

const doubled = [Link](n => n * 2); // [2, 4, 6]

8. Object Destructuring

Extract values from objects easily.

Example:

const user = { name: 'Eva', age: 30 };

const { name, age } = user;

9. Spread and Rest Operators

Spread (...) expands values, Rest (...) gathers values.

Example:

const arr = [1, 2];


JavaScript Interview Notes with Real-Time Examples

const newArr = [...arr, 3]; // [1, 2, 3]

function sum(...nums) {

return [Link]((a, b) => a + b);

10. Prototypes & Inheritance

Prototypes allow sharing methods.

Example:

function Person(name) {

[Link] = name;

[Link] = function() {

return `Hi ${[Link]}`;

};

11. Event Loop

Handles async execution in JS.

Example:

[Link]("1");

setTimeout(() => [Link]("2"), 0);

[Link]("3"); // Output: 1, 3, 2

12. 'this' Keyword

'this' refers to the object that owns the method.

Arrow functions don't bind their own 'this'.


JavaScript Interview Notes with Real-Time Examples

Example:

const obj = {

value: 10,

show: function() { [Link]([Link]); }

};

13. Type Coercion

JS automatically converts types.

Example:

'5' + 1 = '51'

'5' - 1 = 4

14. ES6+ Features

- let, const

- Arrow functions

- Template literals: `Hello ${name}`

- Destructuring

- Spread/Rest

- Modules (import/export)

- Optional chaining

Example:

const person = { name: 'John', address: { city: 'NY' } };

[Link](person?.address?.city);

15. Real-Time Example

Email validation in a form:


JavaScript Interview Notes with Real-Time Examples

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (![Link](email)) {

setError("Invalid email");

Common questions

Powered by AI

Array methods such as map, filter, and reduce offer functional programming capabilities, enhancing readability and maintainability of code. The map method applies a function to each element in an array, returning a new array with the results. Example: const nums = [1, 2, 3]; const doubled = nums.map(n => n * 2); // [2, 4, 6]. Filter returns a new array containing elements that satisfy a specified condition. Example: const evens = nums.filter(n => n % 2 === 0); // [2] Reduce accumulates a single result from an array of values, useful for calculating sums. Example: const sum = nums.reduce((total, n) => total + n, 0); // 6 These methods reduce the need for manual loops and make code more declarative .

The purpose of the spread and rest operators in ES6 is to provide a more flexible way to handle collections of data such as arrays and function parameters. The spread operator expands an iterable into individual elements. For example, const arr = [1, 2]; const newArr = [...arr, 3]; results in [1, 2, 3]. In contrast, the rest operator collects multiple elements into an array. This is often used in function parameters to handle various numbers of arguments. For instance, function sum(...nums) { return nums.reduce((a, b) => a + b); } gathers all given arguments into the array nums and computes their sum .

Hoisting in JavaScript is a mechanism where variable and function declarations are moved to the top of their containing scope during compilation, meaning their declarations are processed before any code is executed . However, this does not lift initializations; only declarations are hoisted. For example, if you console.log(a); before the line var a = 5; it results in undefined instead of 5, because the initialization isn't hoisted. A common pitfall occurs in situations where developers expect let or const variables to be hoisted like var. They are hoisted differently, and attempting to access them before declaration results in a ReferenceError due to the temporal dead zone .

Type coercion in JavaScript is the automatic or implicit conversion of values from one data type to another during operations . For instance, '5' + 1 results in '51' because the number 1 is coerced into a string, whereas '5' - 1 results in 4 due to the string being coerced to a number. This implicit conversion can lead to bugs if not carefully managed, as it may yield unexpected outputs. One common pitfall is in conditionals where truthy and falsy values can lead to incorrect logic flows, such as '' (empty string) being coerced into false .

In JavaScript, the 'this' keyword refers to the object from which a function was called . In regular functions, 'this' is dynamic and can change based on how the function is invoked (as a method on an object, called with call() or apply(), etc.). However, arrow functions do not have their own 'this'; they inherit 'this' from the lexical context in which they are defined. This characteristic makes arrow functions particularly useful for handlers such as callbacks where maintaining the correct 'this' would otherwise require binding .

JavaScript handles asynchronous operations using Callbacks, Promises, and async/await . Promises provide a cleaner and more readable syntax than callbacks by allowing chaining with .then() and .catch(). However, they can lead to 'promise hell' if not structured properly. Async/await syntax further simplifies the handling of asynchronous code, making it appear synchronous and improving readability. It also makes error handling more straightforward with try/catch blocks. A downside of async/await is that it still relies on Promises under the hood, and its use is restricted to await within functions declared as async .

JavaScript has two categories of data types: Primitive and Non-Primitive . Primitive types include String, Number, Boolean, Null, Undefined, Symbol, and BigInt. These types are immutable and stored as single values. Examples include let name = "Alice" for a String and let age = 25 for a Number . Non-Primitive types are Objects, Arrays, and Functions, which are mutable, can store multiple values, and are stored by reference. An example of an Object is let user = { name, age }; .

A closure in JavaScript is a function that retains access to its lexical scope, even after the outer function has finished executing . This allows the function to maintain state between calls. A real-world example is implementing a private counter: function createCounter() { let count = 0; return { increment: function() { count++; return count; }, decrement: function() { count--; return count; } }; } const counter = createCounter(); counter.increment(); // 1 counter.increment(); // 2 This setup uses closures to encapsulate 'count' within the returned object, ensuring it's only accessible and changeable through 'increment' and 'decrement' methods .

The event loop in JavaScript is a mechanism that allows the non-blocking execution of asynchronous operations by coordinating the message queue and call stack. When setTimeout is used, the callback is placed into a message queue for execution after a specified delay, only when the call stack is empty . Similarly, when Promises resolve, their .then() callbacks are queued to the microtask queue, which is prioritized over tasks from the regular message queue like those scheduled by setTimeout. This distinction explains why, even with a delay of zero, setTimeout callbacks execute after Promise-based microtasks .

ES6 introduced several enhancements for handling object properties and functions, such as destructuring and arrow functions. Destructuring allows for more concise code by extracting multiple properties from an object in a single statement. Example: const {name, age} = user; . Arrow functions provide a shorter syntax and lexical 'this' binding, making them ideal for compact anonymous functions, as seen in the syntax: const add = (a, b) => a + b; . ES6 also introduced spread and rest operators, which help in expanding and gathering array elements or function arguments respectively .

You might also like