If you have not kept up with the many changes that JavaScript has gone through during the past few years, then maybe now is the time to incorporate them into your code. ES6 has been out for a while now, so a few of the following concepts are hopefully already being implemented by many of you. The following concepts are designed to make your code more flexible and scalable. Essentially, to ensure that your code can withstand the test of time just a little bit more.
Default Function Parameters
Default parameters allow our function parameters to include with them default values, in case they are not provided during function calls. Take the following for example.
function sum(a, b)
{
return a + b;
}
sum(3, 4);
sum(3);
The first function call would return '7' as expected. But the second call would return a confusing Nan (Not a number). Which makes sense from a logical perspective, as we left that value to its own devices, which in JavaScript means 'undefined'. However, this isn't as scalable as we could make it. Ideally, we would want to plug all the potential holes that can cause a leak in our code. Because the sum of 3 is 3. So this is a great place to implement default parameters.
function sum(a = 0, b = 0)
{
return a + b;
}
sum(3, 4);
sum(3);
Now calling the sum function with any parameter missing, will still result in a numeric value. The sum of 3, is once again 3.
Var vs Let vs Const
I'll say this now. More than likely, most of the internet is built upon the 'var' declaration and for one simple reason. Because it has been around longer. Similar to how most cars on the road are not electric right now. The number is growing. But gas engines have been in use for decades longer and they last. Mainly because they get you from point a to point b for a very long time and only start to show their age after alot of use.
What's wrong with var?
The short answer is nothing. Var does what var does, and does it well. It declares a variable. The world doesn't end when you use var. But. Because there is always a but. With the introduction of let and const in ES6, we now have more options. And more options are always good.
Using let
let is a block-level declaration, which means that any variable declared with a let, can only live within its current block-scope, or any subsequent child scopes.
function sumlist(nums)
{
for(var i = 0; i < nums.length; i++)
{
var tmp = i;
}
console.log(i); // still exists
}
One of the main uses of let is in for loops. We create variables to keep track of the incrementor in for loops. Normally, with the traditional 'var' route, this would leave our i variable in the scope after the for loop has completed. And equally, any other variables declared inside of the for loop would also remain in the scope. let solves that issue for us.
function sumlist(nums)
{
for(let i = 0; i < nums.length; i++)
{
let tmp = i;
}
console.log(tmp); // error
console.log(i); // error
}
And thus, we have a cleaner namespace, better memory management, and less chance of conflicts moving forward.
const
Constant variables are common in many programming languages. And they are exactly as their name implies. They are constant and do not change. If we attempt to change them, they will produce an error message.
const name = 'Walt';
name = 'Bob'; // error
If you know for a fact that a variable should not change, then you should make it into a const. Some people prefer to make everything into a const, unless otherwise specified. However, I find that to be too restrictive, as many times I am uncertain of the rate of change of variables until I have had some time to work on it.
But certain things that are for certain constant, should be marked as such. Such as numeric constants like Pi (3.14...) or other things of that nature.
String Templates
String templates are one of my favorite features in the current JavaScript specification. Normally, in order to concatenate strings and values in JavaScript you would append them using the '+' operator as follows:
var name = 'Walt';
var greeting = 'Hello ' + name;
While perfectly fine, the biggest challenge that can arise is when appending many variables to the string. The problem can get more frustrating if the string includes things such as the single quote (') character. In which case, you'll have to escape it, or to alternate between the (") character. And eventually, you might get lost in a sea of plus signs and single and double quotes.
String templates help to resolve that issue by not having us escape out of our strings. We continue to type, while using a special template syntax in order to inject our values into our string.
var name = 'Walt';
var greeting = `Hello ${name}`;
Note that the string is wrapped in the caret character (`), not the single quote. That would the top left most character on most keyboards. And any values that you wish to append you do so with the ${variable/function/operation} declaration.
Any JavaScript expression can go inside of the curly braces.
Arrow Functions
Arrow functions accomplish 2 things. For one, they allow us to write functions in a short-hand fashion which can overall cut down on file sizes and keystrokes. And secondly, they allow for implicit returns. Which can be both good and bad, as someone who is unaware of that feature would find it confusing. A big use for the arrow syntax is in replacing anonymous functions that we typically use with callback functions. For example:
var list = [1, 3, 4];
list.forEach(function(item){
console.log(item);
});
That's a relatively straightforward example, but still notice that there is a fair amount of boilerplate required in order to accomplish something trivial. Arrow functions, make this process a bit more concise for us.
var list = [1, 3, 4];
list.forEach(item => console.log(item));
Overall, much cleaner and much less typing, which means less chances for errors and bugs in the future. And in the larger scheme of things, this could easily take a file that's thousands of lines long down by a few hundreds lines.
Spread Operator
The spread operator is new to me, however, it's an interesting one and deserves some further looking at. It is essentially a way of dynamically inserting parameters into a function, without having to declare the function parameters one by one. Take the following for example, without using the spread operator. The first function allows us to add together 3 different numbers. While the second function allows us to enter an array of numbers and we can then reduce that into a sum.
function sum(a, b, c)
{
return a + b + c;
}
function sum2(list)
{
return list.reduce((acc, value) => { return acc + value });
}
sum(1, 2, 3);
sum2([1, 3, 4]);
We can also accomplish this with the spread operator as follows.
function sum(...args)
{
return list.reduce((acc, value) => { return acc + value });
}
sum(1, 3, 4, 5, 6, 7);
Similar to our array example from above, but more intuitive. The ...args parameter will deconstruct whatever it is that you include as an argument and bundle it into a single collection. Useful? Potentially.
These were just a few of the newer updates to the JavaScript language that I found to be beneficial in writing shorter and more scalable code. Hopefully you begin to use some of these, if not all, into your day to day coding. And stay tuned for part 2 where I'll dive deep into another set of components that you probably have not heard about.
Happy coding!.