borgmater
borgmater

Reputation: 696

Uncaught TypeError: arr.forEach is not a function

I'm a JS beginner, and stumbled upon a problem I cannot figure out. The title error comes up after I run this simple sum function in Sublime:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>JS Exercise</title>
    <script src="JSexercise.js"></script>
</head>
<body>
    <h1>JS Exercise</h1>
</body>
</html>

JS

function sumArray(arr){
    var sum = 0;
    arr.forEach(function(element){
        sum+=element;
    });
    return sum;
}

var input = prompt("Give array");
console.log(sumArray(input));

Error

Uncaught TypeError: arr.forEach is not a function at sumArray (JSexercise.js:3) at JSexercise.js:10

Upvotes: 0

Views: 1670

Answers (2)

Jonathan Dion
Jonathan Dion

Reputation: 1671

the forFeach API needs an array. input is a string not an array.

function sumArray(arr){
    var sum = 0;
    arr.forEach(function(element){
        sum+=element;
    });
    return sum;
}

var responses = [];
var input = prompt("Give array");
responses.push(input)
console.log(sumArray(responses));

Upvotes: 0

SKSpall
SKSpall

Reputation: 192

input variable will take a string. split() is used to convert a string to an array. So first split the string based on the delimiter you pass in prompt which will output an array. Then pass this array to function sumArray.

var input= "1 2 3 4 5"; // Enter 1 2 3 4 5 in prompt box
// Split the string by whitespaces - arr will now contain [1,2,3,4,5]
var arr = input.split(" ");
console.log(sumArray(arr));

Upvotes: 2

Related Questions