So we're getting to know JavaScript! One complaint I've been hearing with my peers is the syntax takes a while to get your head around. JavaScript is not forgiving when it comes to mistakes, especially when involving curly braces and parenthesis. Hunting for the missing closing curly braces in dozens, sometimes hundreds of lines of code can eat up a lot of time.
Luckily JavaScript does give us some ways of easing our pain. Let's take a basic look at arrow functions
What is an arrow function?
An arrow function is a compact way of writing out functions! Sometimes they can even be condensed into one line. Let's take a look at some simple code;
Here we have a simple function. We'll get this down to a single line. First we remove the "function" declaration, and put an arrow (=>) between the argument and opening bracket.
Then we can remove the curly braces, and the word "return." With arrow functions, the return is implied.
Awesome. Now we can remove the argument parentheses and we have just one line of clean looking code.
JavaScript syntax can get complicated. There are situations were you can't use arrow functions. For instance, if you have a function that contains more than one statement, you still have to use curly braces and the return keyword.
Another case where you would have you use a regular function is if you have no arguments. If you want to leave those parenthesis empty, say if you don't know how many arguments you might need, arrow functions simply won't work. Go with a regular function.
Also you can't name them. Arrow functions are all anonymous functions, as they can't have a name identifier.
I hope this brief explanation of arrow functions have helped you understand it a little bit more. It was a foreign concept to me when starting to learn JavaScript and for a while when practicing writing code, I stuck to regular functions. Only after I saw it broken down, step by step, did I understand the syntax a little better.
Top comments (0)