In the last article we’ve created a flexible function which returns a value and is safe to use.
You’d be excused to write the above function until, say 2016. But times have changed and so has the syntax – for the better.
We’ll use some great features courtesy of ES6.
First of all “var” is deprecated. Instead we can (and should) use “let” and “const”.
Seems good, but wait a minute! How come am I using “const” for the result when clearly it’s changing? Great question. The reason is that the const keyword relates to reference and not value. What does that mean? Well it means that for every new assignment the reference to the stored value is changed, making it illegal. But it’s perfectly fine if it’s the same array with changing content. The reference stays the same! The same cannot be said for “str”. Its value keeps changing for every iteration.
Pro tip: try to use consts whenever you can to prevent accidental value changes.
Learn more about “let” and “const” here.
Now the function has a more modern syntax internally, but not externally. Let’s create an arrow function instead.
To be honest this is a case in which it really doesn’t matter if you’re using the regular syntax or the arrow version, but I think the more you flex those ES6 muscles – the better. So there.
Let’s explore our next victim: params. You see, “params.length”, “params.fizz” etc. just look awkward. How much nicer it would have been had we used local constants for length etc. Well, we could have just assigned variables this way:
const from= params.from;
const fizz = params.fizz;
However ES6 has a neat feature called “destructuring” which allows us to create variables automatically without declaring them explicitly. And it goes like this:
Amazing! We don’t need to reference “params” anymore, we have our own new variables. Alas these are variables and constants anymore, but the price is well worth the value.
Side note: it is possible to destruct constants, but it cannot be done from the parameter bracket.
But personally in this case I prefer sticking to the more streamlined solution.
Now before you go out and celebrate check what happens if you call the function without any parameter. It crashes. SAD.
We’ve added a default value for param: an empty object literal. This saves the day, but still looks a bit pathetic if we call the function without any parameters. Wouldn’t it be neat if the function would perform the original task instead? Can we do that?
Yes we can.
So now we’re flexible, bulletproof, scalable. Modern even. Happy?
Not the least!
You’ll discover why in the next article.