56
Illustrating Lexical Scope in JavaScript
// outer/global scope: RED
var students = [
{ id: 14, name: "Kyle" },
{ id: 73, name: "Suzy" },
{ id: 112, name: "Frank" },
{ id: 6, name: "Sarah" },
];
function getStudentName(studentID) {
// function scope: BLUE
for (let student of students) {
// loop scope: GREEN
if (student.id == studentID) {
return student.name;
}
}
}
var nextStudent = getStudentName(73);
console.log(nextStudent); // Suzy

students
, getStudentName
and nextStudent
.getStudentName(..)
, holds one identifier: studentID
.student
.NOTE: Scope bubbles are determined during compilation. Each marble is colored based on which bucket it's declared in, not the color of the scope it may be accessed from.
getStudentName(..)
is nested inside the global scope. The block scope of the for
loop is similarly nested inside that function scope.ReferenceError
being thrown. ReferenceError
.undefined
value.typeof
operator returns the string "undefined" for variable references in either state:
var studentName;
typeof studentName; // "undefined"
typeof doesntExist; // "undefined"
function getStudentName() {
// assignment to an undeclared variable :(
nextStudent = "Suzy";
}
getStudentName();
console.log(nextStudent);
// "Suzy" -- oops, an accidental-global variable!
ReferenceError
.That concludes this chapter. I'll be back with the notes for the next chapter soon.
Till then, Happy Coding :)
If you enjoyed reading the notes or have any suggestions or doubts, then feel free to share your views in the comments.
In case you want to connect with me, follow the links below:
In case you want to connect with me, follow the links below:
56