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?
2 Answers 2
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.
3 Comments
arr = arr.forEach return undefined that's why OP function return undefinedThe 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;
});
}
1 Comment
.map for me and for the explanation. I didn't know that.
itemhold the value ofarr[i], so you cannot change the original value like this.itemwitharr[i]must work?arr = arr.forEachandforEachreturn nothing, you have to remove the assignmentarr =