Explore a variety of JavaScript exercises and challenges designed to reinforce learning and encourage creative application of programming concepts.
Welcome to the Additional Exercises and Challenges section of “JavaScript Essentials: Getting Started with Programming.” This section is designed to help you reinforce the concepts you’ve learned throughout the book by providing practical exercises and challenges. These exercises range in difficulty, allowing you to start simple and gradually tackle more complex problems as you build your confidence and skills.
// Basic "Hello, World!" program
console.log("Hello, World!");
// Challenge: Greet a user by name
let userName = "Alice";
console.log("Hello, " + userName + "!");
// Declare two variables and assign them values
let num1 = 5;
let num2 = 10;
// Calculate the sum of num1 and num2
let sum = num1 + num2;
// Output the result to the console
console.log("The sum is: " + sum);
typeof
operator.// Declare variables of different data types
let myString = "Hello";
let myNumber = 42;
let myBoolean = true;
let myNull = null;
let myUndefined;
// Output the type of each variable
console.log(typeof myString); // string
console.log(typeof myNumber); // number
console.log(typeof myBoolean); // boolean
console.log(typeof myNull); // object (special case)
console.log(typeof myUndefined); // undefined
// Declare two numbers and an operator
let a = 8;
let b = 4;
let operator = '+';
// Perform the operation based on the operator
let result;
if (operator === '+') {
result = a + b;
} else if (operator === '-') {
result = a - b;
} else if (operator === '*') {
result = a * b;
} else if (operator === '/') {
result = a / b;
}
// Output the result
console.log("The result is: " + result);
// Declare a score
let score = 85;
// Determine the grade based on the score
let grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
// Output the grade
console.log("The grade is: " + grade);
// Declare a number for the multiplication table
let number = 5;
// Use a loop to generate the multiplication table
for (let i = 1; i <= 10; i++) {
console.log(number + " x " + i + " = " + (number * i));
}
// Function to convert temperatures
function convertTemperature(temp, unit) {
if (unit === 'C') {
return (temp * 9/5) + 32; // Convert Celsius to Fahrenheit
} else if (unit === 'F') {
return (temp - 32) * 5/9; // Convert Fahrenheit to Celsius
}
}
// Test the function
console.log(convertTemperature(0, 'C')); // 32
console.log(convertTemperature(32, 'F')); // 0
// Create an array of numbers
let numbers = [5, 3, 8, 1];
// Add a number to the end of the array
numbers.push(7);
// Remove the first number from the array
numbers.shift();
// Sort the array in ascending order
numbers.sort((a, b) => a - b);
// Output the modified array
console.log(numbers);
// Create an object representing a book
let book = {
title: "JavaScript Essentials",
author: "Tokenizer Inc.",
year: 2024,
displayInfo: function() {
console.log(this.title + " by " + this.author + ", published in " + this.year);
}
};
// Call the method to display the book's information
book.displayInfo();
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation</title>
</head>
<body>
<h1 id="myHeading">Original Heading</h1>
<button onclick="changeHeading()">Change Heading</button>
<script>
// Function to change the heading's text
function changeHeading() {
document.getElementById('myHeading').innerText = "New Heading";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Interactive List</title>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button onclick="addItem()">Add Item</button>
<script>
// Function to add a new list item
function addItem() {
let newItem = document.createElement('li');
newItem.innerText = "New Item";
document.getElementById('myList').appendChild(newItem);
}
</script>
</body>
</html>
console.log()
to help debug and fix the issues.// Incorrect code with errors
let x = 10;
let y = 20;
let z = x + y;
console.log("The value of z is: " + z;
// Corrected code
let x = 10;
let y = 20;
let z = x + y;
console.log("The value of z is: " + z);
// Original code
let a = 5;
let b = 10;
let c = a + b;
console.log(c);
// Refactored code
let firstNumber = 5; // First number to add
let secondNumber = 10; // Second number to add
let sum = firstNumber + secondNumber; // Calculate the sum
console.log("The sum is: " + sum); // Output the result
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<style>
.completed {
text-decoration: line-through;
}
</style>
</head>
<body>
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add a new task">
<button onclick="addTask()">Add Task</button>
<ul id="taskList"></ul>
<script>
function addTask() {
let taskInput = document.getElementById('taskInput');
let taskText = taskInput.value;
if (taskText === '') {
alert('Please enter a task.');
return;
}
let taskItem = document.createElement('li');
taskItem.innerText = taskText;
taskItem.onclick = function() {
this.classList.toggle('completed');
};
document.getElementById('taskList').appendChild(taskItem);
taskInput.value = '';
}
</script>
</body>
</html>
To truly master JavaScript, it’s important to experiment and try modifying the code examples provided. Here are a few suggestions:
To help visualize some of the concepts, let’s use Mermaid.js diagrams.
graph TD; A[Start] --> B{Score >= 90?} B -->|Yes| C[Grade = A] B -->|No| D{Score >= 80?} D -->|Yes| E[Grade = B] D -->|No| F{Score >= 70?} F -->|Yes| G[Grade = C] F -->|No| H{Score >= 60?} H -->|Yes| I[Grade = D] H -->|No| J[Grade = F] C --> K[End] E --> K G --> K I --> K J --> K
Description: This flowchart represents the logic used in the Grade Evaluator exercise, showing how the program determines the grade based on the score.
For further reading and to deepen your understanding of JavaScript, consider exploring the following resources:
As you work through these exercises, consider these questions:
In this section, we’ve provided a variety of exercises and challenges to help you practice and apply the JavaScript concepts covered in this book. By working through these problems, you’ll gain a deeper understanding of programming and build the confidence to tackle more complex projects.
By engaging with these exercises and quiz questions, you’re taking significant steps toward mastering JavaScript. Keep practicing, and don’t hesitate to explore additional resources to expand your knowledge!