JavaScript Good to Knows Part II

What’s something that’s been confusing? How would you explain it to someone else?

Something that was confusing for me when I first started with JavaScript, and still is at times, was the concept of “scope” and what is meant by global scope for a variable vs. local scope. After lots of hands-on practice, I now think I have a pretty clear understanding of this very critical difference. For a full explanation, see my discussion below about why leaving the global scope untouched is important.

Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

In order to understand why avoiding altering global scope is a best practice, it’s important to first understand the difference between a global variable and a local variable. A local variable is any variable declared inside of a function, and this variable is said to have local scope, which means that it is stored in memory and accessible to the program only over the scope of that function itself, in other words only accessible to code in the same function code block. A global variable on the other hand, is a variable declared outside of a function. Unlike local variables, global variables are preserved in memory the entire time the program is running and are accessible by all parts of the program. Declaring variables globally, especially if this practice could easily be avoided by local declarations, is a bad practice for several reasons. First, if all variables are defined globally, this is horrible for code maintenance and readability, since it becomes unclear when and where in your code each variable is actually being used or manipulated. Also, since global variables live in memory for the entire time your program is running, this also means worse performance than using local variables which are only stored in memory and accessed in the local scope to which they pertain. In addition, declaring too many variables in global scope can easily lead to what is called “Namespace pollution”. This essentially means that, if I have too many global variables in my program declared, I may inadvertently end up referring to one of those global variables when trying to create a variable with the same name in local scope. For a super basic illustration of what this means, suppose I have a program with several functions that say, involve a user’s age. And so, for convenience and code readability, I want to name the main variable inside of each of those functions age . If I make sure to stay within local scope, then this is perfectly fine, as the identifier age will only be relevant over the scope of each individual function:

However, if I were to have the same code as above but also (inadvertently) declared a variable age in the global scope, then this brings in unnecessary confusion:

Read more about why global variables aren’t a good thing here.

What is “use strict”;? What are the advantages and disadvantages to using it?

Writing “use strict” in your JavaScript code informs the JS engine that the code should be read and executed in “strict mode”. This means that the JS engine will throw errors for several common forms of syntax that without “use strict” are normally what are called “silent errors” — technically errors but not thrown as errors unless using strict mode. Some examples of these types of silent errors that would be throw errors in strict mode include using a previously undeclared variable, using delete to delete a variable. “use-strict” also follows scope: declared at the top of JS code it will invoke strict mode globally, while if declared inside of a function body, it will invoke strict mode only within the local scope of that function. See this explanation from educative.io for more details and code examples. Therefore, one apparent benefit of strict mode is that, as stated concisely by MDN’s definition: strict mode “Fixes mistakes that make it difficult for JavaScript engines to perform optimizations” hence “strict mode code can sometimes be made to run faster than identical code that’s not strict mode.” However, one drawback of strict mode has to do with browser compatibility: for browsers that do not support strict mode, code written with “use-strict” may behave unexpectedly, and should therefore be tested to ensure cross browser compatibility. It also appears to be a relatively common opinion among some developers that another potential drawback of strict mode is that, since it holds syntax rules to higher standards, can have the effect of limiting the full potential and features the JavaScript language has.

What is function hoisting in JavaScript?

Customarily, JavaScript code is understood to be synchronous, in other words it is read and executed one line at a time in the order that it is written. However, the behavior of function “hoisting” might be seen as an exception to this. Hoisting is typically and casually understood to mean that all variable and function declarations are moved (“hoisted”) to the top of the current scope, so that they are accessible everywhere within that scope, even if in the code they are being invoked before being declared. A simple example of function hoisting would be as follows:

However, a very important caveat is that hoisting occurs for functions that are declared with the function keyword, but does NOT occur for functions that are initialized with variables. This means that functions declared using var, let, or const will NOT be hoisted. (This means by implication arrow notation functions, which are declared with one of the former 3 keywords are not hoisted.) Therefore, regardless of whether hoisting is taking place or not, a best practice in any case is to always declare all variables at the top of every scope.

The importance of standards and standards bodies like ECMA.

Imagine you are moving to a new house in your home country only to find that all of a sudden none of the outlets fit any of your electronics. The outlets in one house were designed by one manufacturer with their own rules for voltage and wiring, the outlets in another house by another manufacture with another set of rules. Thank goodness you don’t need to worry about this due to plug and voltage standards.

In the same way, the existence of standards in web development and programming technologies, as well as standard setting bodies like the European Computer Manufacturers Association (ECMA), the Unicode Consortium, and a host of others, are absolutely essential.

Standards are critical for consistency in user experience in that they are the reason why we can expect the same code to behave and display uniformly across multiple web browsers and devices. Without standardization of code and internationally agreed upon specifications, ensuring the same codebase stays compatible across browsers would quickly become a gargantuan if not impossible task, resulting in inconsistent performance and poor user experience.

Standards are also critical form the developer perspective, in that they are what make open-source code and collaboration possible. Moreover, since standardizing bodies take every effort to ensure that newer specifications are backwards compatible with no longer commonly used pieces of code (like CSS float or JS var), standardization is what allows for any developer or team of developers to contribute new code to even a long existing codebase or project, therefore allowing for continued and consistent progress and improvement in technology overtime.

Without standards, building a huge web application with millions of international users like reddit or facebook and maintaining it year after year would be like trying to build a house where each carpenter insisted on her own size of nail and lumber size.

For further reading, see this great post by Travis Horn for an excellent further rundown of how standardization is critical to web development. See also this excellent article by freeCodeCamp about how JavaScript is a result of ECMA script standards.

What actions have you personally taken on recent projects to increase maintainability of your code?

The first and by far most important answer to this question is: COMMENTS, COMMENTS, COMMENTS! Especially on my recent projects that can involve more complex logic, I have found that commenting every step of the way not only helps me keep track of what step I am on in writing my planned code, but it also helps me easily be able to remember where I left off even when I come back to a project after having walked away from it for a while. Ideally, within a function, I try to separate each line of code with a comment in order to be clear about exactly what that step of the function is doing.

Along with comments, I make sure to try and name all of my variables as clearly as possible. Finally, each time I invoke a method that returns something, even though it is not technically necessary I nonetheless store that return value in a new variable with a clear and concise name. Especially for more complex functions that involve invoking several methods on the input prior to output, I find this practice to be a lifesaver in not getting lost in where I am in my code or what it is doing.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Michael Fares

Michael Fares

10 Followers

I am a Frontend Web Developer, Educator, Lifelong autodidact, 3rd Culture Kid, and Citizen of the World.