Getting On Board with Let, Const, & Arrow Functions

Setting off on your journey, into the land of a beginner JavaScript programmer, you were probably taught right off the bat to use some older conventions which aren’t standard practice anymore.

It has been quite a while since the release of ES6 in 2015 and these not-so-new features have become standard practice. Even though you began learning without these features, you will need to familiarize yourself with them to become a well-rounded developer.

Over the course of my own learning trek, having to make this switch myself, I noticed a lot of fellow students struggling to understand how best to adopt these new and better habits. My goal is to help the reader better understand why it’s worth making the switch and providing some (hopefully) helpful tips on making the change.

Bad Habit: Using var to declare every single variable.

Why Should We Use Let & Const?

Redeclaration

One of the big reasons that let and const were created is that variables declared with var can then be redeclared. This can create a big problem.

Let’s say you declare a variable early on in your code. Declaring it with var, there is a possibility you could forget that you had already declared the variable. You’d end up declaring it again to represent something else entirely, unintentionally changing the value set when you created it the first time.

var data = 1;
var data = 5;

The above JavaScript code does not generate an error. If we need to store a brand-new value, representing a new idea, we shouldn’t be able to reuse a variable name.

let data = 1;
let data = 5;

With let and const, redeclaration is not allowed. This code would throw SyntaxError: Identified ‘data’ has already been declared.

This may not seem like a glaring issue when working with small bits of code, but when you end up working with large codebases (and alongside other programmers who are working on that same code) this can become a real pain point.

Function-Scoped vs. Block-Scoped

In addition to the problem with redeclaration, var is function scoped, but not block-scoped like let and const. Take a look at the following code:

// Using varvar i = 30;for (var i = 1; i <= 5; i++) {
console.log(i); // logs 1 through 5
}
console.log(i); // logs 6

In this example, you can see that even though the variable i was initially set to 30, the code in the loop resets this value to start at 1, loops through, and eventually results in i being set to 6. This is extremely problematic. While being scoped in functions, var is not scoped for just any block of code.

// Using let

let i = 30;
for (let i = 1; i <=5; i++) {
console.log(i); // logs 1 through 5
}
console.log(i); // logs 30

In the above example, you can see that the looped i variable declared with let did not affect the originally defined i from line 3. This makes much more sense than the above example with var and behaves as one would hope. This behavior is due to let being block-scoped. The variablei inside of the loop does not access the variable i defined in the global scope (line 3).

When to Opt for Const

Between let and const, you could technically always use let (like we always used var) but const is a great choice for when you have something to represent that will never change, a constant value. For that reason, some programmers opt to use const any time you have a variable that will not need to be redeclared.

One common example is pi. Pi will always be approximately 3.14159265. If you are doing operations using pi, you don’t want to accidentally change the value. With const, you couldn’t accidentally do this, even if you tried.

const pi = 3.14159265;
pi = 5.43;
// throws TypeError: Assignment to constant variable.

Another place you might see const being used a lot is when declaring functions, arrays, and objects (complex data types). While the values inside these data types can be changed through their respective methods (because these values are stored by reference and not by value), the pointer (variable name) should never be changed.

For more on values passed by value versus by reference see: https://codeburst.io/javascript-passing-by-value-vs-reference-explained-in-plain-english-8d00fd06a47c

Bad Habit: Declaring every function with the function keyword.

Why Should We Bother with Arrow Functions?

Arrow functions are very widely used, and you need to at least be able to understand the syntax since are bound to see them all over the place. When using higher-order functions, or any type of anonymous function, using arrow functions will help you greatly. In general, they are more concise and make code a lot more readable.

At this point, as not to take up the rest of your day, I highly suggest this read from freeCodeCamp if you’d like to learn more on this topic: https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/

Moving along. I’d like to demonstrate my technique for making the switch to using these ES6 features.

Breaking Your Habits

Weaning yourself off of always declaring with a function keyword and using var, as opposed to let and const, might be seen as a challenge to your existing coding abilities. Rather than jumping straight into it and having another aspect of your code to thoroughly debug, I propose a stepped approach.

Start small. If you don’t feel comfortable changing everything at once, take a little step first. When you feel comfortable with that change, make another. You can even write your code first in the way you are most familiar with, and then, once ensuring the code is working as expected, throw a wrench in and try to refactor using these newer conventions. This way, if something breaks, you know exactly where you went wrong and have far fewer problems to debug.

Here are some examples of small steps you could take to implement using arrow functions.

Step 1: Write your function as usual. Ensure it works.

const add = function(num1, num2) {
return num1 + num2;
}

Step 2: Get rid of the function keyword. Add the function arrow instead.

const add = (num1, num2) => {
return num1 + num2;
}

Step 3: Make the return implicit. Get rid of those curly braces and the return keyword. Note: You should only do this for simple one-line return statements. Anything more complex and you’ll want to leave the return keyword and those braces intact.

const add = (num1, num2) => num1 + num2;

Step 4: If there is only one parameter, you can get rid of the parens around it. If there are no given parameters you’ll need a pair of empty parens.

var squared = (num) => num * num;
var sqare = num => num * num;

Either of the above functions would work the same, although, you would just want to use one or the other, not both.

I hope this is helpful for someone out there. Please let me know if you have any interesting methods of implementing these ES6 features for yourself!

--

--

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
Persis Randolph

Persis Randolph

DevOps Developer based out of New Orleans, LA