Getting JavaScript to work
More often than not when code is copied from an example the modification results in the scoping of variables is problematic.
Variable Scope
Most of the errors I encounter when developing in JavaScript is in relation to the scoping of variables. This makes the use of Developer Tools important as you can add console.log(); statements to check if a variable is visable and not undefined.
Types of Scope in JavaScript:
- Global Scope: Variables declared outside any function or block are accessible anywhere in the program.
- Function (Local) Scope: Variables declared inside a function are accessible only within that function.
- Block Scope: Introduced in ES6 with let and const, variables declared inside {} are accessible only within that block.
- Lexical Scope: Inner functions can access variables from their outer functions.
- Module Scope: In ES modules, variables are private to the module unless explicitly exported.
Top