2

While attempt to read "secrets of the javascript Ninja"(ok, so perhaps I am not qualify to read this book just yet) but I see below code and I understand what code is doing but part I really don't understand is where function(index) is being called. Is index arbitrary terms or some sort of javascript to indicate generic index?

<script type="text/javascript">
  function forEach(list,callback) {
    for (var n = 0; n < list.length; n++) {
      callback.call(list[n],n);
    }
}
  var weapons = ['shuriken','katana','nunchucks'];
  forEach(
    weapons,
    function(index){
        function

         assert(this == weapons [index],
             "Got the expected value of " + weapons [index]);
} );
</script>

2 Answers 2

2

It is passed as the second argument to forEach.

forEach(list,callback)

… to a variable called callback.

So it is called here:

callback.call(list[n],n);

via the call method


Is index arbitrary terms or some sort of javascript to indicate generic index?

It's an argument name. You defined the name yourself. The value it gets passed is determined when you call the function.

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

Comments

1

index it's an alias for the variable that will be available inside the execution context of the callback, hence available to the caller, the name could be whatever.

this is an example of a function used as a first class function (a crucial concept in javascript), that is pass them around as objects to define custom behaviour.

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.