Notes

All About Scope in Javscript

The scope of a program in JS is the set of variables that are available for use within the program.

Advantages of utilizing scope

Different Kinds of 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"

Lexical Scope


Different Variables in Javascript

The different ways to declare variables

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

Function Scope vs Block Scope

Global Variables


Closures

Calculating Closures

Closures and Scope Basic Closure Rules:

Applications of Closures


Context in Javascript

What about this ?

Issues with Scope and Context

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'}

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


Arrow Functions aka Fat Arrows

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