Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why don't we pass the object property as an argument to the function?

Hi,

I learned programming mainly with Python, and I struggle a bit to understand the difference of scoping in JS. Indeed, do all functions in JS can search for global variable to work with even when they're not passed as arguments?

For example, I don't understand why the example of Adrew works when we don't write it like this:

var dice = {
  sides: 6,
  roll : function (this.sides) {
    var randomNumber = Math.floor(Math.random() + this.sides) + 1;
    console.log(randomNumber);
  }
}

Thanks in advance for answers ;)

can you post Andrew's code for comparison?

Hi Karolin,

Andrew's code is this one :

var dice = {
  sides: 6,
  roll : function () {
    var randomNumber = Math.floor(Math.random() + this.sides) + 1;
    console.log(randomNumber);
  }
}

1 Answer

Indeed, do all functions in JS can search for global variable to work with even when they're not passed as arguments?

Short answer: Yes. Local scopes are only created inside functions in JS. If a variable is not defined inside a function, js will keep looking 'outwards' to find a definition, and the first one it finds, it will use it.

http://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

Comparing and contrasting Python and JS: https://blog.glyphobet.net/essay/2557

Block level scoping was just introduced in ECMAScript6, but there is extremely limited support for it at this time. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Thank you a lot for the answer Karolin! These links are awesome, especially the one comparing Python and JS, it will prove helpfull for me.