0

This is my first question on Stackoverflow :)

Below, I have set up two functions and I'm trying to use them to mutate the array "nums". But it doesn't seem to work. What am I doing wrong, especially in the last part after the function definitions? I am using higher order functions to learn how they work.

function forEach(array, callback) {
    for(let i=0; i<array.length; i++) {
    callback(array[i]);
  }
}

function mapWith(array, callback) {
    forEach(array, callback);
}

let nums = [1, 2, 3];
mapWith(nums, item => item+=2);
console.log(nums); //console output: [1, 2, 3]

But changing the last part the following way, does show that the array is changing the way I wanted. But why can't I manipulate it directly?

let nums = [];
mapWith([1, 2, 3], item => nums.push(item+=2));
console.log(nums); //console output: [3, 4, 5]

3 Answers 3

2

The problem here seems to be that you are not saving your returned callback value for each array element. You just need to modify your forEach() function like this

function forEach(array, callback) {
    for(let i=0; i<array.length; i++) {
        array[i] = callback(array[i]);
  }
}
Side note

Your mapWith function is doing nothing but calling your forEach function. You could just use forEach

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

1 Comment

You're totally right. Now I can see why it wasn't working. :) To the side note: It was part of the exercise for using higher order functions, but I understand what you're saying.
0

It works correctly, when you call callback(array[i]); it passes value to callback function not reference, if you will pass for example an object to callback it will be passed as refernce.

An example:

const obj = {val: 1};
const modify = (obj) => {
   obj.val += 1;
}

modify(obj);
console.log(obj);

Comments

0

This is what you are basically doing:

function callbackFunction (item) {
  return item + 2;
}
let test = 5;
const newNumber = callbackFunction(test);
console.log(test);
console.log(newNumber);

You don't mutate the variable test, but just return new variable. That's why you are getting the same numbers.

Also, notice you wrote this mapWith(nums, item => item=+2); instead of item += 2.

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.