Skip to content

3. Research

Sjors Wijsman edited this page May 23, 2020 · 18 revisions

This page contains...

JavaScript Research

Frontend Development Week 1

Scope

The scope dictates whether or not variables are accessible.

In JavaScript there's a global and a local scope. Generally, local scopes can only access variables from the global or its own local scope. It's like a supermarket; you can only take groceries from the shelves (global scope) or your own cart (local scope) and taking from other carts isn't allowed. Every function in JavaScript creates its own local scope. This means that variables created inside a function will only be accessible inside this function. An example:

var globalScope = "global";
function example() {
  var localScope = "local";
  console.log(globalScope, localScope)
}
example()
console.log(globalScope, localScope)

Will first log global local and then throw a Uncaught ReferenceError on line 6: localScope is not defined because the localScope variable declared inside the function is inaccessible from the global scope where the console.log() function is called.

Sources

JavaScript Scope. (n.d.). Retrieved May 11, 2020, from https://www.w3schools.com/js/js_scope.asp

Context

The context refers to the current value of the this keyword.

The this keyword contains the object that holds the code that's currently executing.

Sources

Gupta, D. (2019, January 6). Understanding Javascript ‘this’ keyword (Context). Retrieved May 11, 2020, from https://towardsdatascience.com/javascript-context-this-keyword-9a78a19d5786

Closures

Closures control what's inside and what's outside of a scope.

When a JavaScript function is created, the closures describe the bounds of the of the newly created function. By using these closures you can "hide" variables from the outside scope. This can thus be used for data privacy and other implementations.

Sources

Elliott, E. (2019, December 19). Master the JavaScript Interview: What is a Closure? Retrieved May 11, 2020, from https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36

Hoisting

Hoisting is JavaScript's behaviour of finding every declaration and storing them into memory before execution.

Because of JavaScript's Hoisting behaviour you can, for example, use a function before its declaration. Like so:

example("Slim Shady");

function example(name) {
  console.log("Hi! My name is...");
}

Possibly against your expectations, this will execute properly and output Hi! My name is...Slim Shady. JavaScript hoists the function declaration and stores this before moving on to the function call on the first line.

Sources

Hoisting. (2020, March 27). Retrieved May 11, 2020, from https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

Clone this wiki locally