Advanced JavaScript Exercises
JavaScript Developer WorldWide
Join the JavaScript Developers worldwide JavaScript Developers JavaScript Coders JavaScript Freelancers
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:
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:
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:
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:
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>
??.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:
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:
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:
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:
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:
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:
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:
Recap of Key Concepts:
These exercises reinforce a wide range of advanced JavaScript topics, including:
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.
Entry Level: Backend Developer | Full stack engineer | Decentralized Application developer |
1 个月Very helpful, thanks a trillion
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