DEV Community

Cover image for ✏️ Learn ES6 With Me: Part Two
yusufcodes
yusufcodes

Posted on

✏️ Learn ES6 With Me: Part Two

Introduction πŸ‘‹πŸΌ

Welcome to part two of this four-part series, where I'll be documenting the concepts I am currently learning as part of my journey to better understand the JavaScript Language.

In this part, I will be covering the following topics:

  1. Arrow Functions: Basics
  2. Arrow Functions: Lexical β€˜This’ Keyword
  3. Destructuring

If you want to start from the beginning of the series, below is a link to Learn ES6 With Me: Part One ⬇️

Arrow Functions: Basics ➑️

Arrow functions are a new way to write out functions in ES6. The syntax is simpler and allows for a much more cleaner look to your code.

For your reference, below is the basic syntax in a generic format, which I've taken directly from Mozilla Developer Network as it's nice and clear:

(param1, param2, …, paramN) => { statements } 
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }

// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }

// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }
Enter fullscreen mode Exit fullscreen mode

Now, onto a basic example. Let's start off with a regular function that we'd write in ES5. Here, I write a function declaration with the name ES5Func, passing in a parameter called name. This is then output to the console in a simple statement:

function ES5Func(name) 
{
    console.log(`Hey ${name}!`);
}

ES5Func('Yusuf'); // Output: Hey Yusuf!
Enter fullscreen mode Exit fullscreen mode

Now, I've written the same code as above but using the ES6 Arrow Function syntax. I'll break it down below:

const ES6Func = (name) => console.log(`Hey ${name}!`);
ES6Func('Yusuf');  // Output: Hey Yusuf! (same as above)
Enter fullscreen mode Exit fullscreen mode
  • We declare a const value called ES6Func - this is the name of our new function
  • We then supply any arguments to the function, in this case, we have name
    • Note: When you only have one argument, you can omit the parentheses if you want
  • We then introduce the use of an arrow => - this is identifying the beginning of our function.
    • Notice how, in this example, we have no curly braces like we usually do in ES5. This is because we're only writing a single line of code, and for simplicity, you don't need to use curly braces when there's only one line of code to execute.

Let's explore another example that has a bit more going on within it:

// Method to square the number entered by the user and return the value
const squareValue = (numToSquare) => {
    console.log(`The number that is going to be squared is: ${numToSquare}`);
    return numToSquare * numToSquare;
};

let valueSquared = squareValue(5);
console.log(valueSquared); // Output: 25 (5 x 5 = 25)
Enter fullscreen mode Exit fullscreen mode

Notice how in this second example, we do have curly braces as we're writing multiple lines of code.

Now, although our functions can be written using ES6 Arrow Function syntax, one thing we need to consider is that the behaviour of the 'this' value is different when we use this syntax. In the next section, I've tried to briefly describe this, although I know that it could be explored in more depth.

Arrow Functions: Lexical 'This' Keyword

With a regular ES5 function, each new function would define it's own this value which was determined by how the function was called - this is not the case with Arrow Functions!

Arrow Functions use the this value of it's surrounding environment, and because the value of this is affected by the location of the function, it is described as being lexical.

Below is an example of us writing an Arrow Function, simply displaying the this property in the console:

let exploreThisKeyword = () => console.log(this);
exploreThisKeyword();
Enter fullscreen mode Exit fullscreen mode

When running this function, the output resolves to the Window object. This is because the current parent scope is Window, the global scope of the browser.

More could be said with the explanation of exactly why this is happening, but I don't want this article to become too long! If you're interested in this topic of JavaScript, I recommend You Don't Know JS Yet: Scope & Closures.

The takeaway point of this section is that Arrow Functions do not create their own value for the 'this' keyword but rather, inherit the value assigned from their surrounding scope. So, keep this in mind as you start to use Arrow Functions.

Destructuring ⛏️

Destructuring is the process of breaking down a data structure into constituent variables. This allows for multiple variables to be quickly defined, without having to individually extract each value you want.

Let's say you have some array, foo, and you want to store the values of this array in some variables. Below is an example of how you would traditionally do this:

// ES5 - storing values from an array into variables
let foo = ['one', 'two', 'three'];

let red = foo[0];
let yellow = foo[1];
let green = foo[2];
Enter fullscreen mode Exit fullscreen mode

Although it works just fine, it's pretty long for what we're trying to achieve. Luckily we have destructuring!

Examples below show how destructuring is possible for Arrays and also Objects.

Arrays

// ES6 - storing values from an array into variables
let foo = ['one', 'two', 'three'];

let [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
Enter fullscreen mode Exit fullscreen mode

Objects

// ES6 - storing the value of some properties of an object into variables
let o = {p: 42, q: true};
let {p, q} = o;

console.log(p); // 42
console.log(q); // true
Enter fullscreen mode Exit fullscreen mode

Hopefully you can see how easy it is to extract data using this new feature of ES6.

Conclusion

In part two of this four-part series, I've covered the following ES6 JavaScript concepts:

  • ES6 Arrow Functions: the basic syntax and the behaviour of the 'this' keyword
  • Destructuring

Stay tuned for the next two parts of this series, which I'll post links to below once they've been released.

Some space for the next unreleased two parts of this series!

Want to read part one of this series? Click below

Note: I am in no way, shape or form, an expert when it comes to JavaScript. My idea and motive behind these posts are to help myself better understand these concepts as I learn them, whilst trying to give something back to the DEV community.
If there is anything fundamentally wrong with the information I've shared, please let me know. We're all still learning, and we can certainly do that together! 😊

Find me on Instagram and Twitter, where I post about the tech that I'm currently working with, and document my journey as a Computer Science studentπŸ™‚.

Discussion (3)

Collapse
dandynamicx profile image
ifechukwu daniel

Nice article

Collapse
yusufcodes profile image
yusufcodes Author

Thanks! πŸ˜ŠπŸ‘ŒπŸ½

Collapse
syntaxseed profile image
SyntaxSeed (Sherri W)

Wow, I find arrow functions to be way less readable.

At a quick glance it looks like a variable assignment, not a function definition.