I have problem with arrow functions in javascript. When I try
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [1, 2, 3, 4];
function myFunction() {
const result =
numbers.reduce(
(total, sum) => total + sum
);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
it works ok. But when I try
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<script>
var numbers = [1, 2, 3, 4];
function myFunction() {
const result = numbers =>
numbers.reduce(
(total, sum) => total + sum
);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
the result value is a string rather than a number. I tried different insertion options for parentheses, but it does not work for me. Where I am doing mistake?
numbers =>?resultas a function, but then you didn't call the function usingresult(numbers).