chuzymatics chuzymatics - 3 months ago 9
Javascript Question

How to call JS .apply() method

Despite all books and blogs I've consulted on this , I have not fully understood how to call js .apply() which is famed to be so important in changing function context. Sometimes I get it right, sometimes I don't,sign all is not well yet.

function sumArr(arr){
var sum =0;
for(var i =0; i<arr.length; i++){
sum+= arr[i];
}
return sum
}
var x = [3, 6, 8];
var obj ={
name: 'somebody',
scores:[3, 6, 8]
}
// console.log(sumArr(x)) outputs 17, fine!
// Now sumArr.apply(null, x) outputs 0
// Next, sumArr.apply(obj, obj.scores) outputs 0
please could somebody tell me how to call this method correctly.

Answer

The problem is that .apply() takes elements out of array passed in second parameter and passes them as parameter to the function, so in your examples when .apply(null, [3,6,8]) actually calls the method as in sumArr(3,6,8). So the correct way to pass the parameters would be like sumArr.apply(null, [[3,6,8]]. So your code snippet would look like

function sumArr(arr){
    var sum =0;
    for(var i =0; i<arr.length; i++){
        sum+= arr[i];
    }
    return sum
}
var x = [3, 6, 8];
var obj ={
    name: 'somebody',
    scores:[3, 6, 8]
}
console.log(sumArr(x));
//.apply() takes each array elment and passes it as a parameter
console.log(sumArr.apply(null, [x]));
console.log(sumArr.apply(obj, [obj.scores]));

Hope this helps.