55
loading...
This website collects cookies to deliver better user experience
// 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
.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
.