Welcome back, explorer! Today, we focus on a notorious code villain: Logical Errors. Unlike syntax errors from past lessons, logical errors whisper confusion into our program without halting it. They're often unnoticed, but when spotted, we can tackle them! So, let's dive in!
Logical errors pop up when our code deviates from our intended plan. There's no crashing of the program or error messages, which sounds fine, right? But hold on, they cause our output to diverge from what we anticipate.
Can you spot the logical error in the following piece of code?
JavaScript1let num1 = 10; 2let num2 = 20; 3let sum = num1 * num2; // Hint: Do we want a sum or a product? 4console.log(sum); // Prints 200, not 30!
Have you got it? Great! We wanted to add the numbers, but a multiplication operator slipped in by mistake. Such small mistakes can lead to logical errors, rendering incorrect output.
Finding logical errors might feel like locating a needle in a haystack. But worry not; we have some strategies. A useful method we employ involves using console.log()
statements to print variable values during program execution. These checkpoints help us identify whether everything is running well.
JavaScript1let num1 = 10; 2let num2 = 20; 3console.log("Expected sum:", num1 + num2); // Sum has to be 30 4let sum = num1 * num2; // Error here. 5console.log("Actual sum:", sum); // Displays 200, not 30
The unexpected discrepancy between "Expected sum" and "Actual sum" helps flag the logical error.
Let's look at some common logical errors.
JavaScript1let fruit = ["apple", "banana", "cherry"]; 2for (let num = 0; num <= fruit.length; num++) { 3 console.log(fruit[num]); // 'undefined' for the last output. Array is zero-indexed 4}
JavaScript1let i = 0; 2while(i >= 0) { 3 console.log(`Number: ${i}`); 4 i++; 5}
JavaScript1let temperature = 30; // in Celcuis 2console.log("The temperature is less than 20 degrees", temperature < 20); 3console.log("The temperature is greater than 10 degrees", temperature > 10); 4// Checking that the temperature is within the interval (10, 20) 5if (temperature < 20 || temperature > 10) { // Wrong! We should use && instead of || 6 console.log("The weather is mild."); 7} else { 8 console.log("The weather is either too hot or too cold."); 9}
Correcting such logical errors is a straightforward process. All it requires is a revision of the logic! You can also note how console.log
helps to identify the issue in all cases - you see every step of program execution that eventually helps to debug it!
Now, let's practice spotting and fixing logical errors using the examples above. We can add multiple console.log()
statements at key points in our code. Let's put this into practice.
JavaScript1let num1 = 10; 2let num2 = 20; 3let sum = num1 + num2; //Fixed Operator. We see correct output! 4console.log(sum); // Outputs 30. Great! 5 6let fruit = ["apple", "banana", "cherry"]; 7for (let num = 0; num < fruit.length; num++) { // Fixed Loop condition. Great job! 8 console.log(fruit[num]); // Each fruit neatly printed. Well done! 9}
Patience and logical thinking are your best allies when dealing with logical errors.
Now, warm up your fingers for some hands-on practice! Consider the code snippet below. Can you spot the logical error and then fix it?
JavaScript1let hoursWorked = 40; 2let hourlyRate = 10; 3let overtimeRate = 1.5; 4if (hoursWorked > 40) { 5 let totalPay = hoursWorked * (hourlyRate * overtimeRate); 6} else { 7 let totalPay = hoursWorked * hourlyRate; 8} 9console.log(totalPay);
You are right! The formula is a bit messed up - we should not multiply but add rates together, so it should be hourlyRate + overtimeRate
instead of hourlyRate * overtimeRate.
Fantastic work! We've traversed the process of identifying and fixing logical errors in JavaScript code. Armed with this knowledge, you're now ready to solve forthcoming exercises based on logical errors, unwinding your debugging skills. Happy coding and debugging!