3

Im brand new to javascript. I simply have an exercise where i need the array numbers to add each index to the next one.

The result should be:

var result = [4,8,15,21,11];

I tried something like this. It works on the first 4 indexes, however gives NaN on last since it doesnt have a next number to add to.

var numbers = [1, 3, 5, 10, 11];

var result = numbers.map((x, index) => x + numbers[index + 1])

console.log(result)

Is there any smarter way to do this and how do i get index 4 to stay as 11? And please explain as im trying to learn.

1 Answer 1

4

That's a perfectly valid way to do it. You can handle the last index by taking advantage of the fact that numbers[index] will be undefined (not an error) if index is beyond the end of the array, and undefined is a falsy value, so you can use || 0 to use 0 instead of undefined if it's there:

var result = numbers.map((x, index) =>  x + (numbers[index+1] || 0));

Live Example:

var numbers = [1, 3, 5, 10, 11];

var result = numbers.map((x, index) => x + (numbers[index + 1] || 0));

console.log(result);

|| is the logical OR operator, but it's a bit special in JavaScript: It evaluates its left-hand operand and, if that value is truthy¹, takes that value as its result; if the left-hand is falsy, the operator evalutes the right-hand operand and takes that value as its result.

In ES2020+ you can use the new nullish coalescing operator (??) instead of ||:

var result = numbers.map((x, index) =>  x + (numbers[index+1] ?? 0));

That will only use the 0 if numbers[index] is null or undefined, rather than if it's any falsy value.


¹ "truthy" and "falsy" - A truthy value is a value that evaluates to true when used as a condition (for instance, if (x) or x || y); a falsy value is a value that evalutes to false. The falsy values are 0, "", NaN, null, undefined, and of course, false. All other values are truthy. (Except there's a special case on browsers: document.all is falsy for legacy reasons.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.