this in the arrow function is the same as this outside the arrow function.įor example, suppose you try to call setTimeout() in aĬlass method.
#ARROW FUNCTION JAVASCRIPT CODE#
Implicit return for one-line functions means more concise code.In other words, the context inside arrow functions is lexically or statically defined. Arrow function expressions are ill-suited as methods, and they cannot be used as constructors. According to MDN, An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Another significant advantage it offers is the fact that it does not bind its own this. Javascript Front End Technology Object Oriented Programming. If your arrow function takes more than 1 param, you must // put parentheses around the parameter names const add = ( a, b) => a + b Why Arrow Functions?Īrrow functions have two major advantages: Arrow functions, introduced in ES6, provides a concise way to write functions in JavaScript. If your arrow function takes 1 param, you can omit the // parentheses around the parameter names let noop = v => v If your arrow function takes no params, declare it with // `() =>` const getAnswer = () => 42 Without curly braces unless your arrow function takes exactly one parameter.When you see =>, you're looking at an arrow function. Using an arrow function is the wrong choice. However, you still need to learn when to useĬonventional functions versus when to use arrow functions, because Were introduced in ES6 to work around several common gotchas withĬonventional functions.