settingsAccountsettings
Menusettings

Q: Sum First Last - JavaScript Task

+3 votes

Write a JavaScript function that calculates and prints the sum of the first and the last elements in an array.
The input comes as array of string elements holding numbers.

Examples:

Input:
['20', '30', '40']

Output:
60


Input:
['5', '10']

Output:
15

The output is the return value of your function.

asked in JavaScript category by user golearnweb

2 Answers

+3 votes

My solution:

function sumFirstLast(arr) {
    let n1 = Number(arr[0]);
    let n2 = Number(arr[arr.length - 1]);
    console.log(n1 + n2);
}

sumFirstLast(['20', '30', '40']);
answered by user ak47seo
edited by user golearnweb
+2 votes

Here is my JS program:

function sum(array) {
    return Number(array[0]) + Number(array[array.length - 1]);
}

console.log(sum(['15', '55']));
answered by user andrew
edited by user golearnweb
...