Getting Started with ECMAScript 6 Arrow function Parameters

JavaScript

ECMAScript 6 Logo - arrow functions parametersThere is a tremendous amount of flexibility when it comes to parameters in Arrow Functions.

In the previous article: “Getting Started with ECMAScript 6 Arrow functions – Basic Syntax,” we had a very basic overview of ECMAScript 6’s Arrow Functions and their syntax. In this article, I’ll dive a little deeper into the topic of parameter.

In the previous article, we learned how the parameter(s) now come first, and then the “=>” characters, which effectively replace the “function” keyword. This is very efficient and is a key aspect to the simplicity of arrow functions. But it won’t take long before you’ll want to accept multiple parameters in your arrow function. And of course, you may want to accept no parameters.

Example # 1

In Example # 1, the function addTwoNumbers accepts two parameters. This differs from all of the examples in the previous article, each of which dealt with only one parameter. In ECMAScript 6’s arrow function, when you need to accept multiple parameters, you leverage syntax which should be quite familiar to you: enclose the parameters in parentheses.

Arrow Functions that Take No Parameters

In situations in which you’ll want to accept no parameters, the syntax will be empty parentheses.

Example # 2

In Example # 2, we have the function: returnHello. This function takes no parameters and simply returns the string: “hello”. It is certainly not a very useful function, but the main point here is that if you need to create an arrow function that takes no parameters, simply use a set of empty parentheses in place of what would have been a single parameter or parentheses that contained multiple parameters.

The Arguments Object

According to the ECMAScript Language Specification ECMA-262 6th Edition – DRAFT, “Arrow functions never have an arguments objects.” At the time of this writing, version 33.1 of FireFox does allow access to the arguments object inside of an arrow function.

Example # 3

Running Example # 3 in the JavaScript console of FireFox 33.1 demonstrates that the argument object is, in fact, available inside of an arrow function. I’m not sure if this is a mistake or an intentional disregard for the specification. For now, it’s probably best to not attempt access to the arguments object inside of an arrow function.

Summary

In this article we talked about parameters in ECMAScript 6 Arrow Functions. We discussed how to accepts multiple parameters, as well as how to specify none. We also talked a bit about access to the arguments object inside an arrow function. In the next article, I will discuss the value of “this” inside an arrow function.

Validating JavaScript Function Arguments

Functions

JavaScript LogoGracefully handling corner cases is the key to writing more robust, error-free JavaScript.

If you work with JavaScript for a living, you write functions. There is just no way around this. So, if you write functions, then arguments are a part of your life. Now, if you are the only one who uses the JavaScript code you write, then life is pretty grand. But if you are writing code that will be consumed by others, then gracefully handling corner cases and errors becomes important; very important.

So, every time I write a function, I assume that someone else will call it. Even if I know no one will, I assume that someday, someway, someone will. Even if it never happens, I feel its a good habit to get into: write code that fails gracefully.

There are a zillion paths down which this conversation can go, but let’s focus on function arguments. When your function absolutely depends on an argument, and that this argument be of a certain type, and that it not be empty, or otherwise useless, you might have a recipe for disaster, if your hungry little function does not get what it needs.

Example # 1A

Example # 1B

In Example # 1A, we use an IF () block to make sure that the “arg” argument was passed-in before we attempt to do anything with it.

Good enough, right?

Not so fast…

Even though we have taken care to make sure we got the “arg” argument, what if our implementation code is a bit lengthy? Well, in Example # 1B we see how silly it is for all that implementation code to be wrapped in an IF () block. This kind of pattern breeds code that is annoying to maintain.

Example # 2

Ahhhhh, now that’s better!

So, as you can see in Example # 2, we simply say: “hey, if arg does not exist, then return.” This was accomplished using the JavaScript logical NOT operator. So, this means that if the argument “arg” does not exist, the function ends right there and none of the implementation code that follows is ever executed.

But…..

What if we need to be 100% sure that the argument “arg” is what we need it to be? What if it’s not enough to simply know that “arg” exists? What if we need to know that “arg” is an array and it has at least one element?

So many questions, so many darned questions.

Example # 3

Ahhhhh… that’s even better! In Example # 3 we’ve once again used the JavaScript logical NOT operator to say the following: “hey, if the argument someArray was not passed, OR if it is NOT an array, OR if it does NOT have at least one element, return.” This way, we can check for all the details we need in one neat little line and avoid a series of messy nested IF () blocks. We do our test, we feel good if none of the expressions evaluated to false, and then we proceed with confidence.

Summary

In this article we discussed function argument validation. We learned how to avoid wrapping our code inside of a large IF() block and validate the presence of the argument we need in one line. We also discussed how to test for the type of our argument, and the fact that it contains the minimum amount of data.

Helpful Links for the JavaScript Logical NOT Operator

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators

http://msdn.microsoft.com/en-us/library/ie/zz722703(v=vs.94).aspx

Writing Argument-Agnostic JavaScript Functions

JavaScript

JavaScript LogoThere is no need to tightly couple a function and the other function that might call it, by sweating the details of the arguments passed in. You can access the local “arguments” variable, examine it, and decide how to handle the situation

Somewhere, I still have the code from my first fairly serious JavaScript project. From time to time, I like to take it out and look it over. It’s riddled with functions that, while written in good spirit, clearly reveal my level of inexperience at the time. This is not something I am proud to discuss publicly, but it is the truth. And, I always tell myself that everything is relative; some day I will look back on code I wrote last week and recoil with the same horror. Programming is a never-ending learning process and while the initial learning curve is steep, the process never ends; we always strive to improve our skill set.

One of the things that really stood out in my mind was how many functions I wrote that looked something like this:

While I don’t think it’s completely insane that I would write a function that takes so many specific arguments, I’ve come to realize that this approach tightly couples the function with the other function that might call it. The reason I keep mentioning “…might” is that in many cases, we write functions that are probably called in the lifetime of the program, but as many JavaScript apps are event-driven, it is not unusual for events to sometimes not happen, which means that functions are sometimes not called.

The point here is that tightly-coupled functions are, of course, sometimes unavoidable, but to me, it always seems a shame to have to write a function that is tightly coupled to its caller, but may never be called. So, I started to think about decoupling these functions from each other as much as possible. Granted, a function like “updateRecord()” will likely only be called to… well… update a record, but we can make it a bit more generic so that we don’t have to worry so much about what arguments were passed in when we write our code. We can simply write the function as if all the arguments we need have been passed in, and then “handle” the corner cases where some arguments are missing. This also frees up the caller in that there is reduced stress, as well, from that end; the caller can pass-in all the expected arguments, some of them, or none of them. What happens in these cases is, of course, up to us, but it does not always have to be an “all or nothing” scenario.

 Example # 1

In Example # 1, we don’t assume any arguments are passed in. We first test to see if the local “arguments” variable has a length that is greater than 0. If it does, great; we can then do something with the arguments. Most likely, we will want to examine them and see if the ones we need are available.

It is important to note that the “arguments” variable is not a true JavaScript array. The subtle details of this are worthy of another post. But keep in mind, it is simply a local variable that is array-like, in that it is an indexed list that can be iterated over and it does have a “length” property.

 Example # 2

In Example # 2, we loop through all of the arguments. Inside the loop, we could examine each argument and see if it meets the needs of the function.

Example # 3

In Example # 3, we pass an object in as the argument to our “updateRecord()” function. What is helpful about this approach is that the “updateRecord()” function does not break or throw an un-handled exception if we pass in too many arguments, not enough arguments, or no arguments. The function simply covers the following:

  1. Were any arguments passed in?
  2. If more than zero arguments were passed in, let’s loop through each one
  3. On each loop, if the argument being examined is an object, let’s loop through its properties
  4. On each sub-loop, we can do something with each property

Granted, your function may be a bit useless unless the exact number of arguments are passed-in and they are named in some exact way. But, your function does not have to be completely useless. It can handle corner cases gracefully, return a useful error, or maybe even partially carry out its intended task. The assumption here is that you or someone on your team will write this function and the one that calls it, so in the end, you can implement your own logic to make this function useful, yet unbreakable.

Summary

This topic is more of a pattern than a specific implementation. I like to use it because I prefer to keep my functions as loosely coupled as possible. It may not always be possible to keep them 100% uncoupled, but I prefer a pattern in which I can pass a function the right, wrong, or partially right number of arguments, and that function can inspect what it gets and handle the situation gracefully. A big plus when passing in an object, is that you can at least not worry about the order of the arguments; you simply grab the passed-in object, and enumerate the properties. What you do with what you find is up to you.

Helpful links for the JavaScript arguments property

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments

http://javascript.info/tutorial/arguments

 http://stackoverflow.com/questions/5303003/best-use-of-the-arguments-property-in-javascript