Skip to content

JavaScript Logic errors

  • by

JavaScript logic errors refer to errors in your code’s logic, which can cause the code to produce unexpected or incorrect output, even when it runs without syntax or runtime errors. These errors can be difficult to debug because the code runs without any error messages, but the results are still wrong.

Some examples of common logic errors in JavaScript include incorrect conditional statements, off-by-one errors, incorrect order of operations, and infinite loops.

  1. Off-by-one errors: These errors occur when you’re working with arrays or loops, and you’re off by one index or iteration. For example, if you’re trying to loop through an array and accidentally skip the first or last element.
  2. Incorrect conditional statements: These errors occur when you use the wrong comparison operator or negate a condition by accident. For example, if you’re trying to check if a value is greater than or equal to 10 but accidentally use the less than or equal to operator.
  3. Incorrect order of operations: These errors occur when you’re performing mathematical operations and the order of operations is incorrect. For example, if you’re trying to calculate a percentage but divide the wrong numbers.
  4. Infinite loops: These errors occur when you have a loop that never stops running, causing your program to crash or freeze. For example, if you accidentally create a while loop that always evaluates to true.

JavaScript Logic errors examples

Simple example code.

<!DOCTYPE html>
<html>
<body>
    <script>
    function calculateAverage(nums) {
    let sum = 0;

    for (let i = 0; i <= nums.length; i++) {
        sum += nums[i];
    }

    let avg = sum / nums.length;
        return avg;
    }

    let numbers = [1, 2, 3, 4, 5];
    let avg = calculateAverage(numbers);
    console.log(`The average is ${avg}.`);
    </script>
</body>
</html>

Output:

JavaScript Logic errors

The purpose of this code is to calculate the average of an array of numbers. However, the output will be “The average is NaN,” which stands for “Not a Number.” The logic error in this code is that the loop in the calculateAverage function has an off-by-one error, since it’s iterating one extra time and attempting to access an index that doesn’t exist in the nums array.

To fix this error, we can change the loop condition to i < nums.length:

function calculateAverage(nums) {
  let sum = 0;

  for (let i = 0; i < nums.length; i++) {
    sum += nums[i];
  }

  let avg = sum / nums.length;
  return avg;
}

let numbers = [1, 2, 3, 4, 5];
let avg = calculateAverage(numbers);
console.log(`The average is ${avg}.`);

Do comment if you have any doubts on this Js error topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *