Finding errors in code with functions in JavaScript
In the following tasks, some programmer has written code and may have made mistakes in it. You should check if the code does what is described. If the code does not work correctly, you need to fix the errors.
The code should find the sum of the results of two functions work:
javascriptfunction func1() {
console.log(3);
}
function func2() {
console.log(5);
}
console.log( func1() + func2() );
The code should find the sum of the array elements:
javascriptfunction sum(arr) {
let res = 0;
for (let elem of arr) {
res += elem;
return res;
}
}
console.log(sum([1, 2, 3, 4, 5]));
The code should find the sum of the array elements, however, it does not print anything to the console:
javascriptlet arr = [1, 2, 3, 4, 5];
function func(arr) {
let res = 0;
for (let elem of arr) {
res += elem;
}
console.log(res);
}
The code should find the sum of the results of two functions work:
javascriptfunction func1() {
return 3;
}
function func2() {
return 5;
}
console.log( func1 + func2 );
The code should find the sum of the array elements:
javascriptlet sum = sum([1, 2, 3, 4, 5]);
console.log(sum);
function sum(arr) {
let sum = 0;
for (let elem of arr) {
sum += elem;
}
return elem;
}
The code should find the sum of the array elements:
javascriptlet res = sum([1, 2, 3, 4, 5]);
console.log(res);
function sum(arr) {
let sum = 0;
for (let elem of arr) {
sum += elem;
}
}
The function append zero to the
number from 1 to 9,
and returns the numbers greater
than 9 without change:
javascriptfunction add(num) {
if (num <= 9) {
return '0' + num;
}
}
The code should find the sum of the array elements:
javascriptlet arr = [1, 2, 3, 4, 5];
let sum = sum(arr);
console.log(sum);
function sum(arr) {
let res = 0;
for (let elem of arr) {
res += elem;
}
return res;
}
The code should find the sum of the digits of a number:
javascriptlet num = 12345;
let res = getDigitsSum(num);
console.log(res);
function getDigitsSum(num) {
let arr = num.split('');
let sum = 0;
for (let elem of arr) {
sum += elem;
}
return sum;
}
The code should check if the number is prime:
javascriptconsole.log(isPrime(13)); // should output true
function isPrime(num) {
for (let i = 2; i < num; i++) {
if (num % i !== 0) {
return true;
} else {
return false;
}
}
}