Scope In JavaScript

  • Videos
  • January 12, 2022
  • 0

Morten Rand, Hendriksen

Topics: JavaScript, VAR

Transcript Summary

VAR is defined as a globally scoped variable in the MDN web docs. This means you must first assign a value to have VAR than assign it a new value inside a function. That new value inside the function takes effect in all associated code, even when function is not taking place. As a result, there may be scope difficulties which lead to unintended behavior mistakes and a great deal of frustration as we try to figure out why things are not operating properly.

A practice demonstration of how this works is to picture two boxes populated using JavaScript. A VAR is created with the name color and than populated it with a color. In this example, the color is purple. This being a CSS color is as to why it works. You can also enter a hex value and it will operate the same way. The query selection is than used to find the corresponding boxes, left and right. We then proceed to use the same color value to populate the style and background properties, as well as the inner HTML. We will be able to see it on the front end. You are also able to change the color variable. JavaScript allows it to do so since it reads from top to bottom.

We will than have two different colors. If we were to uncommand the function, there will be a heading color. The heading color will be adjusted to what we declare it to be. Declaring a color will only apply inside this function. It is because VAR is globally scoped, despite us changing the color of the VAR inside the function, it will apply everywhere. Remember that JavaScript reads from the top down. A matter of scope may occur if we cut and paste a set color in either box resulting in a different color.

Since the beginning, this has been an issue for JavaScript developers. As a result, they would have to declare custom variables inside functions that only exist within those functions and then pass variables in and out to make everything work properly and it has become really cluttered. In conclusion, we will be left with two additional sorts of variables: Let and Scope. They are both locally scoped variables, therefore this issue can be addressed.


Classification of Data Structure