Js Summary
Js Summary
•
•
•
HTML DOM, allows JavaScript to access and modify all the elements in an HTML document.
In this article, we will discuss DOM along with its properties and methods used to manipulate
documents and understand their implementation through the examples.
Note: It is called a Logical structure because DOM doesn’t specify any relationship between
objects.
Table of Content
What is DOM?
The Document Object Model (DOM) is a programming interface for HTML(HyperText
Markup Language) and XML(Extensible Markup Language) documents. It defines the logical
structure of documents and the way a document is accessed and manipulated.
So basically Document Object Model is an API that represents and interacts with HTML or
XML documents.
The DOM is a W3C (World Wide Web Consortium) standard and it defines a standard for
accessing documents.
With HTML DOM, we can easily access and manipulate tags, IDs, classes, attributes, or elements
of HTML using commands or methods provided by the document object.
Using DOM JavaScript we get access to HTML as well as CSS of the web page and can also
modify the behavior of the HTML elements.
DOM is basically the representation of the same HTML document but in a tree-like structure
composed of objects. JavaScript can not understand the tags(<h1>H</h1>) in HTML document
but can understand object h1 in DOM.
JavaScript interprets DOM easily, using it as a bridge to access and manipulate the elements. DOM
Javascript allow access to each of the objects (h1, p, etc) by using different functions.
The Document Object Model (DOM) is essential in web development for several
reasons:
• Dynamic Web Pages: It allows you to create dynamic web pages. It enables the
JavaScript to access and manipulate page content, structure, and style dynamically which
gives interactive and responsive web experiences, such as updating content without
reloading the entire page or responding to user actions instantly.
• Interactivity: With the DOM, you can respond to user actions (like clicks, inputs, or
scrolls) and modify the web page accordingly.
• Content Updates: When you want to update the content without refreshing the entire
page, the DOM enables targeted changes making the web applications more efficient and
user-friendly.
Structure of DOM
DOM can be thought of as a Tree or Forest (more than one tree). The term structure model is
sometimes used to describe the tree-like representation of a document.
Each branch of the tree ends in a node, and each node contains objects Event listeners can be
added to nodes and triggered on an occurrence of a given event. One important property of DOM
structure models is structural isomorphism: if any two DOM implementations are used to create
a representation of the same document, they will create the same structure model, with precisely
the same objects and relationships.
Documents are modeled using objects, and the model includes not only the structure of a document
but also the behavior of a document and the objects of which it is composed like tag elements with
attributes in HTML.
Properties of DOM
Let’s see the properties of the document object that can be accessed and modified by the
document object.
Representation of the DOM
• Window Object: Window Object is object of the browser which is always at top of the
hierarchy. It is like an API that is used to set and access all the properties and methods of
the browser. It is automatically created by the browser.
• Form Control Elements: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.
• getElementsByName(): returns all the elements having the given name value.
• getElementsByTagName(): returns all the elements having the given tag name.
• getElementsByClassName(): returns all the elements having the given class name.
In modern web development, having a way to persist data helps developers improve performance
and create a better user experience. And using local storage is an effective way of persisting data
in an application.
In this article, you will learn what local storage is and how to use it in modern web applications.
You will also learn the advantages of using local storage, as well as some of its limitations.
Table of Contents
• What is Local Storage?
• Differences Between Local Storage and Session Storage
• How to Use Local Storage
• A Practical Example
• How to View Local Storage in DevTools
• Benefits of Using Local Storage
• Limitations of Local Storage
• Conclusion
Local storage works by accepting data in key-value pairs. It retains the data even when the user
refreshes the page or closes the tab or browser.
The key differences between the two are the lifespan of the stored data and their scope.
Data in local storage remains available even when the tab/browser is closed. But closing the
tab/browser clears any data stored in session storage.
Also, data in local storage is accessible across multiple browser tabs and windows. On the other
hand, data in session storage is only accessible within specific browser tabs and is not shared.
To store data in local storage, you use the setItem() method. This method takes in two
arguments, a key and a value.
localStorage.setItem(key, value)
If the key does not exist in local storage, the setItem() method will create a new key and assign
the given value to it. But if a key with the same name exists in local storage, it will update the
value of the key with the provided value.
How to Read Data From Local Storage
To retrieve and use data from local storage, you use the getItem() method. This method takes
in a key as an argument.
localStorage.getItem(key)
If the given key exists in local storage, the method returns the value of that key. If it doesn’t, the
method returns null.
Local storage can only store strings. This means if you need to store values like objects or arrays,
you first need to get a string representation of the value. You do this using the
JSON.stringify() method.
Example:
const userObj = {
username = "Maria",
email: "[email protected]"
}
localStorage.setItem('user', JSON.stringify(userObj))
The JSON.stringify() method converts the userObj object into a string representation before
sending it to local storage.
Now, when you want to retrieve the data back from local storage, you also need to change it
from its string representation back to the original form. And you do that using the JSON.parse()
method.
Example:
if (storedUserData) {
const userData = JSON.parse(storedUserData)
// You can use userData here...
} else {
console.log('User data not found in local storage')
}
In the example above, we first check if there is data for ‘user’ in local storage before using the
JSON.parse() method. This is important because if it does not exist in local storage,
JSON.parse() will be applied to a null value (which will result in an error).
You use the removeItem() method when you want to delete a single item from local storage.
The method takes in a key as an argument and deletes the corresponding key-value pair from
local storage.
localStorage.removeItem(key)
But what if, instead of deleting a single key-value pair, you want to clear all data from the local
storage? Well, local storage has a method for that - the clear() method.
localStorage.clear()
The clear() method deletes all key-value pairs in the local storage for the current domain.
If you want to get the name of a key at a particular index in local storage, you can use the key()
method. It takes in a number as an argument and returns the name of the key at that specified
index.
Example:
localStorage.key(0)
The example above will return the name of the key at index 0. If there is no key at the specified
index, the method will return null.
A Practical Example
The following shows a practical demo of the difference between local storage and session
storage.
In this example, we'll save the user's name in local storage and save the age in session storage.
<h1 class="userName"></h1>
<h2 class="userAge"></h2>
<br />
</body>
The markup includes two header elements. One for userName and the other for userAge. It also
includes two input elements for name and age. Each input has an associated button we'll use for
saving the data.
Now, let's use the querySelector method to select the various elements.
First, we get the value of the name input, set it as the textContent of userNameText. And then
use the setItem() of local storage to save the userName value in local storage.
Next, let's see how we can get the name value from local storage when we need it.
function displayUserName () {
const nameFromLocalStorage = localStorage.getItem("name")
if (nameFromLocalStorage) {
userNameText.textContent = nameFromLocalStorage
} else {
userNameText.textContent = "No name data in local storage"
}
}
displayUserName()
Now, let's do the same thing for the age value. The only difference here will be using session
storage instead of local storage.
saveAgeButton.addEventListener("click", () => {
const userAge = document.querySelector(".age").value
userAgeText.textContent = userAge
sessionStorage.setItem("age", userAge)
})
function displayUserAge () {
const ageFromSessionStorage = sessionStorage.getItem("age")
if (ageFromSessionStorage) {
userAgeText.textContent = ageFromSessionStorage
} else {
userAgeText.textContent = "No age data in session storage"
}
}
displayUserAge()
The setItem and getItem methods also works for session storage.
Demo:
As you can see from the demo above, when you close and reopen the page, the name data from
local storage persists. But the age data from session storage is cleared once the page closes.
First, open DevTools. You can do that by right clicking on the web page and selecting "Inspect".
Then, select the "Application" tab on the DevTools panel. Depending on your browser, this panel
may have a different name. For example, it's called "Storage" in Safari and Firefox.
Demo of how to open the "Application" panel in DevTools.
Locate the "Storage" section on the sidebar showing a list of the various web storage options.
Demo of how to open the local storage tab in the storage panel.
You can click on individual items to view the corresponding key-value pair.
Benefits of Using Local Storage
The following are some of the benefits local storage has over other storage mechanisms in
modern web development.
1. Persistent data: When you use local storage, the stored data remains even when the user
closes the tab or the browser. This is useful for saving user preferences, settings, and
other relevant data. It can help create a seamless user experience.
2. Offline access: You can use local storage as a means to cache data which can be
accessed even with limited or no internet. This makes it a useful feature for apps that rely
on caching data for offline use like news readers, productivity apps, and so on.
3. More storage capacity: Compared to other storage means, local storage has a relatively
high capacity. For example, cookies are limited to 4 kilobytes per domain. But local
storage can store up to 5 megabytes of data per domain.
Conclusion
Local storage is a feature in modern web browsers that makes it easy for web developers to store
and persist data between browser sessions.
Compared to traditional cookies, it provides larger storage capacities. Also, unlike cookies, it
does not rely on server-side processes. This reduces the need for frequent server requests and
helps improve performance.
In this article, you learn about how to use local storage. We covered saving, retrieving, and
deleting data from local storage. You also learned about some of the benefits of using local
storage in your project, and some of its limitations too.
Map, filter, and reduce are three of the most useful and powerful high-order array methods. In
this tutorial, you'll see how each of these high-order array methods work. You'll also learn where
you'll want to use them and how to use them, with the help of analogies and examples. It’ll be
fun!
This is where map() comes into the picture. The map method will help you do this:
map() takes a maximum of three arguments, which are value/element, index, and array.
Let’s say you want to multiply each element by 5 while not changing the original array.
So what's going on here? Well, I have an arrOne array with 6 elements in it. Next, I initialized
an arrow function multFive with ‘num’ as an argument. This returns the product of num and 5,
where the ‘num’ variable is fed the data by the map() method.
If you’re new to arrow functions but are familiar with regular functions, an arrow function is the
same as this:
function(num)
{
return num * 5;
}
Then, I initialized another variable arrTwo that will store the new array that the map() method
will create.
On the right-hand side, I called the map() method on the ‘arrOne’ array. So, the map() method
will pick each value of that array starting from the index[0] and perform the desired calculation
on each value. Then it'll form a new array with the calculated values.
Important: Notice how I’m stressing not changing the original array. That is because this
property is what makes the map() method different from the ‘forEach()’ method. The map()
method makes a new array whereas the ‘forEach()’ method mutates/changes the original array
with the calculated array.
Let’s take an example: Suppose you have an array arrName and that array stores a bunch of
numbers. Now, you would like to see what numbers can be divided by 3 and make a separate
array from them.
Let's break down this code. Here, I have an array arrNum with 7 elements in it. Next, I initialized
a function divByFive with ‘num’ as an argument. It returns true or false for each time a new
num is passed for the comparison, where the ‘num’ variable is fed the data by the filter() method.
Then, I initialized another variable arrNewNum that will store the new array that the filter()
method will create.
On the right-hand side, I called the filter() method on the arrNum array. So, the filter() method
will pick each value of that array starting from the index[0] and perform the operation on each
value. Then it'll form a new array with the calculated values.
203
Everything is the same as the map() and filter() methods – but what’s important to understand is
how the reduce method works under the hood.
There’s not a definite syntax of the reduce() method. Let’s see the simplest one and that will give
you the gist of all the ways you can use reduce().
Take a look at this syntax. Here, reduce is taking two arguments, a1 and a2, where a1 acts as an
accumulator while the a2 has the index value.
Now, on the first run the accumulator is equal to zero and a2 holds the first element of the array.
What reduce does is that it throws the value in the accumulator that a2 holds and increments it to
the next one. After that, the reduce() method performs the operation on both operands. In this
case it is addition.
So, basically a1 is the accumulator which is currently zero and a2 holds 15. After the first run,
the accumulator has 15 in it and a2 is holding the next value which is 39.
So, 0 + 15 = 15
Now, on second run, reduce throws a2’s value, 39 in the accumulator and then performs the
operation on both operands.
So, 15 + 39 = 54
Now, on the third run, the accumulator has a sum of 15 and 39 which is 54. a2 now holds 20
which the reduce method throws at the accumulator which sums up to 54 + 20 = 74.
There are several different types of higher order functions like map and reduce. We will discuss
these later in this tutorial. But before that let's first dive deep into what higher order functions
are.
higherOrderFunction(callbackFunction);
The above example is quite simple isn't it? So let's expand it further and see how you can use
HOFs to write more concise and modular code.
So, suppose I want you to write a function that calculates the area and diameter of a circle. As a
beginner, the first solution that comes to our mind is to write each separate function to calculate
area or diameter.
But have you noticed the problem with the above code? Aren't we writing almost the same
function again and again with slightly different logic? Also, the functions we have written aren't
reusable, are they?
So, let's see how we can write the same code using HOFs:
Now, as you can see in the above code, we have only written a single function calculate() to
calculate the area and diameter of the circle. We only need to write the logic and pass it to
calculate() and the function will do the job.
The code that we have written using HOFs is concise and modular. Each function is doing its
own job and we are not repeating anything here.
Suppose in the future if we want to write a program to calculate the circumference of the circle.
We can simply write the logic to calculate the circumference and pass it to the calculate()
function.