JavaScript: Difference between functions and arrow functions

nashmeyah

Nashmeyah

Posted on December 28, 2020

JavaScript: Difference between functions and arrow functions

There are many ways you can define functions in JavaScript. First is using the function keyword. There is function expression, function declaration

// function declaration
function(name) {
  return "Hello, ${name}!"
}

// function expression
const greeting = (name) {
  return "Hello, ${name}!"
}
Enter fullscreen mode Exit fullscreen mode

Second is using the ES2015 arrow function syntax.

// arrow function
 const greeting = (name) => {
  return "Hello, ${name}!"
}
Enter fullscreen mode Exit fullscreen mode

How do you know which one to use? Of course, depending on how you want to use it, think of 1. this value 2. Constructors 3. Implicit returns.

In regular functions and arrow functions, This values are dependent on how the function is called(invoked). "A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict *mode.

In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context)."(MDN, this keyword)

Regular functions can handle constructors well, as for arrow functions, when you use the new keyword to create a constructor it will throw an error.

Regulars functions, you must use the returns keyword to explicitly return your value. As for arrow function, you can implicitly return, if its a simple num+1 you can remove the curly braces and it will still know to return the value.

These are just some differences between using functions. If the reader(you) think there should be more information that I should add or alter, please let me know. Thank you for reading!

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
nashmeyah
Nashmeyah

Posted on December 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About