Karim Aya

Karim Aya

1560933652

JavaScript’s Arrow Functions Explained By Going Down A Slide

If you have been using JavaScript for a few years, you are probably familiar with this syntax:

function addTen(num){
  return num + 10;
});

console.log(addTen(10));
//20

This function syntax was popular in ES5, or ECMAScript 5.

There is one major advantage to this syntax: It includes the word function, so it is obvious that you are writing a function!

A function clearly takes in anywhere from 0 to many arguments and runs a specific set of statements every time that it is called.

But then the world of JavaScript took a leap forward with ES6 in 2015.

Now, the same function as above would be written like this:

let addTen = (num) => num + 10;

console.log(addTen(10));
//20

Now, there is no function keyword, and no return statement! Functions in ES6 are much more terse , or concise.

So, since those obvious clues have been removed, you might be having a little bit of a hard time with understanding the different parts of arrow functions.

Fortunately, as you will soon see with a few animations, arrow functions are pretty easy to understand once you learn to visualize the arrow “=>” in a new way.

So here is how arrow functions are just like a water slide. In order to fully understand this tutorial, it might help to know about map functions and scoping.

Arrow Functions Visualized

Let’s explore the addTen function a little more deeply.

let addTen = (num) => num + 10;

console.log(addTen(10));
//20

This function will transform one parameter and output that parameter with 10 added.

The transformation happens with that subtle “=>” arrow.

I like to transform that arrow into a tube slide in my mind to show what is actually happening. Here is what I mean:

The equals sign is like the tube slide and the arrow is like the landing pad.

Arrow functions follow this pattern:

(parameters) => {statements}

So let’s add those to the diagram with our addTen function example.

The last thing we need to show is how the parameter, which is 10 in this case, goes down the slide and becomes available in the statements of the function. Here’s what that looks like.

That’s all it is! Pretty straightforward.

Now, let’s look at an example where there are two different parameters. Here is our new function:

let multiply = (num1, num2) => {return num1 * num2};

console.log(multiply(2, 10));
//20

In this case we are just multiplying the two parameters together. Both will go down the slide together. Like this:

There’s one more example you should know about- combining the map() method with arrow functions.

The map() method will send every element in an array into the arrow function, in order.

Let’s go through an example- imagine that you have an array of numbers, and you want to get the square root of each one.

Here’s the code.

let nums = [1, 4, 9];

let squares = nums.map((num) => {
  return Math.sqrt(num);
});

console.log (squares)
// [1, 2, 3]

You need to know a little about the map method to understand this one. But, you will probably notice the terse syntax yet again- the map() method is much shorter than writing a for() loop.

Here’s what is happening in this code:

  1. There are three elements in the nums array, so the num parameter goes down the slide 3 times.
  2. The Math.sqrt() method takes the square root of the number each time.
  3. The result is stored in the squares array each time.

The Difference Between Arrow Functions And Traditional Functions

You might be wondering… is this simply a difference in syntax?

Actually, there is one important way that the traditional ES5 functions and ES6 functions work differently.

The big change is that arrow functions do not have their own scope. Therefore, if you try to use the this keyword, you will be surprised when it does not refer to the scope of the arrow function.

To go back to our slide analogy, this means that this is the same at the top and bottom of the slide. If we were using ES5 functions, then this would be different at the top and bottom of the slide.

To quickly recognize this in code, just look for the function keyword. If you see it, that means that a new scope is being created. If not, assume that you are using the scope of the enclosing function.

#javascript

What is GEEK

Buddha Community

JavaScript’s Arrow Functions Explained By Going Down A Slide
Vincent Lab

Vincent Lab

1605017502

The Difference Between Regular Functions and Arrow Functions in JavaScript

Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the closest non-arrow parent function. Arrow functions can never be constructor functions so they can never be invoked with the new keyword. And they can never have duplicate named parameters like a regular function not using strict mode.

Here are a few code examples to show you some of the differences
this.name = "Bob";

const person = {
name: “Jon”,

<span style="color: #008000">// Regular function</span>
func1: <span style="color: #0000ff">function</span> () {
    console.log(<span style="color: #0000ff">this</span>);
},

<span style="color: #008000">// Arrow function</span>
func2: () =&gt; {
    console.log(<span style="color: #0000ff">this</span>);
}

}

person.func1(); // Call the Regular function
// Output: {name:“Jon”, func1:[Function: func1], func2:[Function: func2]}

person.func2(); // Call the Arrow function
// Output: {name:“Bob”}

The new keyword with an arrow function
const person = (name) => console.log("Your name is " + name);
const bob = new person("Bob");
// Uncaught TypeError: person is not a constructor

If you want to see a visual presentation on the differences, then you can see the video below:

#arrow functions #javascript #regular functions #arrow functions vs normal functions #difference between functions and arrow functions

JavaScript: The Good Parts of Arrow Functions

When I was at a coding boot camp learning about JavaScript and ES6, everyone in class seemed to have some level of confusion around normal function declarations and the new ES6 arrow function declarations. Common questions we had included:

  • When should we use normal functions or arrow functions?
  • What are the differences between normal functions and arrow functions?
  • Are we able to use one or the other in all situations for consistency?

After doing some research, I found that normal functions and arrow functions are actually not interchangeable in certain circumstances. Apart from the syntax, normal functions and arrow functions have another major difference: the way they bind the this keyword in JavaScript.

Let’s look at a very simple example. Suppose we have a simple JavaScript object:

const obj1 = {
	  fullName: 'Object 1',
	  color: 'red',
	  print: function() {
	    console.log(`${this.fullName} is ${this.color}`);
	  }
	};

	obj1.print(); // Object 1 is red
view raw
object1.js hosted with ❤ by GitHub

We have a print method on obj1 that logs a string to the console. The result is what we have expected, that this in the print method refers to obj1 itself.

Now let’s create another object with a slightly different print method:

const obj2 = {
	  fullName: 'Object 2',
	  color: 'blue',
	  print: function() {
	    setTimeout(function() {
	      console.log(`${this.fullName} is ${this.color}`);
	    }, 1000);
	  }
	};

	obj2.print(); // undefined is undefined
view raw
object2.js hosted with ❤ by GitHub

Now the print method will only log the resulting string after one second due to setTimeout . But why is it logging undefined is undefined instead of Object 2 is blue ?

#es2015 #javascript #es6 #javascript-tips #arrow-functions #function

JavaScript’s Arrow Functions Explained By Going Down A Slide

If you have been using JavaScript for a few years, you are probably familiar with this syntax:

function addTen(num){
  return num + 10;
});

console.log(addTen(10));
//20

This function syntax was popular in ES5, or ECMAScript 5.

There is one major advantage to this syntax: It includes the word function, so it is obvious that you are writing a function!

A function clearly takes in anywhere from 0 to many arguments and runs a specific set of statements every time that it is called.

But then the world of JavaScript took a leap forward with ES6 in 2015.

Now, the same function as above would be written like this:

let addTen = (num) => num + 10;

console.log(addTen(10));
//20

Now, there is no function keyword, and no return statement! Functions in ES6 are much more terse , or concise.

So, since those obvious clues have been removed, you might be having a little bit of a hard time with understanding the different parts of arrow functions.

Fortunately, as you will soon see with a few animations, arrow functions are pretty easy to understand once you learn to visualize the arrow “=>” in a new way.

So here is how arrow functions are just like a water slide. In order to fully understand this tutorial, it might help to know about map functions and scoping.

Arrow Functions Visualized

Let’s explore the addTen function a little more deeply.

let addTen = (num) => num + 10;

console.log(addTen(10));
//20

This function will transform one parameter and output that parameter with 10 added.

The transformation happens with that subtle “=>” arrow.

It can also be written with a return statement:

let addTen = (num) => {return num + 10};

console.log(addTen(10));
//20

I like to transform that arrow into a tube slide in my mind to show what is actually happening. Here is what I mean:

The equals sign is like the tube slide and the arrow is like the landing pad.

Arrow functions follow this pattern:

(parameters) => {statements}

So let’s add those to the diagram with our addTen function example.

The last thing we need to show is how the parameter, which is 10 in this case, goes down the slide and becomes available in the statements of the function. Here’s what that looks like.

That’s all it is! Pretty straightforward.

Now, let’s look at an example where there are two different parameters. Here is our new function:

let multiply = (num1, num2) => {return num1 * num2};

console.log(multiply(2, 10));
//20

In this case we are just multiplying the two parameters together. Both will go down the slide together. Like this:

There’s one more example you should know about- combining the map() method with arrow functions.

The map() method will send every element in an array into the arrow function, in order.

Let’s go through an example- imagine that you have an array of numbers, and you want to get the square root of each one.

Here’s the code.

let nums = [1, 4, 9];

let squares = nums.map((num) => {
  return Math.sqrt(num);
});

console.log (squares)
// [1, 2, 3]

You need to know a little about the map method to understand this one. But, you will probably notice the terse syntax yet again- the map() method is much shorter than writing a for() loop.

Here’s what is happening in this code:

  1. There are three elements in the nums array, so the num parameter goes down the slide 3 times.
  2. The Math.sqrt() method takes the square root of the number each time.
  3. The result is stored in the squares array each time.

The Difference Between Arrow Functions And Traditional Functions

You might be wondering… is this simply a difference in syntax?

Actually, there is one important way that the traditional ES5 functions and ES6 functions work differently.

The big change is that arrow functions do not have their own scope. Therefore, if you try to use the this keyword, you will be surprised when it does not refer to the scope of the arrow function.

To go back to our slide analogy, this means that this is the same at the top and bottom of the slide. If we were using ES5 functions, then this would be different at the top and bottom of the slide.

To quickly recognize this in code, just look for the function keyword. If you see it, that means that a new scope is being created. If not, assume that you are using the scope of the enclosing function.

Posts

1

Thanks for reading ❤

2

If you liked this post, share it with all of your programming buddies!

3

Follow me on **[Facebook]( https://www.facebook.com/moriohdotcom)** | **[Twitter]( https://twitter.com/moriohdotcom)**

4

5

### Learn More

6

7

☞ [The Complete JavaScript Course 2019: Build Real Projects!](http://learnstartup.net/p/rJWeUz65Z "The Complete JavaScript Course 2019: Build Real Projects!") 

8

☞ [Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)](http://learnstartup.net/p/BJBa7-l-g "Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)")

9

☞ [JavaScript Bootcamp - Build Real World Applications](http://learnstartup.net/p/-J13WdymB "JavaScript Bootcamp - Build Real World Applications") 

10

☞ [The Web Developer Bootcamp](https://learnstartup.net/p/SJQU6Gxbg "")

11

☞ [JavaScript: Understanding the Weird Parts](http://learnstartup.net/p/HyUQWUMTqW "JavaScript: Understanding the Weird Parts")

12

☞ [From Javascript to Typescript to Elm](http://tech.learn4startup.com/bc52b1d27c "")

13

☞ [JavaScript Web Workers: A Beginner’s Guide](http://dev.edupioneer.net/580481d0e4 "")

14

☞ [Top 12 Javascript Tricks for Beginners](http://on.geeklearn.net/1540f81ec6 "")

15

☞ [Learn JavaScript - JavaScript Course for Beginners](http://on.geeklearn.net/162c65c573 "")

16

☞ [JavaScript naming conventions: do’s and don’ts](http://tech.learn4startup.com/417232d415 "")

17

☞ [12 Concepts That Will Level Up Your JavaScript Skills](http://dev.edupioneer.net/97a2cf32d6 "")

18

19

*Originally published on [https://dev.to](https://dev.to/kbk0125/javascript-s-arrow-functions-explained-by-going-down-a-slide-1ebm)*

Thanks for reading ❤

#javascript #function

Giles  Goodwin

Giles Goodwin

1603176407

The real reason why JavaScript has arrow functions

Nowadays, all my code is based on the use of arrow functions. If you are still not using them yourself, then don’t be ashamed of who you are. That’s your parent’s job. Instead, find about all the benefits that you can get by using arrow functions like the cool kids.

This is an example of arrow function and the same code written traditionally:

const arrowFunction = (arg1, arg2) => arg1 + arg 2;

const traditionalFunction = function(arg1, arg2) {
  return arg1 + arg2;
};

You may notice that the code is shorter and that there is an arrow. Everything before the arrow is arguments of the function and everything after the arrow is always returned as the result of the function.

If you need a function that contains multiple statements you can still do this:

const arrowFunction = (arg1, arg2) => {
  const result = arg1 + arg2;
  return result;
};

#javascript #js #functional-javascript #functional-programming #javascript-tips

Madyson  Reilly

Madyson Reilly

1601069940

Function Expression vs Function Declaration in JavaScript

Function Expression vs Function Declaration in JavaScript.

It was until during one of the JavaScript mock interviews did I came across the term function expression.

The question was: What is the difference between these two syntax?

function x(){

}

let x = function(){

}

I was clueless for a moment. After thinking a little, I could only come up with: the second syntax invokes an _anonymous _function and is assigned to a variable.

I was alien to the term hoisting.

In this article, we will acquaint ourselves with three simple terms: function declaration,_ function expression, _and hoisting.

What is function declaration?

Function declaration is also known as _function statement. _It contains the name of the function, parameters, and a return statement. **Naming the function **is what sets function declaration apart. Parameters and return statement is optional.

Image for post

Function Declaration

What is function expression?

Function expression also has a name, parameters, and return statement. All of which are optional. The important thing to bear in mind is: the function here is _assigned _to a JavaScript variable.

Image for post

Function Expression

#function-expression #function-declaration #functions-in-javascript #coding #javascript #express