1

This function works properly:

function task02(arr) {
 var out = [];
 arr = arr.forEach(function(item, i){
 (item > 0) ? out.push(1) : out.push(0);
 });
 return out;
}

And this one's not (outputs undefined):

function task02(arr) {
 arr = arr.forEach(function(item, i){
 (item > 0) ? item = 1 : item = 0;
 });
 return arr;
}

I've tried using both item and item[i], but it's not working. Can someone please explain to me, why this is not working?

asked Sep 14, 2015 at 7:54
4
  • item hold the value of arr[i], so you cannot change the original value like this. Commented Sep 14, 2015 at 7:56
  • So, replacing item with arr[i] must work? Commented Sep 14, 2015 at 7:57
  • Nah, it's not working. Commented Sep 14, 2015 at 8:00
  • It's because you do arr = arr.forEach and forEach return nothing, you have to remove the assignment arr = Commented Sep 14, 2015 at 8:02

2 Answers 2

4

Can someone please explain to me, why this is not working?

JavaScript is pass/call/assign by value. That implies that assigning a value to a variable won't magically change the value of another variable (or an array element).

Simpler example:

var foo = 42;
var bar = foo;
foo = 21;

bar will still have the value 42.


In your case, assigning to item won't change the array element.


As always, if you use an unfamiliar method, read its documentation first.

answered Sep 14, 2015 at 7:57
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation.
arr = arr.forEach return undefined that's why OP function return undefined
@Hacketo: Good catch. But even without that it wouldn't have worked.
3

The callback function in your second example doesn't have any side-effects. It just iterates over the array, does the comparison and that's it. This is the main difference between .forEach (which iterates over the array, but returns undefined) and array methods such as .map, .filter, .reduce that iterate, execute the callback on every item and return a modified array.

If you want to avoid a temporary array you should use Array.map in this case:

function task02(arr) {
 return arr.map(function(item, i){
 return (item > 0) ? 1 : 0;
 });
}
answered Sep 14, 2015 at 7:57

1 Comment

Thanks for discovering .map for me and for the explanation. I didn't know that.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.