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
Roland O'Donnell
5,667 Pointsare variables and objects accessible in all javascripts files in the same project?
im not grasping how two javascript files are linked? example:
script1.js ----
var students = [ { name: 'Dave', track: 'Front End Development', achievements: 158, points: 14730 } ];
scripts2.js--------
var message = ''; var student; for (var i = 0; i < students.length; i += 1) { student = students[i]; message += '<h2>Student: ' + student.name + '</h2>'; message += '<p>Track: ' + student.track + '</p>'; message += '<p>Points: ' + student.points + '</p>'; message += '<p>Achievements: ' + student.achievements + '</p>';
QUESTION: how does scripts2.js even know the variable students exist as an array of objects in a seperate file? sure they are both linked to the html file but not to each other?
i just can't under why i can create
var test = 0;
in scripts1.js
then change the value
test = 1;
in scripts2.js
its great to be able to, but i just want to know how and why!
thanks
1 Answer
Wolfgang Warneke
10,845 PointsA good way to think about it is to consider where the JavaScript is actually happening. Those files aren't executing themselves; they get interpreted in the browser. According to this HTML5 Rocks! article when given
<script src="first.js">
</script src="second.js">
the browser will download them both at the same time, and then execute them in order. I would definitely recommend looking into the Document Object Model, how the browser renders the HTML document. I believe Treehouse has a new course 'JavaScript and the DOM' coming soon. You could look at this chapter from Eloquent JavaScript for some perspective on this. I like where he's talking about the browser's JavaScript environment being like a sandbox, but with a steel cage...
A super useful part about how the browser can read from many files is that it allows for script libraries to be included, like jQuery. Hope this helps