The scope
of a program in JS is the set of variables that are available for use within the program.
Advantages of utilizing scope
Security
: Adds security by ensuring variables can only be access by pre-defined parts of our program.Reduced Variable Name Collisions
: Restricts re-using variable names; helps prevent overwriting variable names.Different Kinds of Scope
Global Scope
window
obj in the browser and the global
obj in Node.js.Local Scope
Block Scope
Scope Chaining: Variables and Scope
let name = "Fiona";
// we aren't passing in or defining and variables
function hungryHippo() {
console.log(name + " is hungry!");
}
hungryHippo(); // => "Fiona is hungry"
Scope Chaining
: When a variable is not found within the immediate scope, JS will keep searching outwards until it matches the one we are referencing.Lexical Scope
Lexing Time
: When you run a piece of JS code that is parsed before it is run.
JS language does not have dynamic scope.
The different ways to declare variables
let
: can be re-assigned; block-scoped.const
: no re-assignment; block scoped.var
: May or may not be re-assigned; scoped to a function.Hoisting and Scoping with Variables
Hoisting
is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
Function-Scoped Variables
Hoisting with function-scoped variables
function test() {
// var hoistedVar;
console.log(hoistedVar); // => undefined
var hoistedVar = 10;
}
Block-Scoped Variables
Things that create block-scopes:
Properties of Constants
Hoisting with block-scoped variables
Temporal Dead Zone
: The time before a let or const variable is declared.Function Scope vs Block Scope
Global Variables
global scope
.Calculating Closures
Lexical Environment
: Consists of any variables available within the scope in which a closure was declared (local inner, outer, and global).Closures and Scope Basic Closure Rules:
Applications of Closures
Passing Arguments Implicitly
Scope
: Refers to the visibility and availability of variables.Context
: Refers to the value of the this
keyword when code is executed.What about this
?
This
: Keyword that exists in every function and evaluates to the object that is currently invoking that function.object.method(arg)
. (i.e. array.push, str.toUpperCase()Context
refers to the value of this within a function and this
refers to where a function is invoked.Issues with Scope and Context
this
is called using normal function style invocation, our output will be the contents of the global object.When Methods have an Unexpected Context
let dog = {
name: "Bowser",
changeName: function () {
this.name = "Layla";
},
};
let change = dog.changeName;
console.log(change()); // undefined
console.log(dog); // { name: 'Bowser', changeName: [Function: changeName] }
console.log(this); // Object [global] {etc, etc, etc, name: 'Layla'}
global.setTimeout()
: popular method of setting a function to run on a timer.
Accepts a callback and a number of milliseconds to wait before invoking the callback.
```js
let hello = function () {
console.log("hello!");
};
// global. is a method of the global object!
global.setTimeout(hello, 5000); // waits 5 seconds then prints "hello!"
```
Strictly Protecting the Global Object
We can run JS in strict mode by tagging use strict
at the top of our program.
Changing Context using Bind
“The simplest use of bind()
is to make a function that, no matter how it is called, is called with a particular this value”.
let cat = {
purr: function () {
console.log("meow");
},
purrMore: function () {
this.purr();
},
};
let sayMeow = cat.purrMore;
console.log(sayMeow()); // TypeError
let boundCat = sayMeow.bind(cat);
boundCat(); // prints "meow"
Binding with Arguments
We can also use bind() to bind arguments to a function.
=>
: A more concise way of declaring a function and also considers the behavior of this
and context.Arrow Functions Solving Problems
let average = function (num1, num2) {
let avg = (num1 + num2) / 2;
return avg;
};
let averageArrow = (num1, num2) => {
let avg = (num1 + num2) / 2;
return avg;
};
As you can see the arrow function is shorter and easier to read.
Anatomy of an Arrow Function
Single Expression Arrow Functions
this
lexically.this
inside an arrow function is not dependent on how it is invoked.this
.