Advanced JavaScript Exercises

Advanced JavaScript Exercises

Advanced JavaScript Exercises (Part 5)

https://basescripts.com/advanced-javascript-exercises-part-5

Lesson Objective:

This lesson focuses on pushing the boundaries of JavaScript by exploring complex topics such as advanced DOM manipulation, algorithms, timing events, browser APIs, and more. The goal is to help learners solidify their understanding of core JavaScript concepts while solving practical coding challenges.

Learning Outcomes:

  • Gain proficiency with the setTimeout() and setInterval() functions.
  • Understand how to manipulate the DOM for various dynamic elements.
  • Learn about browser-specific APIs and how they can be leveraged in web development.
  • Write and understand algorithms for common coding problems using only JavaScript.

Exercise 1: Delayed Execution using setTimeout()

Learning Objective:

Learn how to delay the execution of a function using setTimeout().

function delayedGreeting() {

??console.log("Hello, after 3 seconds!");

}

console.log("This message appears first.");

setTimeout(delayedGreeting, 3000);

Explanation:

  • This exercise demonstrates the use of setTimeout() to delay the execution of a function by 3 seconds.
  • It highlights how JavaScript manages asynchronous behavior and scheduling.

Exercise 2: Countdown Timer using setInterval()

Learning Objective:

Learn how to create a simple countdown timer that updates every second using setInterval().

<p id="countdown">10</p>

<script>

let timeLeft = 10;

const countdownElement = document.getElementById('countdown');

const countdownInterval = setInterval(() => {

??timeLeft--;

??countdownElement.textContent = timeLeft;

??if (timeLeft === 0) {

????clearInterval(countdownInterval);

????alert("Time's up!");

??}

}, 1000);

</script>

Explanation:

  • setInterval() is used to repeatedly call a function every second.
  • The countdown timer updates the displayed time on the webpage every second until it reaches zero, at which point the interval is cleared.

Exercise 3: Simple Image Slideshow

Learning Objective:

Create a simple image slideshow using setInterval() to switch between images.

<img id="slideshow" src="image1.jpg" alt="Slideshow Image" width="400">

<script>

const images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];

let currentIndex = 0;

const slideshowElement = document.getElementById('slideshow');

setInterval(() => {

??currentIndex = (currentIndex + 1) % images.length;

??slideshowElement.src = images[currentIndex];

}, 2000);

</script>

Explanation:

  • This exercise creates a simple slideshow where the image changes every 2 seconds using setInterval().
  • It demonstrates how to loop through an array of images and update the src attribute dynamically.

Exercise 4: Fetch API to Display Data

Learning Objective:

Learn how to use the Fetch API to retrieve data from an external API and display it.

<ul id="todoList"></ul>

<script>

fetch('https://jsonplaceholder.typicode.com/todos')

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

??.then(data => {

????const todoList = document.getElementById('todoList');

????data.slice(0, 5).forEach(todo => {

??????const listItem = document.createElement('li');

??????listItem.textContent = todo.title;

??????todoList.appendChild(listItem);

????});

??})

??.catch(error => console.error('Error fetching data:', error));

</script>

Explanation:

  • This exercise demonstrates how to use the Fetch API to get data from an external API and dynamically display the first 5 items on the page.
  • The exercise helps learners understand asynchronous data fetching and DOM manipulation.

Exercise 5: Shuffle an Array

Learning Objective:

Understand how to implement an algorithm to shuffle an array.

function shuffleArray(arr) {

??for (let i = arr.length - 1; i > 0; i--) {

????const j = Math.floor(Math.random() * (i + 1));

????[arr[i], arr[j]] = [arr[j], arr[i]];

??}

??return arr;

}

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(shuffleArray(numbers)); // Example output: [5, 2, 8, 3, 7, 1, 6, 4, 9]

Explanation:

  • This function implements the Fisher-Yates (Knuth) shuffle algorithm to randomly shuffle an array.
  • The algorithm ensures a uniform shuffle by swapping elements as it traverses the array.

Exercise 6: Toggle Dark and Light Mode

Learning Objective:

Learn how to implement a light/dark mode toggle using JavaScript.

<button id="toggleMode">Toggle Dark Mode</button>

<style>

??body.dark-mode {

????background-color: black;

????color: white;

??}

</style>

<script>

const toggleButton = document.getElementById('toggleMode');

toggleButton.addEventListener('click', () => {

??document.body.classList.toggle('dark-mode');

});

</script>

Explanation:

  • This exercise demonstrates how to use JavaScript to toggle between light and dark mode on a webpage.
  • It uses the classList.toggle() method to switch between different styles by toggling a CSS class on the body.

Exercise 7: Detect Scroll Position

Learning Objective:

Learn how to detect the user's scroll position and trigger an action when a certain scroll depth is reached.

window.addEventListener('scroll', () => {

??const scrolled = window.scrollY;

??if (scrolled > 300) {

????console.log('Scrolled more than 300px down the page!');

??}

});

Explanation:

  • This exercise listens for the scroll event and checks the current vertical scroll position (scrollY).
  • When the user scrolls past 300 pixels, an action is triggered, providing a foundation for infinite scrolling or other scroll-based interactions.

Exercise 8: Get User's Current Location using Geolocation API

Learning Objective:

Learn how to use the Geolocation API to retrieve and display the user’s current coordinates.

<button id="getLocation">Get Location</button>

<p id="locationDisplay"></p>

<script>

const locationDisplay = document.getElementById('locationDisplay');

const getLocationButton = document.getElementById('getLocation');

getLocationButton.addEventListener('click', () => {

??if (navigator.geolocation) {

????navigator.geolocation.getCurrentPosition((position) => {

??????locationDisplay.textContent = Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude};

????}, () => {

??????locationDisplay.textContent = 'Unable to retrieve your location';

????});

??} else {

????locationDisplay.textContent = 'Geolocation is not supported by your browser';

??}

});

</script>

Explanation:

  • The Geolocation API allows you to access the user's current geographic location.
  • This exercise retrieves the user's latitude and longitude and displays it on the page when the button is clicked.

Exercise 9: Generate a Random Password

Learning Objective:

Learn how to create a random password generator using JavaScript.

function generatePassword(length) {

??const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()';

??let password = '';

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

????password += characters.charAt(Math.floor(Math.random() * characters.length));

??}

??return password;

}

console.log(generatePassword(12)); // Example output: 'aB1cD@2#Ef!'

Explanation:

  • This exercise generates a random password with a specified length using characters from a defined set.
  • It teaches learners how to work with random number generation and string manipulation to create a custom password generator.

Exercise 10: Modal Popup Implementation

Learning Objective:

Learn how to create a simple modal popup window using JavaScript.

<button id="openModal">Open Modal</button>

<div id="modal" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); padding:20px; background:white; border:2px solid black;">

??<p>This is a modal window</p>

??<button id="closeModal">Close Modal</button>

</div>

<script>

const modal = document.getElementById('modal');

const openModalButton = document.getElementById('openModal');

const closeModalButton = document.getElementById('closeModal');

openModalButton.addEventListener('click', () => {

??modal.style.display = 'block';

});

closeModalButton.addEventListener('click', () => {

??modal.style.display = 'none';

});

</script>

Explanation:

  • This exercise demonstrates how to create a modal popup using basic HTML, CSS, and JavaScript.
  • The modal is initially hidden (display: none) and is displayed or hidden when specific buttons are clicked, providing a simple example of dynamic user interaction with the UI.

Recap of Key Concepts:

These exercises reinforce a wide range of advanced JavaScript topics, including:

  1. Asynchronous Timing Functions (setTimeout and setInterval): Understanding how to schedule and repeat tasks using asynchronous timing functions.
  2. DOM Manipulation: Dynamically updating the DOM with elements, such as images and text, using JavaScript.
  3. API Interactions: Using the Fetch API to retrieve and display data from external sources.
  4. Algorithms: Implementing practical algorithms, such as shuffling arrays and generating random passwords, and understanding how they work.
  5. Browser APIs: Leveraging browser-specific features like the Geolocation API to access user-specific data, such as their current location.
  6. Event Handling: Managing user-triggered events like button clicks, scroll detection, and toggling between light and dark modes.
  7. UI Components: Building interactive UI elements like modals and slideshows from scratch using only JavaScript.
  8. String and Array Manipulation: Working with common operations on arrays (e.g., shuffling) and strings (e.g., generating random strings).

By completing these exercises, learners will have improved their ability to solve real-world problems using pure JavaScript, deepening their understanding of key concepts that are essential for web development without relying on libraries or frameworks.

Azeezat Nasir

Entry Level: Backend Developer | Full stack engineer | Decentralized Application developer |

1 个月

Very helpful, thanks a trillion

回复
Sadaf Shahab

Bachelors in Commerce | Front-end developer | Next JS | React JS | Tailwind CSS | Learning Certified Cloud Applied Generative AI, Engineer (GIAIC) | Learning Web & Mobile app development (SMIT)

2 个月

great

要查看或添加评论,请登录

JavaScript Developer WorldWide的更多文章

社区洞察

其他会员也浏览了