Topic Overview and Actualization

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!

Introduction to Logical Errors

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?

let num1 = 10;
let num2 = 20;
let sum = num1 * num2; // Hint: Do we want a sum or a product?
console.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.

Pinpointing Logical Errors: Printing Method

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.

let num1 = 10;
let num2 = 20;
console.log("Expected sum:", num1 + num2); // Sum has to be 30
let sum = num1 * num2; // Error here.
console.log("Actual sum:", sum); // Displays 200, not 30

The unexpected discrepancy between "Expected sum" and "Actual sum" helps flag the logical error.

Common Logical Errors in JavaScript

Let's look at some common logical errors.

  • Off-by-One Errors: Commonly, this error creeps in when we accidentally step outside an array's bound.
let fruit = ["apple", "banana", "cherry"];
for (let num = 0; num <= fruit.length; num++) { 
    console.log(fruit[num]); // 'undefined' for the last output. Array is zero-indexed
}
  • Infinite loops where the stop condition never gets met:
let i = 0;
while(i >= 0) {   
  console.log(`Number: ${i}`);
  i++;
}
  • Mishandling boolean logic, incorrect use of logic operations:
let temperature = 30; // in Celcuis
console.log("The temperature is less than 20 degrees", temperature < 20);
console.log("The temperature is greater than 10 degrees", temperature > 10);
// Checking that the temperature is within the interval (10, 20)
if (temperature < 20 || temperature > 10) { // Wrong! We should use && instead of ||
  console.log("The weather is mild.");
} else {
  console.log("The weather is either too hot or too cold.");
}

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal