Internet
Seminar

Spring 2019
course
site

scope in javascript

resources

Zeroth rule: any variable that you access (i.e. try to get its variable) which has not been defined yet causes an error ... which prohibits any other javascript that follows in the same script or file from being run. (To see the error, load the page with Firefox Web Tools or something similar.)

First rule : all js files that are loaded into a webpage are in the same global scope. (Ummm....)

Second rule : any js variable which is not declared with "let" or "var" or "const" is automagically a global. (Ummm....)

Third rule : "var" is the oldest (and somewhat funkiest) of the three type declarations. "var a" has function scope (not block), and may be declared more than once without complaint.

/* This is one of the patterns used to keep the variable "foo" local. */
(function(){ 
  var foo = "put something here"; 
  do_something_with(foo);  
})();

Fourth rule: "let" and "const" are newer, and both block scoped (i.e. only kept within { }). Declaring a variable twice with let or const is an error.

Finally, there are "closures". I have one in this example ... but it's tricky enough that I will explain in person. :)


aside

Wat

Wat's going on? Hmmm ... maybe this blurb on basic types and operations can shed some light.

>>> '37' - 7
30
>>> '37' + 7
'377'

... or maybe not.

https://cs.marlboro.college /cours /spring2019 /internet /www /jim /scope /home
last modified Wed July 3 2024 7:23 am