Skip to content

Instantly share code, notes, and snippets.

@nbeers22
Created April 1, 2019 08:36
Show Gist options
  • Save nbeers22/2557a8f9ee978095fbb5fe781112a0ba to your computer and use it in GitHub Desktop.
Save nbeers22/2557a8f9ee978095fbb5fe781112a0ba to your computer and use it in GitHub Desktop.
JavaScript Variable Scope

Questions: What is scope? Your explanation should include the idea of global vs. block scope. Why are global variables avoided? Explain JavaScript's strict mode What are side effects, and what is a pure function?

  1. Scope determines the visibility/accessibility of variables, objects, and funcitons within the code. JavaScript has global scope, function scope, and with the addition of ES6, block scope using let and const. Global variables are available everywhere but are typically viewed as bad practice because they can produce unintended results down the line. They also can be a performance hit, because when JavaScript is compiled it checks for variable values first in the block scope, then the enclosing function scope (if there is one), and then the global scope until it finds what it is looking for. If you had a large application using several global variables, you could see a potential hit to performance.

While var, let, and const are all hoisted, var will be hoisted to the top of the enclosing function, while let/const will only be hoisted to the top of the enclosing block, like an if statement or for loop that may be inside that enclosing function.

  1. Global variables are avoided because they can potentially cause unwanted behavior down the line, especially when you have a project with several javascript files that all get concatenated into one in production. You may be accientally changing the value of a variable on accident that could have been avoided if the variable was declared inside a local scope somewhere.

  2. 'Use strict' is something you can put in your JS file to enforce adherence to strict policies, most notably, not using global variables. Other things that strict mode restricts are: deleting a variable or object, deleting a function, duplicating parameter names, and read-only/get-only properties.

'Use strict' may be declared globally or within a block if you only want strict mode to restrict the code inside a particular block.

  1. A pure function is given the same inputs, it always returns the same output, and it has no side effects. A side effect is a state change that is observable outside the functoin that is different from its return value. Some examples include, writing to global variables, logging to the console, and writing to the screen. In functional programming, it is thought to be best to keep side effects separate from the rest of the logic because it will be much easier to maintain.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment