Code 201 Class 10 Reading Notes
The Stack
The JavaScript interpreter processes one line of code at a time. When a sstatement needs data from another function, it stacks (or piles) the new function on top of the current task.
function greatUser() {
return 'Hello ' + getName();
}
function getName() {
var name = 'Molly';
return name;
}
var greeting = greetUser();
alert(greeting);
1) The value for the greeting variable is obtained by calling the greetUser() function. So the variable cannot be assigned until the greetUser() function has done its job.
2) The statement is effectively put on hold, and the greetUser() task gets stacked on top of it. In turn, the greetUser() function cannot return a value until the getName() function has completed its task.
3) So, getName() is stacked on top of the greetUser() function. You can see the stack starting to build up. When getName() has done its job, a value is returned back to the greetUser() function.
4) Since getName() has done its job, it is removed from the stack. In turn, the greetUser() function can now finish its job and return a value to the greeting variable.
5) The greetUser() function has finished its work and it is removed from the stack and the value is finally assigned to the greeting variable.
-
If you understand execution contexts (which have two stages) and stacks, you are more likely to find the error in you code.
-
Debuggin is the process of finding errors. It involves a process of deduction.
-
The console helps narrow down the area in which the error is located, so you can try to find the exact error.
-
JavaScript has 7 different types of errors. Each creates its own error object, which can tell you tis line number and gives a description of the error.
-
If you know that you may get an error, you can handle it gracefully using the try, catch, finally statements. Use them to give your users helpful feedback.