[Solved] Sum First Last - JavaScript Task

  

3
Topic starter

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.

1 Answer
2

My solution 1:

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

My solution 2:

function sum(array) {
    return Number(array[0]) + Number(array[array.length - 1]);
}
 
console.log(sum(['15', '55']));
Share: