JavaScript latest one file
JavaScript latest one file
• What is JavaScript?
• Data Types
• Callback Functions
• Nested Objects
• Destructuring Assignment
• Event Handling
• Browser Events
• Template Literals
• Default Parameters
• Callbacks vs Promises
• async / await
• Error Handling
• What is an API?
• Fetch API
• Handling JSON
• Constructor Functions
• Classes in ES6
• DRY Principle
• Naming Conventions
• localStorage vs sessionStorage
• Practical Examples
• Calculator App
• Interactive Quiz
• Coding Challenges
TekStudy
Our Learning Spot
Chapter 1: Introduction to JavaScript
What is JavaScript?
• Modern Versions: ES6 (2015) introduced major enhancements like let, const, arrow
functions, promises, etc.
To run JavaScript:
• Local Environment:
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>
<script>
alert("Hello, World!");
console.log("Hello, World!");
TekStudy
Our Learning Spot
</script>
</body>
</html>
In this example:
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
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 = 35; // Error: Identifier 'age' has already been declared.
console.log(age); // Output: 30
1.3 const
JavaScript is a dynamically-typed language, meaning variables can hold any type of value and
the type can change over time.
TekStudy
Our Learning Spot
• String: Textual data, e.g., "Hello"
• Undefined: A variable that has been declared but not assigned any value
• Symbol: Unique and immutable data type primarily used for object properties
3. Operators in JavaScript
Operators are used to perform operations on variables and values. JavaScript has various
types of 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
• ==: Equal to
• ||: Logical OR
• !: Logical NOT
let x = true;
let y = false;
console.log(!x); // false
JavaScript automatically converts types when performing operations. This is called type
coercion.
TekStudy
Our Learning Spot
let num = 5;
Sometimes, you need to manually convert between types using functions like String(),
Number(), etc.
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
• Explanation: If the variable age is greater than or equal to 18, the message "You are
an adult" is logged.
The if...else statement executes one block of code if the condition is true and another block
if the condition is false.
} else {
• Explanation: Since age is 16, the output will be "You are a minor."
TekStudy
Our Learning Spot
The else if statement is used when you want to test multiple conditions.
} else {
• 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.
The for loop is the most common loop, especially when the number of iterations is known
beforehand.
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.
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.
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++;
• Explanation: The do block runs first, and then the condition i < 5 is checked.
Sometimes, you might need to control the flow of loops using break or continue.
The break statement is used to exit a loop before it completes all its iterations.
if (i === 3) {
console.log(i);
• Explanation: This will print 0, 1, and 2 because the loop breaks when i equals 3.
The continue statement skips the current iteration and moves to the next one.
TekStudy
Our Learning Spot
if (i === 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.
In JavaScript, a function can be defined using the function keyword followed by the function
name, parameters, and code to execute.
function greet(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.
Functions can accept multiple parameters, and you pass arguments when calling the
function.
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;
• 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.
• 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;
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
};
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.
• 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.
If the function has only one parameter, you can omit the parentheses.
console.log(square(5)); // Output: 25
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() {
console.log(message);
• Explanation: The function is immediately invoked after its declaration. The variable
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!");
9. Higher-Order Functions
function greetPerson(name) {
return function() {
};
• 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.
Arrays are defined using square brackets []. Elements in the array are separated by commas.
• Explanation: The array fruits contains three strings, representing different fruits. Each
item in an array is accessed using an index, starting from 0.
To access an element of an array, we use the index number. Remember, array indices start
from 0.
fruits.push("Orange");
fruits.pop();
fruits.shift();
TekStudy
Our Learning Spot
• unshift(): Adds an element to the beginning of the array.
fruits.unshift("Pineapple");
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.
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"
};
• Explanation: The object person contains three properties: name, age, and profession.
You can access the properties of an object using either dot notation or bracket notation.
• Dot Notation:
• Bracket Notation (useful when property names have spaces or special characters):
console.log(person["age"]); // Output: 30
person.age = 31;
console.log(person.age); // Output: 31
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 = [
];
• 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() {
};
TekStudy
Our Learning Spot
5.1 Iterating over Arrays
You can iterate over arrays using loops like for, forEach(), or map().
console.log(fruits[i]);
fruits.forEach(function(fruit) {
console.log(fruit);
});
Alternatively, if you only want the values, you can use Object.values():
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.
let products = [
];
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.
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.
<!DOCTYPE html>
<html>
<body>
</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()
2.2 getElementsByClassName()
This method selects elements by their class name. It returns a live HTMLCollection.
2.3 getElementsByTagName()
This method selects elements by their tag name (e.g., div, p, h1).
2.4 querySelector()
This method selects the first element that matches the specified CSS selector.
2.5 querySelectorAll()
This method selects all elements that match the specified CSS selector. It returns a NodeList.
Once you've selected an element, you can manipulate it by changing its properties, styles, or
content.
To change the text content of an element, use the textContent or innerText property.
TekStudy
Our Learning Spot
let header = document.getElementById("header");
Use the classList property to add, remove, or toggle classes for an element.
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.
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) {
});
You can prevent the default behavior of an event (e.g., preventing a form from submitting)
using the preventDefault() method.
form.addEventListener("submit", function(event) {
});
JavaScript allows you to dynamically create new elements or remove existing ones from 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
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.
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.
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>
When you write JavaScript for the browser, you're primarily interacting with two key objects:
the window object and the document 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:
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:
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.
You can add event listeners to elements to react to user interactions like clicks, key presses,
and mouse movements.
Example:
button.addEventListener("click", function() {
alert("Button clicked!");
});
TekStudy
Our Learning Spot
• click: When the user clicks on an element.
JavaScript can be used to get data from form fields, validate it, and even submit it
asynchronously using AJAX (covered in Chapter 9).
Example:
form.addEventListener("submit", function(event) {
});
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.
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
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
// Retrieving data
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.
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(data => {
console.log(data);
})
.catch(error => {
});
AJAX allows you to send and receive data from a web server asynchronously, without
refreshing the page.
TekStudy
Our Learning Spot
Example (using XMLHttpRequest):
xhr.onreadystatechange = function() {
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.
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 {}).
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
• 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.
Arrow functions have a more concise syntax compared to regular function expressions:
Example:
// Regular function
return a + b;
};
// Arrow function
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
Template literals use backticks (``) instead of quotes and allow embedding expressions
within ${}.
Example:
Template literals also support multi-line strings without the need for escape characters.
Example:
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.
With array destructuring, you can extract values from an array and assign them to individual
variables.
Example:
TekStudy
Our Learning Spot
console.log(x); // Outputs: 1
console.log(y); // Outputs: 2
console.log(z); // Outputs: 3
With object destructuring, you can extract properties from an object and assign them to
variables.
Example:
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:
console.log(`Hello, ${name}`);
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.
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);
The spread operator (...) allows you to expand an array or object into individual elements.
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.
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() {
TekStudy
Our Learning Spot
}
7.2 Inheritance
ES6 classes support inheritance, allowing one class to inherit methods and properties from
another.
Example:
this.job = job;
introduce() {
console.log(`I am a ${this.job}`);
8.1 Promises
Example:
TekStudy
Our Learning Spot
let myPromise = new Promise((resolve, reject) => {
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed.");
});
myPromise
8.2 Async/Await
async and await allow you to write asynchronous code that looks synchronous, making it
easier to work with Promises.
Example:
console.log(data);
fetchData();
ES6 introduced native support for modules in JavaScript. This allows you to break up your
code into smaller, more manageable files.
You can export functions, variables, or classes from one file and import them into another.
TekStudy
Our Learning Spot
Example (exporting):
return a + b;
Example (importing):
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.
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(() => {
}, 2000);
fetchData((data) => {
});
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.
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.
The basic way to make an AJAX request is by using the XMLHttpRequest object. Here’s a
simple example:
Example:
xhr.onload = function () {
} else {
};
You can also use AJAX to send data to the server using the POST method.
Example:
TekStudy
Our Learning Spot
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
} else {
};
const data = JSON.stringify({ title: "New Post", body: "This is a new post", userId: 1 });
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.
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) {
})
TekStudy
Our Learning Spot
.then(data => console.log(data)) // Handling the data
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 = {
userId: 1
};
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(postData)
})
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.
Example:
TekStudy
Our Learning Spot
async function fetchPosts() {
try {
if (!response.ok) {
console.log(data);
} catch (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.
Whether you're using callbacks, Promises, or async/await, handling errors properly is crucial
in asynchronous code.
For callbacks, you can check for errors by passing an error object as the first parameter in
the callback:
function fetchData(callback) {
setTimeout(() => {
callback(error, data);
TekStudy
Our Learning Spot
}, 2000);
if (error) {
console.error("Error:", error);
} else {
});
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => {
if (!response.ok) {
return response.json();
})
try {
if (!response.ok) {
console.log(data);
} catch (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.
In this chapter, we will primarily focus on using the Fetch API as it is the most modern and
easiest approach.
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.
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) {
})
.then(data => {
})
.catch(error => {
});
In this example:
• .then() chains the response handling, while .catch() is used for 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) {
})
TekStudy
Our Learning Spot
.then(posts => {
})
.catch(error => {
});
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.
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 = {
userId: 1
};
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
},
})
.then(data => {
TekStudy
Our Learning Spot
console.log("Post Created:", data); // Handle the created post
})
.catch(error => {
});
In this example:
• JSON.stringify() converts the postData object into a JSON string, which is required for
the API request.
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:
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
})
.then(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.
API responses come with HTTP status codes that tell you whether the request was successful
or not:
Example:
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => {
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
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:
Async/await syntax makes working with APIs more readable and easier to manage,
especially when handling multiple asynchronous tasks.
Example:
try {
if (!response.ok) {
console.log(posts);
} catch (error) {
console.error("Error:", error);
fetchPosts();
Example:
const postData = {
userId: 1
};
TekStudy
Our Learning Spot
try {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(postData)
});
if (!response.ok) {
} 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.
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.
• Reference Errors: Occur when you refer to a variable that has not been declared or is
out of scope.
• Type Errors: Occur when a value is not of the expected type (e.g., trying to call a
method on undefined).
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).
• Eval Errors: Rare errors that occur when there is an issue with the eval() function.
TekStudy
Our Learning Spot
o Fix: Avoid using eval() if possible, as it can introduce security vulnerabilities.
JavaScript provides a try...catch block to handle errors and prevent your application from
crashing when something goes wrong.
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 {
console.log(result);
} catch (error) {
• 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.
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 {
console.log(result);
} catch (error) {
} finally {
TekStudy
Our Learning Spot
console.log("This will always execute.");
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.
You can throw an instance of the Error object or create your own custom error types.
Example:
function checkAge(age) {
try {
console.log(checkAge(16));
} catch (error) {
If you need more control, you can define your own custom error types by extending the
Error class.
Example:
constructor(message) {
super(message);
this.name = "ValidationError";
TekStudy
Our Learning Spot
}
function validateData(data) {
if (!data.name) {
try {
validateData({});
} catch (error) {
} else {
Debugging is an essential skill for any developer. JavaScript provides several tools and
techniques to help debug your code effectively.
The console object is invaluable when debugging JavaScript. You can use the following
methods to log information:
TekStudy
Our Learning Spot
• console.assert(): Tests whether an expression is true, and if not, it logs an error
message.
Example:
console.table(data);
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.
• The code will pause at that line, and you can inspect the current state of variables.
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:
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() {
TekStudy
Our Learning Spot
function b() {
a();
• 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.
OOP is centered around the idea of objects — collections of properties (data) and methods
(functions) that model real-world entities.
2. Objects in JavaScript
const person = {
name: "Alice",
age: 28,
greet() {
};
• Here, person is an object with properties name, age, and a method greet.
TekStudy
Our Learning Spot
3. Constructor Functions (Before ES6)
this.name = name;
this.age = age;
this.greet = function () {
};
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.
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 () {
};
TekStudy
Our Learning Spot
dog.speak(); // Output: Dog makes a sound.
ES6 introduced the class syntax, making OOP more intuitive and cleaner.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
greet() {
khusboo.greet();
Output:
class Animal {
constructor(name) {
this.name = name;
TekStudy
Our Learning Spot
speak() {
constructor(name, breed) {
this.breed = breed;
speak() {
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
console.log(`Deposited: ₹${amount}`);
TekStudy
Our Learning Spot
}
checkBalance() {
account.deposit(1000);
account.checkBalance();
8. Static Methods
class MathUtil {
static add(x, y) {
return x + y;
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
TekStudy
Our Learning Spot
}
display() {
super(name, price);
this.discount = discount;
display() {
10. Summary
Concept Description
TekStudy
Our Learning Spot
Concept Description
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.
// Bad
let x = 30;
// Good
// Preferred
// Avoid
TekStudy
Our Learning Spot
3. Avoid Global Variables
// Global pollution
// Scoped safely
Use IIFE (Immediately Invoked Function Expressions) or modules to scope your code.
// Good
Split larger tasks into multiple functions for clarity and reusability.
"use strict";
This helps catch silent bugs like undeclared variables or duplicate parameter names.
Always use try...catch when working with uncertain operations (e.g., APIs).
try {
TekStudy
Our Learning Spot
} catch (error) {
// Old
// Better
Avoid unnecessary for loops when a method exists for the task.
// Bad
console.log("Welcome");
console.log("Welcome");
// Good
function greet() {
TekStudy
Our Learning Spot
console.log("Welcome");
greet();
Comment why, not what. Your code should be self-explanatory, but use comments for
complex logic.
// Bad: obvious
// Good: meaningful
// Callback Hell
doThis(function(result) {
doThat(result, function(output) {
doMore(output, function(finalResult) {
console.log(finalResult);
});
});
});
// Promises / Async-Await
console.log(res3);
Example of debouncing:
let timeout;
return () => {
clearTimeout(timeout);
};
console.log("Resized!");
}, 300));
TekStudy
Our Learning Spot
• Linters (like ESLint) to enforce code quality.
Summary Checklist
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.
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.
1. localStorage
Key Features:
// Store data
localStorage.setItem("username", "Khusboo");
// Retrieve data
// Remove item
localStorage.removeItem("username");
TekStudy
Our Learning Spot
// Clear all
localStorage.clear();
2. sessionStorage
Key Features:
Example:
sessionStorage.setItem("sessionID", "XYZ123");
// Get data
let id = sessionStorage.getItem("sessionID");
console.log(id);
sessionStorage.clear();
TekStudy
Our Learning Spot
4. JSON and Web Storage
Web Storage only stores strings. Use JSON.stringify() and JSON.parse() for arrays or objects.
// Save object
localStorage.setItem("user", JSON.stringify(user));
// Retrieve object
console.log(retrievedUser.name); // Khusboo
<script>
function toggleTheme() {
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 = () => {
document.body.style.background = "#333";
};
</script>
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.
7. Security Considerations
• Web Storage is accessible via JavaScript — it’s not safe from malicious scripts.
Summary
TekStudy
Our Learning Spot
Method Best For
Quick Quiz
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.
• Component reusability
Example:
function HelloWorld() {
}
TekStudy
Our Learning Spot
You can render it using:
2. Vue.js
Example:
<script>
el: '#app',
data: {
});
</script>
3. Angular
Example:
@Component({
selector: 'app-root',
TekStudy
Our Learning Spot
template: `<h1>Hello Angular</h1>`
})
Comparison Table
cd my-app
TekStudy
Our Learning Spot
npm start
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
• 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
• 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.
Concepts Covered:
✔ DOM manipulation
✔ Event listeners
✔ Local storage
Features:
• Add tasks
• Delete tasks
<button onclick="addTask()">Add</button>
<ul id="taskList"></ul>
<script>
function addTask() {
if (taskText) {
const li = document.createElement("li");
TekStudy
Our Learning Spot
li.innerText = taskText;
document.getElementById("taskList").appendChild(li);
taskInput.value = "";
</script>
Concepts Covered:
✔ Fetch API
✔ JSON parsing
✔ API key usage
✔ Error handling
Features:
• Enter a city
Code Snippet:
<div id="output"></div>
<script>
TekStudy
Our Learning Spot
const url =
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=met
ric`;
document.getElementById("output").innerHTML =
`🌡 ${data.main.temp}°C - ${data.weather[0].description}`;
</script>
3. Calculator
Concepts Covered:
✔ Arithmetic logic
✔ Button events
✔ eval() (with caution)
Basic Layout:
<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>
Concepts Covered:
✔ Conditional logic
✔ Arrays and objects
✔ DOM updates
Sample Logic:
<div id="quiz"></div>
<button onclick="next()">Next</button>
<script>
const questions = [
];
let index = 0;
function next() {
TekStudy
Our Learning Spot
const ans = prompt(questions[index].q);
index++;
} else {
alert("Quiz Complete!");
</script>
Summary
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
Answer:
Example:
Answer:
Example:
TekStudy
Our Learning Spot
3. What is the scope of a variable in JavaScript?
Answer:
Answer:
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;
count++;
console.log(count);
TekStudy
Our Learning Spot
}
counter(); // 1
counter(); // 2
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;
Advanced-Level Questions
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')
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) {
e.target.classList.toggle("highlight");
});
Bonus Questions
TekStudy
Our Learning Spot
• Difference between synchronous and asynchronous?
TekStudy
Our Learning Spot