JavaScript uses a concept of Execution Contexts which correspond to variable scope
3 Types of Execution Contexts:
- Global Context - code in the script that is not contained in a function
- Function Context - code contained in a function (one context per function)
- Eval Context
2 Types of Variable Scope:
- Global Scope - variables declared outside of functions and code blocks
- Function Level Scope - variables declared in functions
JavaScript can only process one function at a time (single thread). To keep track of what needs to be executed, it stacks execution contexts in what is refered to as the Stack. Each time a new item is added, a new execution context is created.
Execution Context Phases:
- Prepare - new scope, variables, functions, and arguements are created (this is referenced as hoisting)
- Execute - assign values, reference and run functions, and execute statements
- JavaScript functions are lexical, which means a function has access to variables in its scope as well as variables in the scope of its parent.
- if it can't find a variable called in the immediate scope it continues looking in the next parent level all the way up to the global scope to find it.
- this is a one way street, parents don't have access to variables in childer
- JavaScript functions are lexical, which means a function has access to variables in its scope as well as variables in the scope of its parent.
Error Objects (7 types) will help you find where your mistakes are by using browser tools to read them
- Error - generic
- SyntaxError - snytax not followed
- ReferenceError - referenced variable not in scope
- TypeError - unexpected data type
- RangeError - number not in acceptable range
- URIError - used incorrectly
- EvalError - used incorrectly
Read and write (log) to the console to understand what is going on with your code.
- console.info, console.warn and consoel.error can be used to write different messages to the console
- console.group will group information written to the console
- console.table can be used on an object to output data in a table format
- console.assert uses a condition to display a message if false
Use the Source tab and breakpoints to stop code at any point
- hover over variables to see their value at that moment in time
- step through and increment the code to find the failure
debugger;keyword can be used in JavaScript to enter a breakpoint from the code
Final Tips:
- Try, Catch, and Finally can be used to handle exceptions if the code is prone to failing
- this gives users helpful feedback
- use
throw new Error('message');to generate your own more descriptive error message