Closed jamiewilson closed 8 years ago
Hello @jamiewilson!
Your issue stems from:
var numberOfLines = contents.toString().split('\n').length - 1
When you use the var
keyword, it creates a new binding available in the immediate execution context.
When you do something like, console.log(foo)
it will look for a foo
variable in its immediate execution context, and then work up each parent execution context in the the scope chain, until at last it reaches the global exectuion context.
This might be of help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
If you remove that the var
from var numberOfLines = contents.toString().split('\n').length - 1
and also remove the numberOfLines
from the line function printResults(numberOfLines) {
, you should observe the desired behavior.
Hope that helps!
:facepalm: Of course! This makes perfect sense now. thanks for that explanation @kid-icarus.
You're welcome @jamiewilson, if you haven't read JavaScript Allongé, it's to read free online and I recommend it.
Here's a little bit on scope/closures:
Hey there.
Here's my question, with more context below
Why is that the
logMyNumber
function in the first example is able to access themyNumber
variable as is, while myprintResults
function needsnumberOfLines
passed as an argument?I read the Art of Node section about callbacks as suggested in this exercise and it helped me come to my solution here. But, it did bring up something that confused me. Here is the Art of Node example of passing in the
logMyNumber
function as the callback foraddOne
:And, similarly I created a function
printResults
to use as my callback, but only returnedundefined
unless I passed in thenumberOfLines
variable, as shown below:Thanks for the help! P.S. Thanks to everyone who's contributed to this project. It's really cool.