Skip to main content

ยท 8 min read

"JavaScript Cookies vs. Local Storage vs. Session Storage"

Introductionโ€‹

When it comes to storing data on the client side in JavaScript, there are several options available, each with its own use cases and considerations.

In this guide, we'll compare JavaScript cookies, local storage, and session storage, helping you understand when to use each one and the advantages they offer.

Let's get started!

Suggested Tutorials ๐Ÿ“‘:โ€‹

1. JavaScript Cookiesโ€‹

JavaScript cookies are small pieces of data that are stored as text files on a user's computer. Cookies are created when a user's browser loads a particular website. The website sends information to the browser, which then creates a text file. Every time the user goes back to the same website, the browser retrieves and sends this file to the website's server. Cookies are used for several purposes, including authentication, session tracking, and storing information about the user's preferences or browsing history.

To create a cookie, we use the document.cookie property. This property is used to both create and read cookies.

Let's create a cookie named username with the value John Doe:

// Set a basic cookie with a name and value
document.cookie = "username=John Doe";

To read a cookie, we can simply access the document.cookie property:

// Read the cookie
const cookieValue = document.cookie;
console.log(cookieValue); // username=John Doe

Suggested Tutorials ๐Ÿ“‘:โ€‹

By default, cookies are deleted when the browser is closed. However, we can set an expiration date for a cookie, after which the cookie will be deleted. To do this, we use the expires property:


// Set a cookie with an expiration date

const date = new Date();
date.setTime(date.getTime() + 1000 * 60 * 60 * 24 * 7); // 7 days from now

document.cookie = `username=John Doe; expires=${date.toUTCString()}`;

By default, cookies are available to all pages on a website. However, we can set a path for a cookie, after which the cookie will only be available to pages within that path. To do this, we use the path property:

// Set a cookie with a path
document.cookie = `username=John Doe; path=/`;

By default, cookies are available to all subdomains on a website. However, we can set a domain for a cookie, after which the cookie will only be available to pages within that domain. To do this, we use the domain property:

// Set a cookie with a domain
document.cookie = `username=John Doe; domain=example.com`;

Suggested Tutorials ๐Ÿ“‘:โ€‹

By default, cookies are sent to the server with every HTTP request. However, we can set the secure flag for a cookie, after which the cookie will only be sent to the server with an encrypted request over the HTTPS protocol. To do this, we use the secure property:

// Set a cookie with a secure flag
document.cookie = `username=John Doe; secure`;

By default, cookies are sent to the server with every HTTP request. However, we can set the SameSite flag for a cookie, after which the cookie will only be sent to the server with a same-site request. To do this, we use the SameSite property:


// Set a cookie with a SameSite flag
document.cookie = `username=John Doe; SameSite=Strict`;

To delete a cookie, we can set its expiration date to a date in the past:

// Delete a cookie
document.cookie = `username=John Doe; expires=Thu, 01 Jan 1970 00:00:00 UTC;`;

Suggested Tutorials ๐Ÿ“‘:โ€‹

2. Local Storageโ€‹

Local storage is a type of web storage that allows us to store data in the browser with no expiration date. This means the data will persist even after the browser window is closed. Local storage is similar to session storage, except that data stored in local storage has no expiration date, while data stored in session storage gets cleared when the page session ends.

2.1. Creating a Local Storage Itemโ€‹

To create a local storage item, we use the localStorage.setItem() method. This method takes two parameters: the name of the item and its value.

Let's create a local storage item named username with the value John Doe:

// Set a local storage item
localStorage.setItem("username", "John Doe");

2.2. Reading a Local Storage Itemโ€‹

To read a local storage item, we use the localStorage.getItem() method. This method takes one parameter: the name of the item.

Let's read the username local storage item:

// Read a local storage item
const username = localStorage.getItem("username");
console.log(username); // John Doe

Suggested Tutorials ๐Ÿ“‘:โ€‹

2.3. Updating a Local Storage Itemโ€‹

To update a local storage item, we use the localStorage.setItem() method. This method takes two parameters: the name of the item and its value.

Let's update the username local storage item:

// Update a local storage item
localStorage.setItem("username", "Jane Doe");

2.4. Deleting a Local Storage Itemโ€‹

To delete a local storage item, we use the localStorage.removeItem() method. This method takes one parameter: the name of the item.

Let's delete the username local storage item:

// Delete a local storage item
localStorage.removeItem("username");

2.5. Clearing All Local Storage Itemsโ€‹

To delete all local storage items, we use the localStorage.clear() method:

// Delete all local storage items
localStorage.clear();

Suggested Tutorials ๐Ÿ“‘:โ€‹

3. Session Storageโ€‹

Session storage is a type of web storage that allows us to store data in the browser with an expiration date. This means the data will persist until the browser window is closed. Session storage is similar to local storage, except that data stored in session storage gets cleared when the page session ends, while data stored in local storage has no expiration date.

3.1. Creating a Session Storage Itemโ€‹

To create a session storage item, we use the sessionStorage.setItem() method. This method takes two parameters: the name of the item and its value.

Let's create a session storage item named username with the value John Doe:

// Set a session storage item
sessionStorage.setItem("username", "John Doe");

3.2. Reading a Session Storage Itemโ€‹

To read a session storage item, we use the sessionStorage.getItem() method. This method takes one parameter: the name of the item.

Let's read the username session storage item:

// Read a session storage item
const username = sessionStorage.getItem("username");
console.log(username); // John Doe

3.3. Updating a Session Storage Itemโ€‹

To update a session storage item, we use the sessionStorage.setItem() method. This method takes two parameters: the name of the item and its value.

Let's update the username session storage item:

// Update a session storage item
sessionStorage.setItem("username", "Jane Doe");

Suggested Tutorials ๐Ÿ“‘:โ€‹

3.4. Deleting a Session Storage Itemโ€‹

To delete a session storage item, we use the sessionStorage.removeItem() method. This method takes one parameter: the name of the item.

Let's delete the username session storage item:

// Delete a session storage item
sessionStorage.removeItem("username");

3.5. Clearing All Session Storage Itemsโ€‹

To delete all session storage items, we use the sessionStorage.clear() method:

// Delete all session storage items
sessionStorage.clear();

Suggested Tutorials ๐Ÿ“‘:โ€‹

Conclusionโ€‹

In this guide, we explored the fundamentals of JavaScript cookies, local storage, and session storage. We saw how to create, read, update, and delete cookies, local storage items, and session storage items. We also saw how to set expiration dates for cookies and how to set paths, domains, and flags for cookies.

To learn more about cookies, local storage, and session storage, check out the following resources:

Happy coding! ๐ŸŽ‰

ยท 10 min read

"Exploring Maps and Sets in JavaScript: ES6 Collections Made Easy"

Introductionโ€‹

ES6 introduced two powerful data structures, Maps and Sets, that provide enhanced ways to manage and manipulate data in JavaScript.

Maps offer key-value pair storage, while Sets store unique values without duplicates.

In this guide, we'll explore the concepts of Maps and Sets and see how they can simplify various programming tasks.

Suggested Tutorials ๐Ÿ“‘:โ€‹

1. What are Maps?โ€‹

Maps are a new data structure in ES6 that allow you to store key-value pairs.

Maps are similar to objects in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key.

However, there are some important differences that make Maps preferable in certain cases.

1.1. Creating Mapsโ€‹

Maps are created using the Map() constructor:

const map = new Map();

You can also pass an array of key-value pairs to the Map() constructor:

const map = new Map([
['key1', 'value1'],
['key2', 'value2']
]);

1.2. Adding and Retrieving Valuesโ€‹

You can add values to a Map using the set() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

You can retrieve values from a Map using the get() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

console.log(map.get('key1')); // value1
console.log(map.get('key2')); // value2

Suggested Tutorials ๐Ÿ“‘:โ€‹

1.3. Checking for Valuesโ€‹

You can check whether a Map contains a value using the has() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

console.log(map.has('key1')); // true
console.log(map.has('key2')); // true
console.log(map.has('key3')); // false

1.4. Deleting Valuesโ€‹

You can delete values from a Map using the delete() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

map.delete('key1');
console.log(map.has('key1')); // false

1.5. Getting the Size of a Mapโ€‹

You can get the size of a Map using the size property:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

console.log(map.size); // 2

Suggested Tutorials ๐Ÿ“‘:โ€‹

1.6. Iterating Over Mapsโ€‹

You can iterate over a Map using the for...of loop:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

for (const [key, value] of map) {
console.log(`${key} = ${value}`); // key1 = value1, key2 = value2
}

You can also iterate over a Map using the forEach() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

forEach((value, key) => {
console.log(`${key} = ${value}`); // key1 = value1, key2 = value2
});

1.7. Converting Maps to Arraysโ€‹

You can convert a Map to an array using the Array.from() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

const array = Array.from(map);
console.log(array); // [ ['key1', 'value1'], ['key2', 'value2'] ]

1.8. Converting Maps to Objectsโ€‹

You can convert a Map to an object using the Object.fromEntries() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

const object = Object.fromEntries(map);
console.log(object); // { key1: 'value1', key2: 'value2' }

Suggested Tutorials ๐Ÿ“‘:โ€‹

1.9. Converting Objects to Mapsโ€‹

You can convert an object to a Map using the Object.entries() method:

const object = { key1: 'value1', key2: 'value2' };
const map = new Map(Object.entries(object));
console.log(map); // Map { 'key1' => 'value1', 'key2' => 'value2' }

1.10. Converting Maps to JSONโ€‹

You can convert a Map to JSON using the JSON.stringify() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

const json = JSON.stringify([...map]);
console.log(json); // [["key1","value1"],["key2","value2"]]

1.11. Converting JSON to Mapsโ€‹

You can convert JSON to a Map using the JSON.parse() method:

const json = '[["key1","value1"],["key2","value2"]]';
const map = new Map(JSON.parse(json));
console.log(map); // Map { 'key1' => 'value1', 'key2' => 'value2' }

1.12. Cloning Mapsโ€‹

You can clone a Map using the Map() constructor:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');

const clone = new Map(map);
console.log(clone); // Map { 'key1' => 'value1', 'key2' => 'value2' }

1.13. Filtering Mapsโ€‹

You can filter a Map using the Map() constructor and the Array.from() method:

const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
map.set('key3', 'value3');
map.set('key4', 'value4');

const filtered = new Map(Array.from(map).filter(([key, value]) => key === 'key1' || key === 'key2'));

console.log(filtered); // Map { 'key1' => 'value1', 'key2' => 'value2' }

Suggested Tutorials ๐Ÿ“‘:โ€‹

2. Differences between Maps and Objectsโ€‹

Here are some of the key differences between Maps and objects:

  • The keys of an object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
  • You can get the size of a Map easily with the size property, while the number of properties in an object must be determined manually.
  • A Map is an iterable and can thus be directly iterated, whereas iterating over an object requires obtaining its keys in some fashion and iterating over them.
  • An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.
  • A Map may perform better in scenarios involving frequent addition and removal of key pairs.

3. What are Sets?โ€‹

Sets are a new data structure in ES6 that allow you to store unique values without duplicates.

Sets are similar to arrays in that both let you store values, retrieve those values, delete values, and detect whether something is stored in a set.

However, there are some important differences that make Sets preferable in certain cases.

3.1. Creating Setsโ€‹

Sets are created using the Set() constructor:

const set = new Set();

You can also pass an array of values to the Set() constructor:

const set = new Set(['value1', 'value2']);

3.2. Adding and Retrieving Valuesโ€‹

You can add values to a Set using the add() method:

const set = new Set();
set.add('value1');
set.add('value2');

You can retrieve values from a Set using the has() method:

const set = new Set();
set.add('value1');
set.add('value2');

console.log(set.has('value1')); // true
console.log(set.has('value2')); // true
console.log(set.has('value3')); // false

Suggested Tutorials ๐Ÿ“‘:โ€‹

3.3. Checking for Valuesโ€‹

You can check whether a Set contains a value using the has() method:

const set = new Set();
set.add('value1');
set.add('value2');

console.log(set.has('value1')); // true
console.log(set.has('value2')); // true
console.log(set.has('value3')); // false

3.4. Deleting Valuesโ€‹

You can delete values from a Set using the delete() method:

const set = new Set();
set.add('value1');
set.add('value2');

set.delete('value1');
console.log(set.has('value1')); // false

3.5. Getting the Size of a Setโ€‹

You can get the size of a Set using the size property:

const set = new Set();
set.add('value1');
set.add('value2');

console.log(set.size); // 2

3.6. Iterating Over Setsโ€‹

You can iterate over a Set using the for...of loop:

const set = new Set();
set.add('value1');
set.add('value2');

for (const value of set) {
console.log(value); // value1, value2
}

You can also iterate over a Set using the forEach() method:

const set = new Set();
set.add('value1');
set.add('value2');

set.forEach(value => {
console.log(value); // value1, value2
});

3.7. Converting Sets to Arraysโ€‹

You can convert a Set to an array using the Array.from() method:

const set = new Set();
set.add('value1');
set.add('value2');

const array = Array.from(set);
console.log(array); // [ 'value1', 'value2' ]

Suggested Tutorials ๐Ÿ“‘:โ€‹

3.8. Converting Arrays to Setsโ€‹

You can convert an array to a Set using the Set() constructor:

const array = ['value1', 'value2'];
const set = new Set(array);
console.log(set); // Set { 'value1', 'value2' }

3.9. Converting Sets to JSONโ€‹

You can convert a Set to JSON using the JSON.stringify() method:

const set = new Set();
set.add('value1');
set.add('value2');

const json = JSON.stringify([...set]);
console.log(json); // ["value1","value2"]

3.10. Converting JSON to Setsโ€‹

You can convert JSON to a Set using the JSON.parse() method:

const json = '["value1","value2"]';
const set = new Set(JSON.parse(json));
console.log(set); // Set { 'value1', 'value2' }

3.11. Cloning Setsโ€‹

You can clone a Set using the Set() constructor:

const set = new Set();
set.add('value1');
set.add('value2');

const clone = new Set(set);
console.log(clone); // Set { 'value1', 'value2' }

3.12. Filtering Setsโ€‹

You can filter a Set using the Set() constructor and the Array.from() method:

const set = new Set();
set.add('value1');
set.add('value2');
set.add('value3');
set.add('value4');

const filtered = new Set(Array.from(set).filter(value => value === 'value1' || value === 'value2'));

console.log(filtered); // Set { 'value1', 'value2' }

4. Differences between Sets and Arraysโ€‹

Here are some of the key differences between Sets and arrays:

  • Sets are not indexed-based - you do not refer to items in a set based on their position in the set.
  • Items in a Set can't be accessed individually.
  • You can easily remove a value from a Set.
  • Sets are iterable, so you can directly loop over them.
  • A value in a Set occurs only once - duplicates are not allowed.
  • Sets can be combined with arrays to create new arrays that contain unique values.

Suggested Tutorials ๐Ÿ“‘:โ€‹

Conclusionโ€‹

Maps and Sets are powerful data structures that provide enhanced ways to manage and manipulate data in JavaScript.

Maps offer key-value pair storage, while Sets store unique values without duplicates.

In this guide, we explored the fundamentals of Maps and Sets and saw how they can simplify various programming tasks.

We also saw the differences between Maps and objects, and between Sets and arrays.

We hope you found this guide helpful.

Happy coding! ๐Ÿฅณ

ยท 3 min read

"Enhance User Experience: Create an Interactive Collapsible FAQ Section with JavaScript"

Introductionโ€‹

Collapsible FAQ (Frequently Asked Questions) sections are a user-friendly way to present information and save space on your website. Using JavaScript, you can create a dynamic experience where users can expand and collapse questions and answers.

In this guide, we'll walk you through the process of creating a collapsible FAQ section step by step.

1. HTML Structureโ€‹

Set up the HTML structure for your FAQ section. Each question will have a corresponding answer.


<!DOCTYPE html>
<html>
<head>
<title>Collapsible FAQ</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="faq">
<div class="question">
<h3>Question 1: What is JavaScript?</h3>
<span class="toggle">+</span>
</div>
<div class="answer">
<p>JavaScript is a programming language...</p>
</div>
<!-- Repeat for other questions -->
</div>
<script src="script.js"></script>
</body>
</html>

2. CSS Stylingโ€‹

Style your FAQ section using CSS. You'll hide the answer sections by default and style the toggling button.


.faq {
width: 500px;
margin: 0 auto;
}

.question {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 1rem;
cursor: pointer;
}

.question:hover {
background-color: #f5f5f5;
}

.question h3 {
margin: 0;
}

.answer {
display: none;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 1rem;
}

.toggle {
font-size: 1.5rem;
font-weight: bold;
color: #ccc;
}

3. JavaScript Functionalityโ€‹

Add JavaScript functionality to your FAQ section. When a user clicks on a question, the corresponding answer will be displayed. The toggle button will also change from a plus sign to a minus sign.


const questions = document.querySelectorAll('.question');

questions.forEach(question => {
question.addEventListener('click', () => {
const answer = question.nextElementSibling;
const toggle = question.querySelector('.toggle');

if (answer.style.display === 'block') {
answer.style.display = 'none';
toggle.textContent = '+';
} else {
answer.style.display = 'block';
toggle.textContent = '-';
}
});
});

Conclusionโ€‹

By combining HTML, CSS, and JavaScript, you've successfully created a collapsible FAQ section. Users can now expand and collapse questions to access answers as needed. This dynamic interaction enhances user experience and provides an organized way to present information on your website. You can further customize the styling and behavior to match your site's design and requirements. With this technique, you've added a valuable feature that improves the accessibility and usability of your web content.

We hope you found this tutorial helpful.

Happy coding! ๐ŸŽ‰

ยท 5 min read

&quot;Choosing the Right Data Fetching Strategy: AJAX vs. Fetch vs. Axios in JavaScript&quot;

Introductionโ€‹

Fetching data from remote servers is a common task in web development. In JavaScript, there are several approaches to accomplish this, with AJAX, Fetch API, and third-party libraries like Axios being popular choices.

In this guide, we'll explore these data fetching strategies, their features, and when to use each one.

Let's get started!

1. AJAX (Asynchronous JavaScript and XML)โ€‹

AJAX is a traditional approach for making asynchronous requests to a server and fetching data without reloading the entire page.

AJAX is a browser technology that uses a combination of:

  • HTML and CSS for presentation
  • JavaScript for dynamic behavior
  • XML for data interchange

Here's an example of an AJAX request using the XMLHttpRequest object:


const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();

In the example above:

  • We create a new XMLHttpRequest object and use the open() method to initialize a request.

  • The open() method accepts three arguments:

    • The HTTP method (GET, POST, PUT, DELETE, etc.)
    • The URL of the resource to be fetched
    • A boolean value indicating whether the request should be asynchronous or not
  • We use the onreadystatechange event handler to listen for changes in the request state.

  • When the request state is 4 (request finished and response is ready) and the status code is 200 (OK), we parse the response text into a JavaScript object and log it to the console.

  • Finally, we call the send() method to send the request to the server.

2. Fetch APIโ€‹

The Fetch API is a modern replacement for the XMLHttpRequest object. It provides a simple, powerful, and flexible interface for fetching resources from the server.

Here's an example of a Fetch request:


fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

In the example above:

  • We use the fetch() method to make a GET request to the specified URL.
  • The fetch() method returns a Promise object that resolves to a Response object.
  • We use the json() method to parse the response body into a JavaScript object.
  • We use the then() method to handle the resolved Promise object.
  • We use the catch() method to handle any errors that may occur.

3. Axios (Third-party library)โ€‹

Axios is a popular third-party library that simplifies HTTP requests and handling responses. It works both in browsers and Node.js.

Learn more about Axios here.

Here's an example of an Axios request:


axios
.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.log(error));

In the example above:

  • We use the get() method to make a GET request to the specified URL.
  • The get() method returns a Promise object that resolves to a Response object.
  • We use the then() method to handle the resolved Promise object.
  • Then we use the catch() method to handle any errors that may occur.

Features and Considerationsโ€‹

AJAX

  • Widely supported, even in older browsers.
  • Requires more boilerplate code for handling responses and errors.
  • Might need additional libraries for Promise-based handling.

Fetch API

  • Modern and built into modern browsers.
  • Returns Promises, making async/await syntax easy to use.
  • Supports different types of data, like JSON, text, and more.

Axios

  • Third-party library with built-in Promise support.
  • Handles request and response interception, making error handling more centralized.
  • Handles JSON parsing by default.

When to Use Each Approachโ€‹

  • Use AJAX if you need to support older browsers or if you prefer not to use third-party libraries.

  • Use the Fetch API if you want to leverage modern browser features and Promises. It's a great choice for most data fetching needs.

  • Use Axios if you want a comprehensive solution with enhanced features like error handling, request/response interception, and a more consistent API.

Conclusionโ€‹

When it comes to data fetching strategies in JavaScript, you have options. AJAX, Fetch API, and Axios each offer unique features and benefits. Choose the strategy that aligns with your project's requirements, browser support, and your preferred coding style. Understanding these strategies will equip you with the tools needed to efficiently fetch data and build responsive web applications.

We hope you found this guide helpful.

Happy coding! ๐Ÿ™Œ

ยท 3 min read

&quot;Build a Dark Mode Toggle with JavaScript and localStorage&quot;

Introductionโ€‹

Dark mode has become a popular feature in modern web design, offering a more comfortable viewing experience in low-light conditions. With JavaScript, you can implement a toggle switch that enables users to switch between light and dark modes.

In this guide, we'll walk you through the process of implementing dark mode using JavaScript to toggle styles.

Let's get started!

1. HTML and CSS Setupโ€‹

First, we'll create a basic HTML page with a button that will be used to toggle between light and dark modes. We'll also add a data-theme attribute to the body element to store the current theme.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Dark Mode Toggle</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body data-theme="light">
<button id="toggle">Toggle</button>
<script src="./script.js"></script>
</body>

</html>

2. CSS Stylesโ€‹

Next, we'll add some basic styles to the page. We'll use the :root selector to define CSS variables for the light and dark themes. We'll also use the body[data-theme="dark"] selector to define styles for the dark theme.


:root {
--bg-color: #fff;
--text-color: #000;
}

body[data-theme="dark"] {
--bg-color: #000;
--text-color: #fff;
}

body {
background-color: var(--bg-color);
color: var(--text-color);
}

3. JavaScript Functionalityโ€‹

Now, we'll add some JavaScript to toggle the theme when the button is clicked. We'll use the document.body.dataset.theme property to get the current theme and toggle it between light and dark.


const toggle = document.getElementById("toggle");

toggle.addEventListener("click", () => {
const currentTheme = document.body.dataset.theme;
const nextTheme = currentTheme === "dark" ? "light" : "dark";
document.body.dataset.theme = nextTheme;
});

4. Add localStorageโ€‹

Finally, we'll add some localStorage to store the current theme. This will allow the theme to persist when the page is refreshed.


const toggle = document.getElementById("toggle");

toggle.addEventListener("click", () => {
const currentTheme = document.body.dataset.theme;
const nextTheme = currentTheme === "dark" ? "light" : "dark";
document.body.dataset.theme = nextTheme;
localStorage.setItem("theme", nextTheme);
});

const currentTheme = localStorage.getItem("theme");
if (currentTheme) {
document.body.dataset.theme = currentTheme;
}

Conclusionโ€‹

That's it! You've successfully implemented dark mode using JavaScript to toggle styles. in this guide, we learned how to:

  • Create a basic HTML page with a button that will be used to toggle between light and dark modes.
  • Add some basic styles to the page using the :root selector to define CSS variables for the light and dark themes.
  • Use the document.body.dataset.theme property to get the current theme and toggle it between light and dark.
  • Add some localStorage to store the current theme. This will allow the theme to persist when the page is refreshed.

Thanks for reading and happy coding!

ยท 4 min read

&quot;JavaScript Timers: setTimeout, setInterval, and requestAnimationFrame&quot;

Introductionโ€‹

In JavaScript, timers are essential for scheduling and managing tasks that occur asynchronously. These timers allow you to control when functions or code snippets should run. Three commonly used timers are setTimeout, setInterval, and requestAnimationFrame.

In this guide, we'll explore each timer's purpose, usage, and how they differ from one another.

Let's dive in! ๐ŸŠโ€โ™€๏ธ

1. The setTimeoutโ€‹

The setTimeout method is used to schedule a function or code snippet to run after a specified amount of time. It accepts two arguments: a callback function and a delay in milliseconds.

For example:


const timeoutId = setTimeout(() => {
console.log("Timeout!");
}, 1000); // After 1 second

// To stop the timeout on function call
const stopTimeout=(timeoutId)=>{
clearTimeout(timeoutId);
}

In the example above:

  • The setTimeout method is used to schedule a function to run after 1000 milliseconds (1 second).
  • The callback function passed to setTimeout will be executed after 1000 milliseconds (1 second).
  • The setTimeout method returns a timeout ID that can be used to stop the timeout using the clearTimeout method.
  • The clearTimeout method is used to stop the timeout after 5000 milliseconds (5 seconds).

2. The setIntervalโ€‹

The setInterval method is used to schedule a function or code snippet to run repeatedly after a specified amount of time. It accepts two arguments: a callback function and a delay in milliseconds.

For example:


let count = 0;
const intervalId = setInterval(() => {
console.log("Interval count:", count++);
}, 1000); // Every 1 second

// To stop the interval after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 5000);


In the example above:

  • The setInterval method is used to schedule a function to run every 1000 milliseconds (1 second).
  • The callback function passed to setInterval will be executed every 1000 milliseconds (1 second).
  • The setInterval method returns an interval ID that can be used to stop the interval using the clearInterval method.
  • The clearInterval method is used to stop the interval after 5000 milliseconds (5 seconds).

3. The requestAnimationFrameโ€‹

requestAnimationFrame is designed for smoother animations and rendering, taking the browser's optimization into account.

For example:


function animate(timestamp) {
// Animation logic here
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

In the example above:

  • The requestAnimationFrame method is used to schedule a function to run before the next repaint.
  • The callback function passed to requestAnimationFrame will be executed before the next repaint.

Usage Differencesโ€‹

  • setTimeout: Used for delaying a single function execution.
  • setInterval: Used for executing a function repeatedly at fixed intervals.
  • requestAnimationFrame: Used for smoother animations and rendering, respecting browser optimizations.

Advantage and Best Practicesโ€‹

  • Use setTimeout when you want to delay a specific action.
  • Prefer setInterval when you need to perform a task at fixed intervals.
  • Use requestAnimationFrame for animations, as it synchronizes with the browser's rendering.

Considerationsโ€‹

  • Be cautious with setInterval, as if tasks take longer than the interval, they can overlap, causing performance issues.
  • requestAnimationFrame is generally recommended for animations due to its efficient use of browser resources.

Conclusionโ€‹

JavaScript timers, namely setTimeout, setInterval, and requestAnimationFrame, provide essential tools for managing asynchronous tasks and animations. Depending on your use case, you can effectively schedule actions or create smooth animations using these timers. By understanding their purposes and differences, you'll have the tools you need to build responsive and interactive web applications.

We hope you found this guide helpful!

Happy coding! ๐Ÿš€

ยท 5 min read

&quot;Getting Started with Jest: A Practical Guide to JavaScript Unit Testing&quot;

Introductionโ€‹

Unit testing is a fundamental practice in software development that helps ensure the reliability and correctness of your code. Jest is a popular JavaScript testing framework that simplifies the process of writing and executing unit tests.

In this guide, we'll walk you through the process of getting started with Jest for unit testing in JavaScript.

What is Jest?โ€‹

Jest is a JavaScript testing framework that was developed by Facebook. It is a popular choice for testing React applications, but it can also be used to test any JavaScript code.

Jest is an open-source project that is maintained by Facebook and the community. It is licensed under the MIT license and is free to use.

Learn more about Jest by visiting its official website.

1. Install Jestโ€‹

To get started with Jest, you'll need to install it as a development dependency in your project. You can do this by running the following command in your terminal:


npm install --save-dev jest

2. Create a Test Fileโ€‹

Next, you'll need to create a test file for your code. Jest will look for test files with the .test.js or .spec.js extension.

For example, if you have a file named sum.js that contains the following code:


function sum(a, b) {
return a + b;
}

module.exports = sum;

You can create a test file named sum.test.js that contains the following code:


const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

3. Run the Testsโ€‹

Finally, you can run the tests by running the following command in your terminal:


npm test

and you should see the following output:


PASS ./sum.test.js
โœ“ adds 1 + 2 to equal 3 (5ms)

4. More Assertionsโ€‹

Jest provides a variety of assertion functions like expect, toBe, toEqual, toBeTruthy, toBeFalsy, and many more to test different aspects of your code.

For example, you can use the toBeTruthy assertion function to test if a value is truthy:


test('true is truthy', () => {
expect(true).toBeTruthy();
});

You can also use the toBeFalsy assertion function to test if a value is falsy:


test('false is falsy', () => {
expect(false).toBeFalsy();
});

5. Mockingโ€‹

Jest provides a variety of mocking functions like jest.fn, jest.spyOn, jest.mock, and many more to mock different aspects of your code.

For example, you can use the jest.fn mocking function to mock a function:


const mockFn = jest.fn();

6. Asynchronous Testingโ€‹

Jest provides a variety of asynchronous testing functions like test, it, expect, beforeEach, afterEach, beforeAll, afterAll, and many more to test asynchronous code.

For example, you can use the test function to test asynchronous code:


test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}

fetchData(callback);
});

Configuring Jestโ€‹

Jest's default configuration usually suffices for most projects. However, you can create a jest.config.js file to customize settings if needed.

For example, you can use the testEnvironment option to specify the test environment:


module.exports = {
testEnvironment: 'node',
};

with the following options:

  • node: Runs tests in a Node.js environment.
  • jsdom: Runs tests in a JSDOM environment.

You can also use the testMatch option to specify the test files to run:


module.exports = {
testMatch: ['**/__tests__/**/*.js?(x)', '**/?(*.)+(spec|test).js?(x)'],
};

You can also use the testPathIgnorePatterns option to specify the test files to ignore:


module.exports = {
testPathIgnorePatterns: ['/node_modules/'],
};

You can also use the testRegex option to specify the test files to run:


module.exports = {
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.jsx?$',
};

and many more options.

Conclusionโ€‹

Jest simplifies the process of writing and running unit tests in JavaScript. By following these steps, you've learned how to get started with Jest and write your first unit test. Unit testing helps you catch bugs early, improve code quality, and build more robust applications. As you become more familiar with Jest, you can explore its advanced features and techniques for more comprehensive testing of your JavaScript code.

We hope you found this guide helpful.

Happy coding! ๐Ÿ˜ƒ

ยท 3 min read

&quot;Create a Character Counter for Textareas with JavaScript: Step-by-Step Guide&quot;

Introductionโ€‹

A character counter is a helpful feature for forms and text areas, allowing users to see how many characters they have entered and providing real-time feedback.

In this blog article, we'll guide you through the process of building a character counter using HTML, CSS, and JavaScript. You'll learn how to create a dynamic counter that updates as users type in a textarea field.

First we'll start with the HTML and CSS, then we'll add the JavaScript to make the counter work.

HTML Structureโ€‹

Set up the HTML structure for your character counter.


<!DOCTYPE html>
<html>
<head>
<title>Character Counter</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<label for="textarea">Enter your text:</label>
<textarea id="textarea" rows="4" maxlength="100"></textarea>
<p><span id="counter">0</span> / 100 characters</p>
</div>
<script src="script.js"></script>
</body>
</html>

2. CSS Stylingโ€‹

Create a styles.css file to style your character counter.


body {
margin: 0;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f9f9f9;
}

.container {
border: 1px solid #ddd;
padding: 20px;
width: 300px;
background-color: white;
}

label {
font-weight: bold;
margin-bottom: 10px;
display: block;
}

textarea {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
resize: none;
}

p {
margin-top: 10px;
}

#counter {
font-weight: bold;
}

3. JavaScript Character Counterโ€‹

Implement the JavaScript logic for the character counter in your script.js file.


const textarea = document.getElementById('textarea');
const counter = document.getElementById('counter');

textarea.addEventListener('input', updateCounter);

function updateCounter() {
const currentLength = textarea.value.length;
const maxLength = parseInt(textarea.getAttribute('maxlength'));

counter.textContent = currentLength;

if (currentLength > maxLength) {
counter.style.color = 'red';
} else {
counter.style.color = 'black';
}
}

Conclusionโ€‹

Congratulations! You've successfully built a character counter for textareas using HTML, CSS, and JavaScript. This feature provides users with real-time feedback on the number of characters they've entered, helping them stay within any specified limits. You can further customize the styling and behavior of the counter to match your website's design and requirements. By combining these technologies, you've added a practical and user-friendly element to your forms, improving the user experience and making your website more interactive.

We hope you found this tutorial helpful.

Happy Coding! ๐ŸŽ‰

ยท 4 min read

&quot;Exploring the &#39;let&#39; and &#39;const&#39; Variables in JavaScript&quot;

Introductionโ€‹

In every programming language, variables play a crucial role in storing and managing data. The introduction of the 'let' and 'const' keywords in ECMAScript 6 (ES6) brought significant improvements to variable declaration and scoping.

In this guide, we'll explore the differences between 'let' and 'const', their usage, and their impact on variable hoisting and scoping.

Let's get started!

What is a Variable?โ€‹

A variable is a named container that stores data. It is used to store data temporarily in the computer's memory. The data stored in a variable can be changed or updated during the execution of a program.

In JavaScript, variables are declared using the 'var', 'let', or 'const' keywords.

1. The let Keywordโ€‹

The let keyword allows you to declare variables with block-level scoping. Variables declared with let are mutable and can be reassigned.

As an example

let count = 1;
count = 2; // Reassignment is allowed
tip

Variables declared with let are not hoisted to the top of their block; they are hoisted but remain uninitialized until the point of declaration.

2. The const Keywordโ€‹

The const keyword also introduces block-level scoping, but variables declared with const are read-only and cannot be reassigned.

As an example

const pi = 3.14159;
// pi = 3.14; // Throws an error

3. Block Scopingโ€‹

Both let and const have block-level scoping, meaning they are confined to the block (curly braces) in which they are defined.

As an example


if (true) {
let localVar = 'Inside block';
}
// console.log(localVar); // Throws an error

In the example above:

  • The variable 'localVar' is declared inside the 'if' block and is not accessible outside the block.

4. Temporal Dead Zone (TDZ)โ€‹

The Temporal Dead Zone is a phenomenon that occurs when accessing a variable declared with let or const before its actual declaration in the code.

As an example


console.log(x); // Throws a ReferenceError
let x = 10;

In the example above:

  • The variable 'x' is declared with let but is accessed before its declaration. This throws a ReferenceError because the variable is in the Temporal Dead Zone.

5. Best Practicesโ€‹

  • Use const for variables that will not be reassigned.
  • Use let for variables that will be reassigned.
  • Avoid using var as it has function-level scoping and can lead to bugs in your code.

6. Choosing Between let and constโ€‹

  • Use let for values that are expected to change (loop counters, etc.).
  • Use const for values that are not expected to change (constants, etc.).

Conclusionโ€‹

Understanding the differences between let and const variables is essential for writing maintainable and error-free JavaScript code. By using let and const appropriately, you can create clear and predictable variable scoping and reduce the risk of bugs caused by variable reassignment. Whether you're working with mutable data or constant values, the let and const keywords provide a powerful and flexible way to manage variables in modern JavaScript development.

We hope you found this guide useful.

Happy coding! ๐Ÿš€

ยท 3 min read

&quot;Enhance User Experience: Create Custom Browser Alerts with JavaScript&quot;

Introductionโ€‹

Customizing browser alerts using JavaScript allows you to create personalized and visually appealing pop-up messages for your website users. Unlike the default browser alerts, custom alerts can be tailored to match your website's design and provide a more user-friendly experience.

In this article, we'll walk you through the process of creating personalized alerts using HTML, CSS, and JavaScript.

Suggested Tutorials ๐Ÿ“‘:โ€‹

Let's dive in! ๐Ÿคฟ

1. Create the HTML Markupโ€‹

Set up the HTML structure for your custom alert.


<!DOCTYPE html>
<html>
<head>
<title>Custom Alerts</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="showAlert">Show Custom Alert</button>
<script src="script.js"></script>
</body>
</html>

2. Create the CSS Stylesโ€‹

Add the CSS styles to customize the appearance of your alert.

body {
margin: 0;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f9f9f9;
}

.alert-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1;
}

.alert-box {
background-color: white;
border-radius: 5px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
text-align: center;
}

.alert-box h2 {
margin: 0;
font-size: 24px;
font-weight: 500;
color: #333;
}

.alert-box p {
margin: 10px 0 20px;
font-size: 16px;
color: #666;
}

.alert-box button {
padding: 10px 20px;
border: none;
border-radius: 5px;
background-color: #333;
color: white;
font-size: 16px;
cursor: pointer;
}

Suggested Tutorials ๐Ÿ“‘:โ€‹

3. Create the JavaScript Functionโ€‹

Implement the JavaScript logic for showing and hiding the custom alert in your script.js file.


const showAlertButton = document.getElementById('showAlert');
const alertOverlay = document.createElement('div');
const alertBox = document.createElement('div');

alertOverlay.classList.add('alert-overlay');
alertBox.classList.add('alert-box');
alertBox.innerHTML = `
<h2>Custom Alert</h2>
<p>This is a personalized alert!</p>
<button id="closeAlert">Close</button>
`;

showAlertButton.addEventListener('click', () => {
document.body.appendChild(alertOverlay);
alertOverlay.appendChild(alertBox);
});

alertOverlay.addEventListener('click', event => {
if (event.target === alertOverlay) {
alertOverlay.remove();
}
});

document.addEventListener('click', event => {
if (event.target.id === 'closeAlert') {
alertOverlay.remove();
}
});

Conclusionโ€‹

Congratulations! ๐Ÿฅณ You've successfully created personalized custom alerts using HTML, CSS, and JavaScript. By customizing the appearance and behavior of alerts, you can provide a more engaging and user-friendly experience for your website visitors. You can further enhance your custom alerts by adding animations, additional styling, and interactive features. With these technologies, you've added a visually appealing and personalized touch to the way you communicate important messages to your users.

We hope you found this tutorial helpful.

Happy coding! ๐Ÿ˜ƒ

Suggested Tutorials ๐Ÿ“‘:โ€‹