JavaScript: Things To Watch Out For

JavaScript: Things To Watch Out For

Today’s post isn’t about new techniques. Today we cover some things to be wary of in JavaScript. These include Function Hoisting, pass by value, scoping rules, and this.


Function Hoisting

Function hosting can be a problem. When you create a function without passing it to a variable, JavaScript pushes the function to the top of your file. Here’s an example:

This kind of behavior can be a cause for error if you don’t understand it, because functions may be available when you don’t expect them to be. If you don’t want this effect, assign your functions to variables. Now since we’re on functions, let’s discussing scoping rules:


Scoping Rules

There three ways to declare a variable in JavaScript; you can use let, const, or var. Both let and const are block scoped; var is function scoped. This is an important distinction to make. Now, here’s an example illustrating that property:

As you can see var drips out of the block scope and is available throughout the entire function; const and let do not. Furthermore, they also throw errors if used incorrectly. In most cases, let and const are preferred over var; const and let can accomplish more consistent rules when compared to var. Well, since we’re on variables, let’s discuss pass by value & cloning.


Pass By Value

JavaScript is a pass by value language; if you pass 2 to a variable and change it to 1, then the variable’s value is 1. Well, objects and arrays are not so simple. Arrays and objects can be passed to new variables as new arrays or objects, but still, change the properties on the original. Here’s an example:

Now, for me, this behavior can be confusing. See, many times JavaScript makes a shallow copy of the original array or object. This means the array of objects or list of arrays within your array refers to the same object in memory. If you’re not careful, this can trip you up as a developer.

This is why you should value immutability, or when passing around objects, clone them (similar to the solution). Now, in JavaScript clone and copy are different; the clone does not reference the same object in memory — copy does.

These are just some of the things to watch out for in JavaScript; be careful on your JavaScript coding journey. ~

Leave a Reply

Your email address will not be published.