softshipper
softshipper

Reputation: 34071

javascript does not scope function parameter

I wrote an array object and then wonna loop through the array. I am using underscore _.each function for do this work. Suddenly it happens unexpected thing in my code, consider the following code

var _ = require('underscore');

var myArray = [ 'RE', 'FR', 'TZ', 'SD'];

var traverse = function (element, index, list) {

    console.log(para1);
    console.log(element);

}

var func1 = function (para1) {
    _.each(myArray, traverse);
}

func1('test');

as output i have got the error message

Volumes/Develop/node_sample/scope.js:7
    console.log(para1);
                ^
ReferenceError: para1 is not defined
    at traverse (/Volumes/Develop/node_sample/scope.js:7:14)
    at Array.forEach (native)
    at Function._.each._.forEach (/Volumes/Develop/node_sample/node_modules/underscore/underscore.js:79:11)
    at func1 (/Volumes/Develop/node_sample/scope.js:13:4)
    at Object.<anonymous> (/Volumes/Develop/node_sample/scope.js:16:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

Why the traverse function does not recognize para1 variable? I execute the _.each function in func and in my opinion should carry the scope with.
But if i write the code like this, then the scope chain works fine

var _ = require('underscore');

var myArray = [ 'RE', 'FR', 'TZ', 'SD'];

var func1 = function (para1) {
    _.each(myArray, function (element, index, list) {

        console.log(para1);
        console.log(element);

    });
}

func1('test');

Upvotes: 0

Views: 72

Answers (2)

Andy
Andy

Reputation: 63524

You've answered your own question. para1 only exists within the scope of func1. You're not passing it to traverse in any way.

Your second example is fine, or you could do this instead:

var myArray = [ 'RE', 'FR', 'TZ', 'SD'];

var traverse = function (para1, myArray) {
  _.each(myArray, function (element, index, list) {
    console.log(para1);
    console.log(element);
  });
}

var func1 = function (para1) {
  traverse(para1, myArray);
}

func1('test');

Fiddle.

Upvotes: 1

Tobias Oberrauch
Tobias Oberrauch

Reputation: 226

Your variable is not in the scope chain: Scope Chain in Javascript

In the second example javascript is searching for 'para1' in the each method, but there is no definition. After then the same search procedure will started with the parent function (close to func1) and at this there is a variable / argument called para1

I think you can pass para1 into the .each method with help of context: each.each(list, iterator, [context]) I'm a jQuery guy so you have to check the docs on your own: http://underscorejs.org/#each

I hope it helps you

Cheers

Upvotes: 0

Related Questions