Search⌘ K
AI Features

Solution Review: Fix the Code

Understand how to fix common JavaScript errors by applying strict mode, replacing var with let and const, using proper comparison operators, and adding missing semicolons. Learn to use ESLint for error detection and ensure your code runs efficiently and correctly.

We'll cover the following...

Solution

The code given below passes all the tests, giving us the desired output.

Javascript (babel-node)
'use strict';
const isPrime = function(n) {
for(let i = 2; i <= Math.sqrt(n); i++) {//or < n instead of <= Math.sqrt(n)
if(n % i === 0) return false;
}
return n > 1;
};
const sumOfPrimes = function(n) {
let sum = 0;
for(let i = 1; i <= n; i++) {
if(isPrime(i)) sum += i;
}
return sum;
};
console.log(sumOfPrimes(10));

Explanation

In the previous lesson, you were required to fix all the errors in the given exercise. The code would not terminate until you fixed the errors.

Using ESLint on code returns, you can see the list of errors in the output of ...