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

JavaScript latest one file

The document is a comprehensive guide on JavaScript, covering topics from basic concepts to advanced techniques. It includes chapters on JavaScript fundamentals, control structures, functions, objects, and asynchronous programming, among others. Additionally, it provides practical examples, best practices, and interview preparation tips for aspiring developers.

Uploaded by

goldypawar18
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)
3 views

JavaScript latest one file

The document is a comprehensive guide on JavaScript, covering topics from basic concepts to advanced techniques. It includes chapters on JavaScript fundamentals, control structures, functions, objects, and asynchronous programming, among others. Additionally, it provides practical examples, best practices, and interview preparation tips for aspiring developers.

Uploaded by

goldypawar18
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
You are on page 1/ 93

JavaScript Mastery: From Basics to Advanced

Chapter 1: Introduction to JavaScript

• What is JavaScript?

• History and Evolution

• Setting Up Your Environment

• Hello World in JavaScript

Chapter 2: JavaScript Fundamentals

• Variables: var, let, and const

• Data Types

• Operators and Expressions

• Type Conversion and Coercion

Chapter 3: Control Structures

• Conditional Statements (if, else, switch)

• Loops (for, while, do...while)

• Break and Continue

Chapter 4: Functions in JavaScript

• Declaring and Invoking Functions

• Function Expressions and Arrow Functions

• Parameters, Return Values

• Callback Functions

Chapter 5: Objects and Arrays

• Object Creation and Manipulation

• Nested Objects

• Arrays and Array Methods

• Destructuring Assignment

Chapter 6: DOM Manipulation

• The Document Object Model (DOM)


TekStudy
Our Learning Spot
• Selecting Elements (getElementById, querySelector)

• Modifying Elements (text, HTML, CSS)

• Event Handling

Chapter 7: JavaScript in the Browser

• window and document Objects

• Dialog Boxes (alert, confirm, prompt)

• Timers (setTimeout, setInterval)

• Browser Events

Chapter 8: ES6 and Beyond

• Let, Const, Arrow Functions

• Template Literals

• Default Parameters

• Spread and Rest Operators

• Modules and Imports

Chapter 9: Asynchronous JavaScript

• Introduction to Async Programming

• Callbacks vs Promises

• async / await

• Error Handling

Chapter 10: Working with APIs

• What is an API?

• Fetch API

• Handling JSON

• Real-world Example: API Integration

Chapter 11: Error Handling & Debugging

• Try, Catch, Finally

• Console and Dev Tools

• Common JavaScript Errors


TekStudy
Our Learning Spot
Chapter 12: Object-Oriented JavaScript

• Constructor Functions

• Prototypes and Inheritance

• Classes in ES6

• Encapsulation and Polymorphism

Chapter 13: JavaScript Best Practices

• Writing Clean Code

• DRY Principle

• Naming Conventions

• Code Optimization Tips

Chapter 14: JavaScript and Web Storage

• localStorage vs sessionStorage

• Storing and Retrieving Data

• Practical Examples

Chapter 15: JavaScript Frameworks Overview

• What are Frameworks & Libraries?

• Introduction to React, Vue, Angular

• When to Use Which?

Chapter 16: Real-World Projects (Mini Projects)

• To-Do List App

• Weather App Using API

• Calculator App

• Interactive Quiz

Chapter 17: JavaScript Interview Preparation

• Top 50 Interview Questions

• Coding Challenges

• Tips to Crack Interviews

TekStudy
Our Learning Spot
Chapter 1: Introduction to JavaScript
What is JavaScript?

JavaScript is a versatile, high-level programming language primarily used to create dynamic


and interactive effects within web browsers. Unlike HTML and CSS, which handle structure
and style respectively, JavaScript controls the behavior of web elements.

History and Evolution

• 1995: Created by Brendan Eich while working at Netscape.

• Originally called: Mocha, later renamed to LiveScript, and finally JavaScript.

• Standardized as: ECMAScript by ECMA International.

• Modern Versions: ES6 (2015) introduced major enhancements like let, const, arrow
functions, promises, etc.

Setting Up Your Environment

To run JavaScript:

• Browser Console: Use browser developer tools (F12).

• Online Editors: Platforms like JSFiddle, CodePen, Repl.it.

• Local Environment:

o Install a code editor like VS Code.

o Create .html file with <script> tag for JS code.

Hello World in JavaScript

You can start writing your first JS code inside a <script> tag or a .js file:

<!DOCTYPE html>

<html>

<head><title>Hello JS</title></head>

<body>

<h1>My First JavaScript</h1>

<script>

alert("Hello, World!");

console.log("Hello, World!");

TekStudy
Our Learning Spot
</script>

</body>

</html>

In this example:

• alert() shows a pop-up message.

• console.log() prints to the browser's console.

TekStudy
Our Learning Spot
Chapter 2: JavaScript Fundamentals
1. Variables in JavaScript

In JavaScript, variables are used to store values that can be used later. There are three ways
to declare a variable: var, let, and const.

1.1 var

• var is function-scoped and can be re-declared and updated. However, it is an older


method and can lead to bugs due to scoping issues.

var name = "John";

var name = "Jane"; // No error

console.log(name); // Output: "Jane"

1.2 let

• let is block-scoped and allows updating the variable but does not allow re-declaring it
in the same block.

let age = 25;

age = 30; // valid

// let age = 35; // Error: Identifier 'age' has already been declared.

console.log(age); // Output: 30

1.3 const

• const is also block-scoped and must be initialized with a value. It cannot be


reassigned after its declaration.

const country = "India";

// country = "USA"; // Error: Assignment to constant variable.

console.log(country); // Output: "India"

2. Data Types in JavaScript

JavaScript is a dynamically-typed language, meaning variables can hold any type of value and
the type can change over time.

2.1 Primitive Types

TekStudy
Our Learning Spot
• String: Textual data, e.g., "Hello"

• Number: Numeric data, e.g., 25, 3.14

• Boolean: Represents true or false

• Undefined: A variable that has been declared but not assigned any value

• Null: Represents the intentional absence of any object value

• Symbol: Unique and immutable data type primarily used for object properties

• BigInt: For handling large integers

2.2 Example: Data Types

let name = "Alice"; // String

let age = 30; // Number

let isActive = true; // Boolean

let user = null; // Null

let address; // Undefined

3. Operators in JavaScript

Operators are used to perform operations on variables and values. JavaScript has various
types of operators.

3.1 Arithmetic Operators

Used to perform basic arithmetic operations like addition, subtraction, multiplication, etc.

• +: Addition

• -: Subtraction

• *: Multiplication

• /: Division

• %: Modulo (remainder)

let a = 10;

let b = 5;

console.log(a + b); // 15

console.log(a - b); // 5

TekStudy
Our Learning Spot
console.log(a * b); // 50

console.log(a / b); // 2

console.log(a % b); // 0 (remainder)

3.2 Comparison Operators

Used to compare two values, returning a boolean result (true or false).

• ==: Equal to

• ===: Equal value and type

• !=: Not equal to

• >: Greater than

• <: Less than

console.log(5 == '5'); // true, because values are equal (loose comparison)

console.log(5 === '5'); // false, because types are different

console.log(10 > 5); // true

3.3 Logical Operators

Used for logical operations, typically used in conditional statements.

• &&: Logical AND

• ||: Logical OR

• !: Logical NOT

let x = true;

let y = false;

console.log(x && y); // false

console.log(x || y); // true

console.log(!x); // false

4. Type Conversion and Coercion

4.1 Implicit Type Coercion

JavaScript automatically converts types when performing operations. This is called type
coercion.

TekStudy
Our Learning Spot
let num = 5;

let str = "10";

console.log(num + str); // "510" (string)

console.log(num - str); // -5 (number)

4.2 Explicit Type Conversion

Sometimes, you need to manually convert between types using functions like String(),
Number(), etc.

let value = "123";

let numValue = Number(value);

console.log(numValue); // 123 (Number)

let num = 456;

let stringValue = String(num);

console.log(stringValue); // "456" (String)

You can also visualize the flow of a loop:

// Flow of a for loop

for (let i = 0; i < 5; i++) {

console.log(i);

Example Output:

TekStudy
Our Learning Spot
Chapter 3: Control Structures
Control structures in JavaScript are essential for directing the flow of execution within a
program. They include conditional statements (if/else), loops (for, while), and control flow
statements like break and continue.

1. Conditional Statements

Conditional statements allow the execution of different blocks of code based on certain
conditions.

1.1 if Statement

The if statement executes a block of code if the condition evaluates to true.

let age = 20;

if (age >= 18) {

console.log("You are an adult.");

• Explanation: If the variable age is greater than or equal to 18, the message "You are
an adult" is logged.

1.2 if...else Statement

The if...else statement executes one block of code if the condition is true and another block
if the condition is false.

let age = 16;

if (age >= 18) {

console.log("You are an adult.");

} else {

console.log("You are a minor.");

• Explanation: Since age is 16, the output will be "You are a minor."

1.3 else if Statement

TekStudy
Our Learning Spot
The else if statement is used when you want to test multiple conditions.

let temperature = 35;

if (temperature < 20) {

console.log("It's cold outside.");

} else if (temperature >= 20 && temperature <= 30) {

console.log("The weather is perfect.");

} else {

console.log("It's too hot outside.");

• Explanation: The program will check each condition in order. Since temperature is
35, the last statement "It's too hot outside" will be executed.

2. Loops in JavaScript

Loops allow you to repeat a block of code multiple times. JavaScript has several types of
loops.

2.1 for Loop

The for loop is the most common loop, especially when the number of iterations is known
beforehand.

for (let i = 0; i < 5; i++) {

console.log(i);

• Explanation: This loop will print numbers from 0 to 4. The initialization (i = 0),
condition (i < 5), and increment (i++) control the loop.

2.2 while Loop

The while loop repeats a block of code as long as the specified condition evaluates to true.

let i = 0;

while (i < 5) {

console.log(i);
TekStudy
Our Learning Spot
i++;

• Explanation: This loop behaves similarly to the for loop, printing numbers from 0 to
4.

2.3 do...while Loop

The do...while loop ensures that the block of code is executed at least once before checking
the condition.

let i = 0;

do {

console.log(i);

i++;

} while (i < 5);

• Explanation: The do block runs first, and then the condition i < 5 is checked.

3. Break and Continue

Sometimes, you might need to control the flow of loops using break or continue.

3.1 break Statement

The break statement is used to exit a loop before it completes all its iterations.

for (let i = 0; i < 5; i++) {

if (i === 3) {

break; // Exit the loop when i is 3

console.log(i);

• Explanation: This will print 0, 1, and 2 because the loop breaks when i equals 3.

3.2 continue Statement

The continue statement skips the current iteration and moves to the next one.

for (let i = 0; i < 5; i++) {

TekStudy
Our Learning Spot
if (i === 3) {

continue; // Skip the iteration when i is 3

console.log(i);

• Explanation: This will print 0, 1, 2, and 4. The iteration for i === 3 is skipped.

4. Switch Statement

The switch statement is an alternative to if...else if when you need to test a variable against
multiple values.

let day = 2;

switch (day) {

case 0:

console.log("Sunday");

break;

case 1:

console.log("Monday");

break;

case 2:

console.log("Tuesday");

break;

default:

console.log("Invalid day");

• Explanation: The program will print "Tuesday" because day equals 2. The break
statement ensures that the code stops executing once a matching case is found.

TekStudy
Our Learning Spot
Chapter 4: Functions in JavaScript
Functions are one of the most fundamental concepts in JavaScript, enabling code reuse,
modularity, and easier debugging. In this chapter, we'll explore how to define and use
functions in JavaScript.

1. What is a Function?

A function is a block of code designed to perform a particular task. It can take inputs
(parameters), perform operations, and return an output. Functions help break down
complex problems into smaller, manageable parts.

1.1 Defining a Function

In JavaScript, a function can be defined using the function keyword followed by the function
name, parameters, and code to execute.

function greet(name) {

console.log("Hello, " + name + "!");

• Explanation: The function greet takes one parameter name and logs a greeting
message to the console. To call this function, you provide an argument.

greet("John"); // Output: Hello, John!

2. Function Parameters and Arguments

Functions can accept multiple parameters, and you pass arguments when calling the
function.

2.1 Multiple Parameters

You can define a function with multiple parameters. Here's an example of a function that
adds two numbers.

function add(a, b) {

return a + b;

console.log(add(5, 3)); // Output: 8

• Explanation: The function add takes two parameters a and b and returns their sum.

TekStudy
Our Learning Spot
2.2 Default Parameters

JavaScript allows you to assign default values to function parameters. If the argument is not
passed, the default value is used.

function greet(name = "Guest") {

console.log("Hello, " + name + "!");

greet(); // Output: Hello, Guest!

• Explanation: Since no argument is provided for name, the function uses the default
value "Guest."

3. Return Statement

The return keyword is used to exit a function and return a value to the caller.

function multiply(a, b) {

return a * b;

let result = multiply(4, 5);

console.log(result); // Output: 20

• Explanation: The function multiply returns the product of a and b, which is assigned
to the variable result.

4. Function Expressions

A function expression defines a function within an expression and can be assigned to a


variable. This is different from a function declaration.

const square = function(num) {

return num * num;

};

console.log(square(4)); // Output: 16

TekStudy
Our Learning Spot
• Explanation: The function square is assigned to the variable square, which can then
be invoked just like a normal function.

5. Arrow Functions

Arrow functions provide a shorter syntax for writing functions and are particularly useful for
short functions. They are defined using the => syntax.

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

console.log(add(5, 3)); // Output: 8

• Explanation: The function add is now written as an arrow function. Arrow functions
also have no this context, making them useful in certain situations like callbacks.

5.1 Arrow Function with One Parameter

If the function has only one parameter, you can omit the parentheses.

const square = num => num * num;

console.log(square(5)); // Output: 25

6. IIFE (Immediately Invoked Function Expressions)

An IIFE is a function that is defined and executed immediately after its creation. It's useful for
creating private scopes and avoiding polluting the global scope.

(function() {

let message = "This is an IIFE!";

console.log(message);

})(); // Output: This is an IIFE!

• Explanation: The function is immediately invoked after its declaration. The variable

message is not accessible outside of the function.

8. Anonymous Functions

Anonymous functions are functions without names. They are often used in situations where
a function is required as an argument or callback.

setTimeout(function() {

TekStudy
Our Learning Spot
console.log("This message is delayed!");

}, 2000); // Output: This message is delayed! (after 2 seconds)

• Explanation: Here, an anonymous function is passed to setTimeout and will execute


after a 2-second delay.

9. Higher-Order Functions

A higher-order function is a function that takes another function as an argument or returns a


function.

function greetPerson(name) {

return function() {

console.log("Hello, " + name + "!");

};

const greetJohn = greetPerson("John");

greetJohn(); // Output: Hello, John!

• Explanation: The greetPerson function returns another function that can be executed
later. This is a basic example of a closure, which will be explored in Chapter 7.

TekStudy
Our Learning Spot
Chapter 5: Arrays and Objects in JavaScript
In JavaScript, arrays and objects are two of the most commonly used data structures. They
allow us to store and manipulate collections of data in a more organized and efficient way.

1. What is an Array?

An array is a special variable that can hold multiple values at once. Unlike a regular variable,
which holds a single value, an array can store a collection of values in a single variable.

1.1 Defining an Array

Arrays are defined using square brackets []. Elements in the array are separated by commas.

let fruits = ["Apple", "Banana", "Cherry"];

console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]

• Explanation: The array fruits contains three strings, representing different fruits. Each
item in an array is accessed using an index, starting from 0.

1.2 Accessing Array Elements

To access an element of an array, we use the index number. Remember, array indices start
from 0.

console.log(fruits[0]); // Output: Apple

console.log(fruits[1]); // Output: Banana

1.3 Array Methods

Arrays come with a variety of built-in methods to manipulate data.

• push(): Adds an element to the end of the array.

fruits.push("Orange");

console.log(fruits); // Output: ["Apple", "Banana", "Cherry", "Orange"]

• pop(): Removes the last element from the array.

fruits.pop();

console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]

• shift(): Removes the first element from the array.

fruits.shift();

console.log(fruits); // Output: ["Banana", "Cherry"]

TekStudy
Our Learning Spot
• unshift(): Adds an element to the beginning of the array.

fruits.unshift("Pineapple");

console.log(fruits); // Output: ["Pineapple", "Banana", "Cherry"]

2. What is an Object?

An object in JavaScript is a collection of key-value pairs, where each key (also called a
property) is a string and the corresponding value can be any valid data type, such as a string,
number, array, or even another object.

2.1 Defining an Object

Objects are defined using curly braces {} and contain key-value pairs. Each key-value pair is
separated by a colon :.

let person = {

name: "John",

age: 30,

profession: "Engineer"

};

console.log(person); // Output: {name: "John", age: 30, profession: "Engineer"}

• Explanation: The object person contains three properties: name, age, and profession.

2.2 Accessing Object Properties

You can access the properties of an object using either dot notation or bracket notation.

• Dot Notation:

console.log(person.name); // Output: John

• Bracket Notation (useful when property names have spaces or special characters):

console.log(person["age"]); // Output: 30

2.3 Modifying Object Properties

You can modify the properties of an object directly.

person.age = 31;

console.log(person.age); // Output: 31

You can also add new properties:


TekStudy
Our Learning Spot
person.city = "New York";

console.log(person.city); // Output: New York

3. Array of Objects

Sometimes, you may need to store multiple objects in an array. This is useful when dealing
with collections of similar objects, such as a list of users or products.

let users = [

{ name: "Alice", age: 25 },

{ name: "Bob", age: 30 },

{ name: "Charlie", age: 35 }

];

console.log(users[0].name); // Output: Alice

• Explanation: Here, we have an array of objects users, and we access the name
property of the first object using users[0].name.

4. Methods in Objects

Objects can also contain methods—functions that operate on the properties of the object.

let person = {

name: "Alice",

greet: function() {

console.log("Hello, " + this.name + "!");

};

person.greet(); // Output: Hello, Alice!

5. Iterating over Arrays and Objects

TekStudy
Our Learning Spot
5.1 Iterating over Arrays

You can iterate over arrays using loops like for, forEach(), or map().

• Using for loop:

for (let i = 0; i < fruits.length; i++) {

console.log(fruits[i]);

• Using forEach() method:

fruits.forEach(function(fruit) {

console.log(fruit);

});

5.2 Iterating over Objects

To iterate over an object’s properties, you can use a for...in loop.

for (let key in person) {

console.log(key + ": " + person[key]);

// Output: name: Alice, age: 31, profession: Engineer

Alternatively, if you only want the values, you can use Object.values():

console.log(Object.values(person)); // Output: ["Alice", 31, "Engineer"]

7. Common Array and Object Use Cases

7.1 Storing and Manipulating Data

Arrays and objects are useful for storing and manipulating large amounts of data. For
example, when working with user data or product catalogs, arrays of objects can be used to
represent multiple records.

7.2 Example - Storing Products:

let products = [

{ name: "Laptop", price: 1200 },

{ name: "Phone", price: 800 },


TekStudy
Our Learning Spot
{ name: "Tablet", price: 400 }

];

console.log(products[1].name); // Output: Phone

TekStudy
Our Learning Spot
Chapter 6: DOM Manipulation in JavaScript
The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of a web page as a tree of objects, allowing programming languages
like JavaScript to interact with and modify the content, structure, and style of web pages
dynamically. In this chapter, we'll explore how to manipulate the DOM using JavaScript,
including accessing elements, modifying them, and handling events.

1. What is the DOM?

The DOM represents the structure of an HTML document as a tree of nodes. Each node
corresponds to an element, attribute, or piece of text in the document. The DOM allows
JavaScript to interact with these nodes, enabling dynamic changes to the page without
needing to reload it.

For example, the following HTML:

<!DOCTYPE html>

<html>

<head><title>My Web Page</title></head>

<body>

<h1 id="header">Welcome to My Web Page</h1>

<p>This is a paragraph of text.</p>

<button id="changeTextButton">Change Text</button>

</body>

</html>

The DOM representation of this document would look something like this:

Document

├── HTML

├── HEAD

└── BODY

├── H1

├── P

└── BUTTON

TekStudy
Our Learning Spot
2. Selecting DOM Elements

To manipulate any part of the HTML document, you first need to access the corresponding
DOM element. JavaScript provides several methods for selecting DOM elements.

2.1 getElementById()

This method selects an element by its unique id.

let header = document.getElementById("header");

console.log(header); // Returns the <h1> element

2.2 getElementsByClassName()

This method selects elements by their class name. It returns a live HTMLCollection.

let paragraphs = document.getElementsByClassName("text");

console.log(paragraphs); // Returns a collection of elements with class "text"

2.3 getElementsByTagName()

This method selects elements by their tag name (e.g., div, p, h1).

let divs = document.getElementsByTagName("div");

console.log(divs); // Returns a collection of all <div> elements

2.4 querySelector()

This method selects the first element that matches the specified CSS selector.

let header = document.querySelector("h1");

console.log(header); // Returns the first <h1> element

2.5 querySelectorAll()

This method selects all elements that match the specified CSS selector. It returns a NodeList.

let allParagraphs = document.querySelectorAll("p");

console.log(allParagraphs); // Returns a NodeList of all <p> elements

3. Manipulating DOM Elements

Once you've selected an element, you can manipulate it by changing its properties, styles, or
content.

3.1 Changing Text Content

To change the text content of an element, use the textContent or innerText property.

TekStudy
Our Learning Spot
let header = document.getElementById("header");

header.textContent = "New Heading Text"; // Changes the content of <h1>

3.2 Changing HTML Content

To change the HTML inside an element, use the innerHTML property.

let paragraph = document.querySelector("p");

paragraph.innerHTML = "This is <strong>new</strong> content!"; // Adds HTML

3.3 Changing Styles

To modify the CSS styles of an element, use the style property.

let button = document.getElementById("changeTextButton");

button.style.backgroundColor = "blue"; // Changes background color to blue

button.style.fontSize = "18px"; // Changes font size

3.4 Adding/Removing Classes

Use the classList property to add, remove, or toggle classes for an element.

let paragraph = document.querySelector("p");

paragraph.classList.add("highlight"); // Adds class "highlight"

paragraph.classList.remove("highlight"); // Removes class "highlight"

paragraph.classList.toggle("highlight"); // Toggles the class "highlight"

4. Event Handling

One of the most powerful features of DOM manipulation is handling user interactions with
the page. JavaScript provides a way to listen for events such as clicks, key presses, and form
submissions.

4.1 Adding Event Listeners

The addEventListener() method is used to listen for events on DOM elements.

let button = document.getElementById("changeTextButton");

button.addEventListener("click", function() {

alert("Button clicked!");

});

TekStudy
Our Learning Spot
4.2 Event Object

When an event occurs, an event object is passed to the event handler. This object contains
useful information about the event, such as the element that triggered it.

button.addEventListener("click", function(event) {

console.log("Event triggered by: " + event.target); // Logs the button element

});

4.3 Preventing Default Behavior

You can prevent the default behavior of an event (e.g., preventing a form from submitting)
using the preventDefault() method.

let form = document.querySelector("form");

form.addEventListener("submit", function(event) {

event.preventDefault(); // Prevents the form from submitting

console.log("Form submission prevented!");

});

5. Creating and Removing Elements

JavaScript allows you to dynamically create new elements or remove existing ones from the
DOM.

5.1 Creating Elements

To create a new element, use the document.createElement() method.

let newParagraph = document.createElement("p");

newParagraph.textContent = "This is a new paragraph!";

document.body.appendChild(newParagraph); // Adds the new paragraph to the body

5.2 Removing Elements

To remove an element, first select it and then call remove() on it.

let paragraph = document.querySelector("p");

paragraph.remove(); // Removes the selected paragraph element from the DOM

6. Traversing the DOM

DOM elements are related to each other in a hierarchical structure, and you can navigate
this structure using properties like parentNode, childNodes, nextSibling, and previousSibling.
TekStudy
Our Learning Spot
6.1 Navigating to Parent Element

let childElement = document.querySelector("p");

let parentElement = childElement.parentNode; // Accesses the parent of the <p> element

6.2 Accessing Child Elements

let parentElement = document.querySelector("div");

let childElements = parentElement.children; // Gets all child elements of the <div>

TekStudy
Our Learning Spot
Chapter 7: JavaScript in the Browser
JavaScript is a powerful tool for creating interactive web applications, and it is most
commonly used within the context of a browser environment. In this chapter, we will
explore how JavaScript interacts with the browser to create dynamic web pages, manipulate
the DOM, handle user input, and interact with external resources.

1. How JavaScript Works in the Browser

When a user loads a webpage, the browser interprets the HTML, CSS, and JavaScript to
render the page. JavaScript runs within the browser, allowing it to dynamically interact with
the content of the page. The browser provides a set of APIs (Application Programming
Interfaces) that JavaScript can use to interact with the page’s structure, styles, and even
external services.

1.1 The Browser's Role

• HTML provides the structure of the page.

• CSS defines the presentation (styling) of the page.

• JavaScript provides the behavior and interactivity, allowing dynamic manipulation of


HTML and CSS.

JavaScript code is typically included within a <script> tag in the HTML document, or in an
external .js file linked to the HTML.

<script src="script.js"></script>

2. Browser APIs and the Window Object

When you write JavaScript for the browser, you're primarily interacting with two key objects:
the window object and the document object.

2.1 The Window Object

The window object represents the global environment of the browser and provides various
methods and properties for interacting with the browser. It is automatically created by the
browser when a webpage is loaded.

Example:

window.alert("Hello, World!"); // Opens a browser alert dialog

Commonly used methods and properties of the window object include:

• window.alert(): Displays an alert box.

• window.confirm(): Displays a confirmation box with OK and Cancel options.


TekStudy
Our Learning Spot
• window.location: Gets or sets the current URL of the browser.

• window.setTimeout() / window.setInterval(): Used to schedule code execution after


a delay or repeatedly at intervals.

2.2 The Document Object

The document object is part of the DOM and represents the HTML document loaded in the
browser. This object provides methods for manipulating and accessing elements within the
page.

Example:

let header = document.getElementById("header");

header.textContent = "Welcome to My Web Page";

Some of the key methods provided by the document object include:

• document.getElementById(): Retrieves an element by its id.

• document.querySelector(): Selects the first element that matches a CSS selector.

• document.createElement(): Creates a new HTML element.

• document.body: Represents the <body> element of the page.

3. Handling User Input in the Browser

One of the most powerful aspects of JavaScript in the browser is its ability to handle user
input. JavaScript can respond to actions such as mouse clicks, keyboard presses, form
submissions, and more.

3.1 Event Listeners for User Input

You can add event listeners to elements to react to user interactions like clicks, key presses,
and mouse movements.

Example:

let button = document.getElementById("myButton");

button.addEventListener("click", function() {

alert("Button clicked!");

});

Common browser events include:

TekStudy
Our Learning Spot
• click: When the user clicks on an element.

• keydown / keyup: When a key is pressed or released.

• submit: When a form is submitted.

• mouseover / mouseout: When the mouse enters or leaves an element.

3.2 Input Fields and Forms

JavaScript can be used to get data from form fields, validate it, and even submit it
asynchronously using AJAX (covered in Chapter 9).

Example:

let form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {

event.preventDefault(); // Prevents the form from submitting

let userName = document.getElementById("username").value;

console.log("User Name: " + userName);

});

4. Working with Browser Storage

JavaScript in the browser can store data locally using various browser storage mechanisms.
This is useful for saving user preferences or application data that needs to persist across
page reloads.

4.1 Local Storage

Local Storage allows you to store key-value pairs in the browser without an expiration date.
Data stored in Local Storage persists even when the browser is closed and reopened.

Example:

// Storing data

localStorage.setItem("userName", "JohnDoe");

// Retrieving data

let userName = localStorage.getItem("userName");

console.log(userName); // Outputs: JohnDoe


TekStudy
Our Learning Spot
4.2 Session Storage

Session Storage is similar to Local Storage, but the data is only available for the duration of
the page session (until the browser or tab is closed).

Example:

// Storing data

sessionStorage.setItem("sessionData", "Temporary Data");

// Retrieving data

let sessionData = sessionStorage.getItem("sessionData");

console.log(sessionData); // Outputs: Temporary Data

5. Working with External APIs

JavaScript in the browser can interact with external APIs to retrieve data or send requests to
other servers. This is commonly done using AJAX (Asynchronous JavaScript and XML) or
newer methods like Fetch API.

5.1 The Fetch API

The Fetch API is a modern method for making HTTP requests in the browser. It returns a
Promise that resolves to the response of the request.

Example:

fetch("https://api.example.com/data")

.then(response => response.json())

.then(data => {

console.log(data);

})

.catch(error => {

console.error("Error fetching data: ", error);

});

5.2 AJAX (Asynchronous JavaScript and XML)

AJAX allows you to send and receive data from a web server asynchronously, without
refreshing the page.

TekStudy
Our Learning Spot
Example (using XMLHttpRequest):

let xhr = new XMLHttpRequest();

xhr.open("GET", "https://api.example.com/data", true);

xhr.onreadystatechange = function() {

if (xhr.readyState === 4 && xhr.status === 200) {

let data = JSON.parse(xhr.responseText);

console.log(data);

};

xhr.send();

TekStudy
Our Learning Spot
Chapter 8: ES6 and Beyond
ECMAScript 6 (also known as ES6 or ES2015) was a major update to the JavaScript language,
introducing several new features and syntax improvements that make JavaScript more
powerful, expressive, and easier to use. Since then, JavaScript has continued to evolve with
further versions (ES7, ES8, ES9, ES10, etc.), each adding more features that make writing
modern JavaScript code smoother and more efficient.

In this chapter, we will go over some of the most important features introduced in ES6 and
later versions, explaining how these features improve JavaScript and providing examples for
each.

1. Let and Const

Before ES6, JavaScript only had the var keyword to declare variables. However, var has some
quirks, such as its function scope, which can lead to unexpected results. ES6 introduced two
new ways to declare variables: let and const.

1.1 Let

• Block-scoped: Variables declared with let are only accessible within the block
(enclosed by curly braces {}).

• Reassignable: Unlike const, variables declared with let can be reassigned.

Example:

let x = 10;

if (true) {

let x = 20; // This 'x' is block-scoped and different from the outer 'x'

console.log(x); // Outputs: 20

console.log(x); // Outputs: 10

1.2 Const

• Block-scoped: Just like let, const is block-scoped.

• Constant: Variables declared with const cannot be reassigned after they are
initialized.

Example:

const y = 30;

TekStudy
Our Learning Spot
y = 40; // This will throw an error because 'y' is a constant

2. Arrow Functions

ES6 introduced arrow functions, which provide a shorter syntax for writing functions. Arrow
functions also have lexical scoping for the this keyword, which makes them useful in certain
situations like callbacks.

2.1 Basic Syntax

Arrow functions have a more concise syntax compared to regular function expressions:

Example:

// Regular function

const add = function(a, b) {

return a + b;

};

// Arrow function

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

console.log(add(2, 3)); // Outputs: 5

console.log(addArrow(2, 3)); // Outputs: 5

2.2 Lexical this

Arrow functions do not have their own this. Instead, they inherit this from the surrounding
scope.

Example:

function Counter() {

this.count = 0;

setInterval(() => {

this.count++;

console.log(this.count);

}, 1000);

}
TekStudy
Our Learning Spot
const counter = new Counter(); // The `this` refers to the Counter instance

3. Template Literals

Before ES6, string concatenation in JavaScript could be cumbersome, especially when


working with variables. ES6 introduced template literals, which allow for easier string
interpolation and multi-line strings.

3.1 String Interpolation

Template literals use backticks (``) instead of quotes and allow embedding expressions
within ${}.

Example:

let name = "Alice";

let age = 30;

let greeting = `Hello, my name is ${name} and I am ${age} years old.`;

console.log(greeting); // Outputs: Hello, my name is Alice and I am 30 years old.

3.2 Multi-line Strings

Template literals also support multi-line strings without the need for escape characters.

Example:

let message = `This is a

multi-line

string.`;

console.log(message);

4. Destructuring Assignment

Destructuring is a convenient way to extract values from arrays or objects and assign them
to variables.

4.1 Array Destructuring

With array destructuring, you can extract values from an array and assign them to individual
variables.

Example:

let [x, y, z] = [1, 2, 3];

TekStudy
Our Learning Spot
console.log(x); // Outputs: 1

console.log(y); // Outputs: 2

console.log(z); // Outputs: 3

4.2 Object Destructuring

With object destructuring, you can extract properties from an object and assign them to
variables.

Example:

let person = { name: "John", age: 25 };

let { name, age } = person;

console.log(name); // Outputs: John

console.log(age); // Outputs: 25

5. Default Parameters

ES6 allows you to define default values for function parameters. If a parameter is undefined
or not passed, the default value will be used.

Example:

function greet(name = "Guest") {

console.log(`Hello, ${name}`);

greet("Alice"); // Outputs: Hello, Alice

greet(); // Outputs: Hello, Guest

6. Rest and Spread Operators

The rest and spread operators are two powerful features in ES6 that allow you to work with
variable numbers of arguments in functions and arrays.

6.1 Rest Operator

The rest operator (...) allows you to collect multiple elements into an array. It is often used in
function arguments to handle variable numbers of arguments.

Example:

function sum(...numbers) {
TekStudy
Our Learning Spot
return numbers.reduce((acc, num) => acc + num, 0);

console.log(sum(1, 2, 3, 4)); // Outputs: 10

6.2 Spread Operator

The spread operator (...) allows you to expand an array or object into individual elements.

Example (for arrays):

let arr1 = [1, 2, 3];

let arr2 = [...arr1, 4, 5];

console.log(arr2); // Outputs: [1, 2, 3, 4, 5]

Example (for objects):

let person = { name: "Alice", age: 30 };

let updatedPerson = { ...person, age: 31 };

console.log(updatedPerson); // Outputs: { name: "Alice", age: 31 }

7. Classes

ES6 introduced classes, which provide a more structured way of creating objects and dealing
with inheritance compared to the older function-based prototype system.

7.1 Class Syntax

A class is defined using the class keyword, and you can define methods within it.

Example:

class Person {

constructor(name, age) {

this.name = name;

this.age = age;

greet() {

console.log(`Hello, my name is ${this.name}`);

TekStudy
Our Learning Spot
}

let person = new Person("Alice", 30);

person.greet(); // Outputs: Hello, my name is Alice

7.2 Inheritance

ES6 classes support inheritance, allowing one class to inherit methods and properties from
another.

Example:

class Employee extends Person {

constructor(name, age, job) {

super(name, age); // Call the parent class's constructor

this.job = job;

introduce() {

console.log(`I am a ${this.job}`);

let employee = new Employee("Bob", 35, "Engineer");

employee.introduce(); // Outputs: I am a Engineer

8. Promises and Async/Await

ES6 introduced Promises as a way to handle asynchronous operations. Later versions of


JavaScript introduced async and await, making asynchronous code even easier to write and
read.

8.1 Promises

A Promise represents the eventual completion (or failure) of an asynchronous operation.

Example:
TekStudy
Our Learning Spot
let myPromise = new Promise((resolve, reject) => {

let success = true;

if (success) {

resolve("Operation successful!");

} else {

reject("Operation failed.");

});

myPromise

.then(result => console.log(result)) // Outputs: Operation successful!

.catch(error => console.log(error)); // Outputs: Operation failed.

8.2 Async/Await

async and await allow you to write asynchronous code that looks synchronous, making it
easier to work with Promises.

Example:

async function fetchData() {

let response = await fetch("https://api.example.com/data");

let data = await response.json();

console.log(data);

fetchData();

9. Modules (ES6 Modules)

ES6 introduced native support for modules in JavaScript. This allows you to break up your
code into smaller, more manageable files.

9.1 Exporting and Importing

You can export functions, variables, or classes from one file and import them into another.

TekStudy
Our Learning Spot
Example (exporting):

export function add(a, b) {

return a + b;

Example (importing):

import { add } from './math.js';

console.log(add(2, 3)); // Outputs: 5

TekStudy
Our Learning Spot
Chapter 9: Asynchronous JavaScript (AJAX
and Fetch API)
In JavaScript, asynchronous programming is a powerful tool that allows you to execute tasks
without blocking the execution of other code. This is especially useful when dealing with
tasks like loading data from a server or performing time-consuming computations.

In this chapter, we’ll explore AJAX (Asynchronous JavaScript and XML) and the Fetch API,
both of which allow us to make asynchronous HTTP requests to a server. These tools are
essential for creating interactive, dynamic web pages.

1. What is Asynchronous JavaScript?

Asynchronous JavaScript refers to operations that can run independently of the main
execution thread. It allows the browser to perform other tasks while waiting for a response
from an asynchronous operation.

JavaScript's event-driven model means that tasks are executed without blocking the main
thread, improving the user experience. Asynchronous operations often involve interacting
with external resources, like fetching data from a server.

2. Callback Functions

Before modern tools like Promises and async/await, JavaScript used callback functions to
handle asynchronous code. A callback function is passed as an argument to another function
and executed once that function finishes its task.

Example:

function fetchData(callback) {

setTimeout(() => {

const data = "Data fetched from server!";

callback(data); // The callback is executed when data is fetched

}, 2000);

fetchData((data) => {

console.log(data); // Outputs: Data fetched from server!

});
TekStudy
Our Learning Spot
While callbacks are simple, they can lead to a situation known as "callback hell," where
nested callbacks become difficult to manage and debug. This is where Promises and
async/await become useful.

3. AJAX (Asynchronous JavaScript and XML)

AJAX is a technique for sending HTTP requests asynchronously without refreshing the entire
page. It allows web pages to update data in the background and display it dynamically
without requiring a page reload.

3.1 Creating an AJAX Request

The basic way to make an AJAX request is by using the XMLHttpRequest object. Here’s a
simple example:

Example:

const xhr = new XMLHttpRequest();

xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true); // GET request to the


server

xhr.onload = function () {

if (xhr.status === 200) {

const response = JSON.parse(xhr.responseText);

console.log(response); // Outputs the fetched data

} else {

console.error("Request failed with status: " + xhr.status);

};

xhr.send(); // Sends the request to the server

3.2 AJAX with POST Requests

You can also use AJAX to send data to the server using the POST method.

Example:

const xhr = new XMLHttpRequest();

TekStudy
Our Learning Spot
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);

xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = function () {

if (xhr.status === 201) {

const response = JSON.parse(xhr.responseText);

console.log("Post Created: ", response);

} else {

console.error("Request failed with status: " + xhr.status);

};

const data = JSON.stringify({ title: "New Post", body: "This is a new post", userId: 1 });

xhr.send(data); // Sending data to the server

4. The Fetch API

The Fetch API provides a more modern and powerful way to make HTTP requests. Unlike
XMLHttpRequest, fetch() returns a Promise that resolves with the Response object
representing the response to the request.

4.1 Basic Fetch Request

The syntax of the fetch() function is simple and clean. Here's an example of a basic GET
request:

Example:

fetch("https://jsonplaceholder.typicode.com/posts")

.then(response => {

if (!response.ok) {

throw new Error("Network response was not ok");

return response.json(); // Parsing the response as JSON

})
TekStudy
Our Learning Spot
.then(data => console.log(data)) // Handling the data

.catch(error => console.error("Fetch error:", error)); // Handling errors

4.2 POST Request with Fetch

Just like with AJAX, you can also send data to the server using the fetch() method by
specifying the method and body properties.

Example:

const postData = {

title: "New Post",

body: "This is a new post",

userId: 1

};

fetch("https://jsonplaceholder.typicode.com/posts", {

method: "POST",

headers: {

"Content-Type": "application/json"

},

body: JSON.stringify(postData)

})

.then(response => response.json())

.then(data => console.log("Post Created:", data))

.catch(error => console.error("Error:", error));

5. Async/Await with Fetch

To make asynchronous code look more synchronous, we can use async/await with the Fetch
API. This makes our code easier to read and manage, especially when dealing with multiple
asynchronous operations.

5.1 Using Async/Await

Here's how we can rewrite the Fetch request using async/await:

Example:
TekStudy
Our Learning Spot
async function fetchPosts() {

try {

const response = await fetch("https://jsonplaceholder.typicode.com/posts");

if (!response.ok) {

throw new Error("Network response was not ok");

const data = await response.json();

console.log(data);

} catch (error) {

console.error("Fetch error:", error);

fetchPosts();

In this example:

• The await keyword is used to pause the function's execution until the promise is
resolved.

• If an error occurs during the fetch operation, it is caught in the catch block.

6. Handling Errors in Asynchronous JavaScript

Whether you're using callbacks, Promises, or async/await, handling errors properly is crucial
in asynchronous code.

6.1 Error Handling in Callbacks

For callbacks, you can check for errors by passing an error object as the first parameter in
the callback:

function fetchData(callback) {

setTimeout(() => {

const error = null; // Replace with an error object if there's an issue

const data = "Data fetched from server!";

callback(error, data);
TekStudy
Our Learning Spot
}, 2000);

fetchData((error, data) => {

if (error) {

console.error("Error:", error);

} else {

console.log(data); // Outputs: Data fetched from server!

});

6.2 Error Handling with Promises

With Promises, errors can be handled using the .catch() method:

fetch("https://jsonplaceholder.typicode.com/posts")

.then(response => {

if (!response.ok) {

throw new Error("Network response was not ok");

return response.json();

})

.then(data => console.log(data))

.catch(error => console.error("Fetch error:", error));

6.3 Error Handling with Async/Await

With async/await, errors are handled using try...catch blocks:

async function fetchPosts() {

try {

const response = await fetch("https://jsonplaceholder.typicode.com/posts");

if (!response.ok) {

throw new Error("Network response was not ok");


TekStudy
Our Learning Spot
}

const data = await response.json();

console.log(data);

} catch (error) {

console.error("Fetch error:", error);

fetchPosts();

TekStudy
Our Learning Spot
Chapter 10: Working with APIs
APIs (Application Programming Interfaces) are a fundamental aspect of modern web
development. They allow different software systems to communicate with each other by
defining methods for one system to request data or functionality from another system.

In this chapter, we will explore how to interact with APIs in JavaScript, how to fetch data,
handle responses, and send data to APIs. By the end of this chapter, you'll be comfortable
working with APIs and integrating them into your applications.

1. What is an API?

An API is a set of rules that allow one piece of software to interact with another. Web APIs
provide a way for applications to communicate over the internet. Most commonly, web APIs
are based on HTTP requests and are used to fetch data from remote servers.

There are two main types of APIs you’ll work with in JavaScript:

• REST APIs (Representational State Transfer) – These APIs use standard HTTP methods
like GET, POST, PUT, DELETE, etc.

• GraphQL APIs – A query language for your API that allows you to request only the
data you need.

2. Making HTTP Requests

In JavaScript, we can make HTTP requests using several methods:

• AJAX with XMLHttpRequest

• Fetch API (modern approach)

• Axios (a popular library for HTTP requests)

In this chapter, we will primarily focus on using the Fetch API as it is the most modern and
easiest approach.

3. Fetching Data from an API

The Fetch API allows you to make network requests similar to XMLHttpRequest. It returns a
Promise that resolves to the Response object representing the response to the request.

3.1 Basic Fetch Request

A simple GET request fetches data from the server. Here's an example of how to retrieve
data from a public API:

Example:

TekStudy
Our Learning Spot
fetch("https://jsonplaceholder.typicode.com/posts")

.then(response => {

if (!response.ok) {

throw new Error("Network response was not ok");

return response.json(); // Parse the JSON response

})

.then(data => {

console.log(data); // Handle the response data

})

.catch(error => {

console.error("Fetch error:", error); // Handle errors

});

In this example:

• fetch() makes the HTTP request to the API.

• response.json() is used to parse the JSON data returned by the API.

• .then() chains the response handling, while .catch() is used for error handling.

3.2 GET Request Example with Error Handling

When making a request to an API, it’s essential to handle any possible errors, such as
network issues or API failures.

Example:

fetch("https://jsonplaceholder.typicode.com/posts")

.then(response => {

if (!response.ok) {

throw new Error("Failed to fetch data.");

return response.json(); // Parse response

})

TekStudy
Our Learning Spot
.then(posts => {

console.log(posts); // Handle the posts data

})

.catch(error => {

console.log("Error:", error); // Handle any errors

});

4. Sending Data to an API (POST Requests)

You can also send data to an API using a POST request. This is useful when you need to
submit data like form inputs, new posts, or updates to the server.

4.1 Making a POST Request

To make a POST request with the fetch() function, you need to specify the method (in this
case, POST) and the body (the data you want to send).

Example:

const postData = {

title: "New Post",

body: "This is a new post",

userId: 1

};

fetch("https://jsonplaceholder.typicode.com/posts", {

method: "POST",

headers: {

"Content-Type": "application/json" // Send data in JSON format

},

body: JSON.stringify(postData) // Convert the object into JSON string

})

.then(response => response.json()) // Parse the JSON response

.then(data => {

TekStudy
Our Learning Spot
console.log("Post Created:", data); // Handle the created post

})

.catch(error => {

console.error("Error:", error); // Handle errors

});

In this example:

• The body property is used to send data to the API.

• JSON.stringify() converts the postData object into a JSON string, which is required for
the API request.

4.2 Sending Form Data

If you need to send form data (like text inputs, files, etc.), you can use the FormData object
in JavaScript. This is useful when sending data to the server as a form submission.

Example:

const formData = new FormData();

formData.append("title", "New Post");

formData.append("body", "This is a new post");

fetch("https://jsonplaceholder.typicode.com/posts", {

method: "POST",

body: formData // Sending form data

})

.then(response => response.json())

.then(data => {

console.log("Post Created:", data);

})

.catch(error => {

console.error("Error:", error);

});

TekStudy
Our Learning Spot
5. Handling API Responses

The response returned by the fetch() function is a Response object. You need to handle this
response by checking the status and parsing the response data accordingly.

5.1 Response Status Codes

API responses come with HTTP status codes that tell you whether the request was successful
or not:

• 200 OK – The request was successful.

• 400 Bad Request – The request was malformed.

• 404 Not Found – The requested resource was not found.

• 500 Internal Server Error – The server encountered an error.

Example:

fetch("https://jsonplaceholder.typicode.com/posts")

.then(response => {

if (response.status === 404) {

throw new Error("Resource not found");

return response.json(); // Parse response if status is OK

})

.then(data => {

console.log(data);

})

.catch(error => {

console.error("Error:", error);

});

5.2 Handling Different Data Types

API responses can return different types of data, such as JSON, text, or even binary data. You
should use the appropriate method to handle the response:

• response.json() for JSON data.

• response.text() for plain text data.


TekStudy
Our Learning Spot
• response.blob() for binary data.

6. Using Async/Await with APIs

Async/await syntax makes working with APIs more readable and easier to manage,
especially when handling multiple asynchronous tasks.

6.1 Async/Await with GET Request

Example:

async function fetchPosts() {

try {

const response = await fetch("https://jsonplaceholder.typicode.com/posts");

if (!response.ok) {

throw new Error("Failed to fetch data");

const posts = await response.json();

console.log(posts);

} catch (error) {

console.error("Error:", error);

fetchPosts();

6.2 Async/Await with POST Request

Example:

async function createPost() {

const postData = {

title: "New Post",

body: "This is a new post",

userId: 1

};

TekStudy
Our Learning Spot
try {

const response = await fetch("https://jsonplaceholder.typicode.com/posts", {

method: "POST",

headers: {

"Content-Type": "application/json"

},

body: JSON.stringify(postData)

});

if (!response.ok) {

throw new Error("Failed to create post");

const data = await response.json();

console.log("Post Created:", data);

} catch (error) {

console.error("Error:", error);

createPost();

TekStudy
Our Learning Spot
Chapter 11: Error Handling and Debugging
When writing JavaScript code, errors are inevitable. They can occur due to syntax issues,
runtime problems, logical mistakes, or unforeseen edge cases. However, understanding how
to handle and debug errors effectively will help you maintain a smooth development process
and ensure a robust application.

In this chapter, we will learn how to handle errors using try...catch blocks, explore
JavaScript’s built-in error types, and discover debugging techniques to troubleshoot your
code effectively.

1. Types of Errors in JavaScript

JavaScript has several types of errors, and understanding them is crucial to troubleshooting.
The most common types are:

• Syntax Errors: Occur when there is a mistake in the syntax of the code.

o Example: Missing a closing bracket or using incorrect punctuation.

o Example: let x = 10; console.log(x

o Fix: let x = 10; console.log(x);

• Reference Errors: Occur when you refer to a variable that has not been declared or is
out of scope.

o Example: console.log(x); // ReferenceError: x is not defined

o Fix: Declare let x = 10; before the console.log(x);

• Type Errors: Occur when a value is not of the expected type (e.g., trying to call a
method on undefined).

o Example: let num = 10; num.toUpperCase(); // TypeError: num.toUpperCase


is not a function

o Fix: Ensure you are calling methods on the correct data type.

• Range Errors: Occur when a value is not in the acceptable range (e.g., negative array
length).

o Example: let arr = new Array(-1); // RangeError: Invalid array length

o Fix: Ensure values are within valid ranges.

• Eval Errors: Rare errors that occur when there is an issue with the eval() function.

o Example: Misuse of eval().

TekStudy
Our Learning Spot
o Fix: Avoid using eval() if possible, as it can introduce security vulnerabilities.

2. Basic Error Handling with try...catch

JavaScript provides a try...catch block to handle errors and prevent your application from
crashing when something goes wrong.

2.1 Using try...catch

The try...catch block lets you write code that might throw an error and catch it in the catch
block. This is useful for handling runtime errors that can occur while executing code.

Example:

try {

let result = riskyFunction();

console.log(result);

} catch (error) {

console.error("Error caught:", error.message);

• The try block contains the code that may throw an error.

• The catch block catches the error and allows you to handle it gracefully.

• error.message contains the error description, which you can log or display to the
user.

2.2 Finally Block

The finally block is an optional part of the try...catch statement. It runs regardless of whether
an error was thrown or not. This is useful for cleanup tasks like closing files or freeing
resources.

Example:

try {

let result = riskyFunction();

console.log(result);

} catch (error) {

console.error("Error caught:", error.message);

} finally {

TekStudy
Our Learning Spot
console.log("This will always execute.");

3. Throwing Custom Errors

In JavaScript, you can throw your own errors using the throw keyword. This allows you to
create custom error messages or handle specific edge cases.

3.1 Throwing Custom Errors

You can throw an instance of the Error object or create your own custom error types.

Example:

function checkAge(age) {

if (age < 18) {

throw new Error("Age must be 18 or older.");

return "Age is valid.";

try {

console.log(checkAge(16));

} catch (error) {

console.error(error.message); // Output: Age must be 18 or older.

3.2 Creating Custom Error Types

If you need more control, you can define your own custom error types by extending the
Error class.

Example:

class ValidationError extends Error {

constructor(message) {

super(message);

this.name = "ValidationError";

TekStudy
Our Learning Spot
}

function validateData(data) {

if (!data.name) {

throw new ValidationError("Name is required.");

try {

validateData({});

} catch (error) {

if (error instanceof ValidationError) {

console.error(error.message); // Output: Name is required.

} else {

console.error("Unknown error:", error);

4. Debugging JavaScript Code

Debugging is an essential skill for any developer. JavaScript provides several tools and
techniques to help debug your code effectively.

4.1 Console Methods

The console object is invaluable when debugging JavaScript. You can use the following
methods to log information:

• console.log(): General logging of messages and values.

• console.error(): Logs error messages.

• console.warn(): Logs warning messages.

• console.table(): Displays tabular data in a table format.

TekStudy
Our Learning Spot
• console.assert(): Tests whether an expression is true, and if not, it logs an error
message.

Example:

const data = { name: "John", age: 30 };

console.table(data);

4.2 Using Breakpoints in the Browser's Developer Tools

Most modern browsers have built-in developer tools, which allow you to set breakpoints in
your code and inspect values at various stages of execution.

• Open the browser’s developer tools (usually pressing F12 or right-clicking and
selecting "Inspect").

• Go to the "Sources" tab and find the JavaScript file you want to debug.

• Click on the line number where you want to set a breakpoint.

• The code will pause at that line, and you can inspect the current state of variables.

4.3 Debugging with debugger Statement

You can also use the debugger keyword directly in your code. When the browser encounters
this statement, it will pause the execution and open the developer tools, where you can
inspect variables and step through the code.

Example:

function calculateTotal(price, tax) {

debugger; // Code execution will pause here

return price + price * tax;

4.4 Error Stack Traces

When an error occurs in JavaScript, the browser typically provides a stack trace. This trace
lists the function calls that led to the error, making it easier to pinpoint the cause.

function a() {

throw new Error("Oops!");

TekStudy
Our Learning Spot
function b() {

a();

b(); // This will show a stack trace in the console

5. Common Debugging Techniques

Here are a few common debugging techniques to keep in mind:

• Check variable values: Log variables at different points to ensure their values are as
expected.

• Step through code: Use breakpoints or the debugger statement to step through your
code line by line and inspect the values.

• Isolate the problem: Simplify your code to isolate the error. Remove or comment out
parts of the code until you find the problematic area.

• Check the browser console: Always check the console for errors or warnings.
Browsers usually give helpful messages about where the error occurred.

TekStudy
Our Learning Spot
Chapter 12: Object-Oriented JavaScript
(OOP)
Object-Oriented Programming (OOP) is a paradigm that organizes code into reusable
objects, making complex applications easier to build and maintain. JavaScript is prototype-
based, but with ES6 and beyond, it fully supports class-based OOP as well.

1. What is Object-Oriented Programming?

OOP is centered around the idea of objects — collections of properties (data) and methods
(functions) that model real-world entities.

Core OOP principles include:

• Encapsulation – Hiding internal details of how an object works.

• Abstraction – Showing only essential features and hiding the rest.

• Inheritance – Sharing properties/methods between classes.

• Polymorphism – Using the same method name for different types.

2. Objects in JavaScript

Object Literal Syntax

const person = {

name: "Alice",

age: 28,

greet() {

console.log(`Hi, I'm ${this.name}`);

};

person.greet(); // Output: Hi, I'm Alice

• Here, person is an object with properties name, age, and a method greet.

TekStudy
Our Learning Spot
3. Constructor Functions (Before ES6)

Before ES6, objects were often created using constructor functions.

function Person(name, age) {

this.name = name;

this.age = age;

this.greet = function () {

console.log(`Hello, my name is ${this.name}`);

};

const john = new Person("John", 30);

john.greet(); // Output: Hello, my name is John

Each time we create an object using new Person(...), it gets its own copy of greet()—which
isn’t efficient. That’s where prototypes help.

4. Prototypes and Inheritance

Every function in JavaScript has a prototype property. You can add methods to it so that all
instances share the same method reference (memory efficient).

function Animal(name) {

this.name = name;

Animal.prototype.speak = function () {

console.log(`${this.name} makes a sound.`);

};

const dog = new Animal("Dog");

TekStudy
Our Learning Spot
dog.speak(); // Output: Dog makes a sound.

Now all Animal objects share the speak method.

5. ES6 Classes (Modern OOP)

ES6 introduced the class syntax, making OOP more intuitive and cleaner.

class Person {

constructor(name, age) {

this.name = name;

this.age = age;

greet() {

console.log(`Hi, I’m ${this.name} and I’m ${this.age} years old.`);

const khusboo = new Person("Khusboo", 25);

khusboo.greet();

Output:

Hi, I’m Khusboo and I’m 25 years old.

6. Inheritance with extends and super()

Classes can inherit from other classes using extends.

class Animal {

constructor(name) {

this.name = name;

TekStudy
Our Learning Spot
speak() {

console.log(`${this.name} makes a sound.`);

class Dog extends Animal {

constructor(name, breed) {

super(name); // Calls the parent constructor

this.breed = breed;

speak() {

console.log(`${this.name} barks. Breed: ${this.breed}`);

const tommy = new Dog("Tommy", "Beagle");

tommy.speak(); // Output: Tommy barks. Breed: Beagle

7. Encapsulation (Private Fields)

With ES2022, JavaScript supports private fields using #.

class BankAccount {

#balance = 0;

deposit(amount) {

this.#balance += amount;

console.log(`Deposited: ₹${amount}`);
TekStudy
Our Learning Spot
}

checkBalance() {

console.log(`Current balance: ₹${this.#balance}`);

const account = new BankAccount();

account.deposit(1000);

account.checkBalance();

// account.#balance = 0; Will throw an error (private)

8. Static Methods

Static methods belong to the class, not the instances.

class MathUtil {

static add(x, y) {

return x + y;

console.log(MathUtil.add(3, 7)); // Output: 10

9. Real-world Example: E-Commerce Product

class Product {

constructor(name, price) {

this.name = name;

this.price = price;

TekStudy
Our Learning Spot
}

display() {

console.log(`${this.name} costs ₹${this.price}`);

class DiscountedProduct extends Product {

constructor(name, price, discount) {

super(name, price);

this.discount = discount;

display() {

const finalPrice = this.price - this.price * this.discount;

console.log(`${this.name} after discount: ₹${finalPrice}`);

const laptop = new DiscountedProduct("Dell Laptop", 60000, 0.1);

laptop.display(); // Output: Dell Laptop after discount: ₹54000

10. Summary

Concept Description

Object Collection of properties and methods

Class Blueprint for creating objects

Constructor Method to initialize an object

TekStudy
Our Learning Spot
Concept Description

extends Inheritance keyword

super() Calls parent class constructor

Prototype Shared methods in pre-ES6 OOP

Encapsulation Hiding data with private fields

Polymorphism Overriding methods in child class

Static Belongs to class, not instance

Conclusion

OOP in JavaScript helps in writing modular, scalable, and maintainable code. Whether you're
building a game, UI component, or data model, understanding and applying OOP concepts
will level up your JavaScript skills!

TekStudy
Our Learning Spot
Chapter 13: JavaScript Best Practices
Writing JavaScript that just works isn't enough. To build scalable, secure, and bug-free apps,
you must follow best practices. This chapter covers essential principles every developer
should embrace.

1. Write Readable and Consistent Code

Readable code is maintainable code.

Use meaningful variable names:

// Bad

let x = 30;

// Good

let maxUsers = 30;

Follow consistent naming conventions:

• camelCase for variables/functions

• PascalCase for classes

• UPPER_CASE for constants

Keep indentation consistent (usually 2 or 4 spaces).

2. Use let and const (not var)

Avoid var — it's function-scoped and can cause weird bugs.

// Preferred

const API_KEY = "abc123"; // Never changes

let userName = "Khusboo"; // May change

// Avoid

var oldSchool = true;

TekStudy
Our Learning Spot
3. Avoid Global Variables

Global variables can lead to naming conflicts and hard-to-track bugs.

// Global pollution

total = 100; // No declaration

// Scoped safely

let total = 100;

Use IIFE (Immediately Invoked Function Expressions) or modules to scope your code.

4. Keep Functions Small and Focused

Functions should do one thing only.

// Good

function calculateTotal(price, taxRate) {

return price + price * taxRate;

Split larger tasks into multiple functions for clarity and reusability.

5. Use Strict Mode

Enables stricter parsing and error handling.

"use strict";

This helps catch silent bugs like undeclared variables or duplicate parameter names.

6. Handle Errors Gracefully

Always use try...catch when working with uncertain operations (e.g., APIs).

try {

const data = JSON.parse(response);

TekStudy
Our Learning Spot
} catch (error) {

console.error("Invalid JSON", error);

Avoid silent failures — log errors or show user-friendly messages.

7. Use Template Literals

Make string concatenation cleaner.

// Old

let msg = "Hello, " + name + "!";

// Better

let msg = `Hello, ${name}!`;

8. Use Array and Object Methods

Leverage built-in methods like .map(), .filter(), .reduce(), Object.keys():

const prices = [100, 200, 300];

const discounted = prices.map(p => p * 0.9);

Avoid unnecessary for loops when a method exists for the task.

9. DRY: Don’t Repeat Yourself

Duplicate code is dangerous. Extract it into reusable functions or constants.

// Bad

console.log("Welcome");

console.log("Welcome");

// Good

function greet() {

TekStudy
Our Learning Spot
console.log("Welcome");

greet();

10. Comment Wisely

Comment why, not what. Your code should be self-explanatory, but use comments for
complex logic.

// Bad: obvious

let total = price * tax; // Multiplying price and tax

// Good: meaningful

// Add tax to the original price

let total = price * tax;

11. Avoid Callback Hell with Promises & Async/Await

// Callback Hell

doThis(function(result) {

doThat(result, function(output) {

doMore(output, function(finalResult) {

console.log(finalResult);

});

});

});

// Promises / Async-Await

async function run() {

const res1 = await doThis();

const res2 = await doThat(res1);


TekStudy
Our Learning Spot
const res3 = await doMore(res2);

console.log(res3);

12. Optimize Performance

• Minimize DOM access.

• Debounce events like scroll or resize.

• Lazy-load images and scripts when possible.

Example of debouncing:

function debounce(fn, delay) {

let timeout;

return () => {

clearTimeout(timeout);

timeout = setTimeout(fn, delay);

};

window.addEventListener("resize", debounce(() => {

console.log("Resized!");

}, 300));

13. Secure Your Code

• Never trust user input.

• Sanitize data before inserting into DOM.

• Avoid eval() — it's a security risk.

14. Use Modern Tools

TekStudy
Our Learning Spot
• Linters (like ESLint) to enforce code quality.

• Formatters (like Prettier) for consistent styling.

• Bundlers (Webpack, Vite) for project structuring.

• Version Control (Git) for tracking code.

Summary Checklist

Best Practice Do This

Consistent Naming camelCase / PascalCase

Use let & const Avoid var

Handle Errors Use try...catch

Comment Smart Explain why

DRY Principle Reuse logic

Use async/await Avoid nested callbacks

Use strict mode "use strict"

Optimize & Secure Minimize DOM, sanitize input

TekStudy
Our Learning Spot
Chapter 14: JavaScript and Web Storage
Modern web applications often need to store data on the client-side. JavaScript provides
several ways to do this securely and efficiently. In this chapter, you'll explore the core
options: localStorage, sessionStorage, and cookies.

What is Web Storage?

Web Storage allows websites to store data in the browser, unlike cookies which are sent to
the server with every request. It provides a way to persist small pieces of data across
sessions or page reloads.

Web Storage consists of two main APIs:

• localStorage: Data is stored with no expiration.

• sessionStorage: Data is stored for the duration of the page session.

1. localStorage

Key Features:

• Stores data with no expiration.

• Available even after the browser is closed and reopened.

• Limited to ~5MB per origin.

Example: Storing and Retrieving Data

// Store data

localStorage.setItem("username", "Khusboo");

// Retrieve data

let name = localStorage.getItem("username");

console.log(name); // Output: Khusboo

// Remove item

localStorage.removeItem("username");

TekStudy
Our Learning Spot
// Clear all

localStorage.clear();

2. sessionStorage

Key Features:

• Data persists only during a single page session.

• Cleared once the browser tab is closed.

Example:

// Store session data

sessionStorage.setItem("sessionID", "XYZ123");

// Get data

let id = sessionStorage.getItem("sessionID");

console.log(id);

// Clear session storage

sessionStorage.clear();

Use Case: Temporary authentication tokens, filters, temporary form data.

3. Comparing localStorage vs sessionStorage

Feature localStorage sessionStorage

Lifespan Until manually cleared Until tab closes

Capacity ~5MB ~5MB

Scope Same-origin Tab-specific

Accessible from All tabs/windows Only that tab

TekStudy
Our Learning Spot
4. JSON and Web Storage

Web Storage only stores strings. Use JSON.stringify() and JSON.parse() for arrays or objects.

const user = { name: "Khusboo", age: 25 };

// Save object

localStorage.setItem("user", JSON.stringify(user));

// Retrieve object

const retrievedUser = JSON.parse(localStorage.getItem("user"));

console.log(retrievedUser.name); // Khusboo

5. Real-Life Use Case: Theme Toggle

Dark Mode Example Using localStorage

<button onclick="toggleTheme()">Toggle Theme</button>

<script>

function toggleTheme() {

let currentTheme = localStorage.getItem("theme");

if (currentTheme === "dark") {

document.body.style.background = "#fff";

localStorage.setItem("theme", "light");

} else {

document.body.style.background = "#333";

localStorage.setItem("theme", "dark");

TekStudy
Our Learning Spot
// Apply saved theme on load

window.onload = () => {

if (localStorage.getItem("theme") === "dark") {

document.body.style.background = "#333";

};

</script>

6. Cookies vs Web Storage

Cookies were traditionally used for client-side storage. However, they are smaller in size
(~4KB), sent with every HTTP request, and mainly used for session management and server
communication.

Feature Cookies Web Storage

Size Limit ~4KB ~5MB

Sent with Request Yes No

Expiration Set manually Auto (session) / Manual (local)

Use Case Auth/session User preferences, cart, etc.

7. Security Considerations

• Don’t store sensitive data like passwords or tokens in localStorage or


sessionStorage.

• Use HTTPS to prevent data interception.

• Sanitize data to avoid XSS attacks.

• Web Storage is accessible via JavaScript — it’s not safe from malicious scripts.

Summary

TekStudy
Our Learning Spot
Method Best For

localStorage Preferences, themes, saved drafts

sessionStorage Tab-specific session data

Cookies Auth tokens, server communication

Quick Quiz

1. What’s the main difference between localStorage and sessionStorage?

2. How would you store an array in localStorage?

3. What happens to sessionStorage when you close a browser tab?

TekStudy
Our Learning Spot
Chapter 15: JavaScript Frameworks
JavaScript frameworks revolutionized frontend and backend development, allowing
developers to build scalable and maintainable applications efficiently. In this chapter, you'll
get introduced to the most popular JS frameworks, understand why they matter, and get
hands-on with basic examples.

What is a JavaScript Framework?

A JavaScript Framework is a collection of pre-written JavaScript code that helps in building


web apps quickly and efficiently. Frameworks provide structure, reusable components, and
standard patterns to write cleaner and scalable code.

Why Use a JS Framework?

• Saves development time

• Better project structure

• Component reusability

• Easier debugging and testing

• Encourages clean coding standards

Popular JavaScript Frameworks

1. React.js (Library, but often grouped with frameworks)

• Created by: Facebook

• Key Concept: Component-based architecture

• Use Case: SPAs (Single Page Applications), dynamic UIs

• Learn Once, Use Anywhere: React Native for mobile apps

Example:

function HelloWorld() {

return <h1>Hello, React!</h1>;

}
TekStudy
Our Learning Spot
You can render it using:

ReactDOM.render(<HelloWorld />, document.getElementById('root'));

2. Vue.js

• Created by: Evan You

• Key Concept: Simple and progressive

• Use Case: Lightweight SPAs and interactive web components

Example:

<div id="app">{{ message }}</div>

<script>

const app = new Vue({

el: '#app',

data: {

message: 'Hello Vue!'

});

</script>

3. Angular

• Created by: Google

• Key Concept: Full-fledged framework with dependency injection, services, routing

• Use Case: Large-scale enterprise apps

Example:

In Angular, you create components using TypeScript:

@Component({

selector: 'app-root',

TekStudy
Our Learning Spot
template: `<h1>Hello Angular</h1>`

})

export class AppComponent {}

4. Next.js (Built on React)

• Purpose: Server-side rendering, SEO-friendly apps

• Use Case: Web apps needing performance + SEO

• Key Features: File-based routing, API routes, full-stack capabilities

Comparison Table

Feature React Vue Angular

Type Library Framework Framework

Language JavaScript JavaScript TypeScript

Learning Curve Medium Easy Steep

Size Small Small Large

Best For Dynamic UI Beginners Large apps

How to Choose the Right Framework?

1. Small app / Simple UI → Vue or React

2. SEO needed / Server-side rendering → Next.js

3. Large enterprise apps → Angular

4. Fast MVP development → React or Vue

Getting Started: Setting Up React

You can create a React project using:

npx create-react-app my-app

cd my-app
TekStudy
Our Learning Spot
npm start

This launches a local server and hot-reloads changes.

Bonus: Micro-Frontend Trend

Modern teams use multiple JS frameworks across one project using micro-frontends. For
example, the dashboard might use React, while the analytics panel uses Angular.

Summary

• Frameworks bring structure and speed to JS development.

• React is great for UIs, Angular for enterprise apps, and Vue for beginners.

• Choose a framework based on project size, team skill, and performance needs.

Quick Tasks

• Install Vue via CDN and bind a message to the DOM.

• Set up a React component to display a list of items.

• Compare the syntax of React and Vue with the same UI goal.

TekStudy
Our Learning Spot
Chapter 16: Real-World JavaScript Projects
Build. Break. Learn. – The best way to master JavaScript is by creating real, usable
applications.

In this chapter, we’ll walk through four beginner-to-intermediate level projects using plain
JavaScript — no frameworks needed. These mini-projects help solidify core JS concepts like
DOM manipulation, event handling, API integration, and conditional logic.

1. To-Do List App

Concepts Covered:
✔ DOM manipulation
✔ Event listeners
✔ Local storage

Features:

• Add tasks

• Mark tasks complete

• Delete tasks

• Store in browser’s local storage

Code (HTML + JS):

<input type="text" id="task" placeholder="Add task..." />

<button onclick="addTask()">Add</button>

<ul id="taskList"></ul>

<script>

function addTask() {

const taskInput = document.getElementById("task");

const taskText = taskInput.value.trim();

if (taskText) {

const li = document.createElement("li");

TekStudy
Our Learning Spot
li.innerText = taskText;

li.onclick = () => li.classList.toggle("completed");

document.getElementById("taskList").appendChild(li);

taskInput.value = "";

</script>

Try Enhancing: Add delete buttons or sync with localStorage.

2. Weather App (Using OpenWeather API)

Concepts Covered:
✔ Fetch API
✔ JSON parsing
✔ API key usage
✔ Error handling

Features:

• Enter a city

• Fetch real-time weather

• Show temperature and description

Code Snippet:

<input type="text" id="city" placeholder="Enter city" />

<button onclick="getWeather()">Check Weather</button>

<div id="output"></div>

<script>

async function getWeather() {

const city = document.getElementById("city").value;

const apiKey = "YOUR_API_KEY";

TekStudy
Our Learning Spot
const url =
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=met
ric`;

const res = await fetch(url);

const data = await res.json();

document.getElementById("output").innerHTML =

`🌡 ${data.main.temp}°C - ${data.weather[0].description}`;

</script>

Note: Sign up at openweathermap.org to get a free API key.

3. Calculator

Concepts Covered:
✔ Arithmetic logic
✔ Button events
✔ eval() (with caution)

Basic Layout:

<input type="text" id="calc" readonly />

<div>

<button onclick="append('1')">1</button>

<button onclick="append('2')">2</button>

<button onclick="append('+')">+</button>

<button onclick="calculate()">=</button>

<button onclick="clearCalc()">C</button>

</div>

<script>

function append(val) {

document.getElementById("calc").value += val;
TekStudy
Our Learning Spot
}

function calculate() {

document.getElementById("calc").value = eval(document.getElementById("calc").value);

function clearCalc() {

document.getElementById("calc").value = "";

</script>

Enhance: Add keyboard support and input validation.

4. Interactive Quiz App

Concepts Covered:
✔ Conditional logic
✔ Arrays and objects
✔ DOM updates

Sample Logic:

<div id="quiz"></div>

<button onclick="next()">Next</button>

<script>

const questions = [

{ q: "What is 2+2?", a: "4" },

{ q: "Capital of France?", a: "Paris" }

];

let index = 0;

function next() {

if (index < questions.length) {

TekStudy
Our Learning Spot
const ans = prompt(questions[index].q);

alert(ans.toLowerCase() === questions[index].a.toLowerCase() ? "Correct!" : "Wrong!");

index++;

} else {

alert("Quiz Complete!");

next(); // auto start

</script>

Enhance: Add radio buttons, scoring, and timer.

Summary

Project Concepts Practiced Difficulty

To-Do App DOM, Events, LocalStorage

Weather App APIs, Fetch, JSON

Calculator Event Handling, Eval, Input Mgmt

Quiz App Logic, Loops, User Input

Final Tip:

Once you’re comfortable, try building one app using a JS framework like React or Vue for
comparison!

TekStudy
Our Learning Spot
Chapter 17: JavaScript Interview Questions
"It's not just about writing code, it's about explaining it too."

Whether you're preparing for your first interview or brushing up your knowledge, this
chapter covers essential JavaScript questions along with clear answers, code examples, and
explanations.

Beginner-Level Questions

1. What are the different data types in JavaScript?

Answer:

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

• Non-Primitive: Object, Array, Function

Example:

let name = "John"; // String

let age = 25; // Number

let isLoggedIn = true; // Boolean

let score = null; // Null

let id = Symbol("id"); // Symbol

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

Answer:

• == compares values (performs type coercion)

• === compares both value and type

Example:

console.log(5 == '5'); // true

console.log(5 === '5'); // false

TekStudy
Our Learning Spot
3. What is the scope of a variable in JavaScript?

Answer:

• Global Scope – accessible anywhere

• Function Scope – declared within a function

• Block Scope – for let and const inside {}

4. Explain var, let, and const.

Answer:

• var: Function-scoped, hoisted

• let: Block-scoped, not hoisted

• const: Block-scoped, immutable reference

Example:

var x = 1;

let y = 2;

const z = 3;

Intermediate-Level Questions

5. What is a closure?

Answer:
A closure is a function that remembers the variables from its outer scope, even after the
outer function has finished executing.

Example:

function outer() {

let count = 0;

return function inner() {

count++;

console.log(count);

TekStudy
Our Learning Spot
}

const counter = outer();

counter(); // 1

counter(); // 2

6. What is hoisting in JavaScript?

Answer:
Hoisting is JavaScript's behavior of moving declarations to the top of their scope before code
execution.

Example:

console.log(a); // undefined

var a = 5;

But let and const are not hoisted the same way:

console.log(b); // ReferenceError

let b = 10;

7. What is the difference between null and undefined?

• undefined: A variable declared but not assigned a value.

• null: An intentional absence of value.

Advanced-Level Questions

8. What are promises and how do they work?

Answer:
Promises represent the result of an asynchronous operation.

Syntax:

TekStudy
Our Learning Spot
let promise = new Promise((resolve, reject) => {

// async task

});

Example:

fetch('https://api.example.com')

.then(res => res.json())

.then(data => console.log(data))

.catch(err => console.log(err));

9. Explain this keyword in JavaScript.

• In global scope, this refers to the window object.

• In object methods, it refers to the object.

• In arrow functions, this is lexically scoped (inherits from parent scope).

10. What is event delegation?

Answer:
Instead of attaching event listeners to multiple child elements, we attach it to a common
parent.

Example:

document.getElementById("list").addEventListener("click", function(e) {

if (e.target.tagName === "LI") {

e.target.classList.toggle("highlight");

});

Bonus Questions

• What are higher-order functions?

• Explain the event loop.

TekStudy
Our Learning Spot
• Difference between synchronous and asynchronous?

• What is a callback function?

• How does async/await work?

Quick Tips for Interviews

• Don’t just memorize — understand the why

• Explain using examples or diagrams

• Practice live coding questions on platforms like LeetCode, HackerRank, JSFiddle

• Stay up to date with ES6+ features

TekStudy
Our Learning Spot

You might also like