JavaScript arrow function assignment - Stack Overflow

I tried googling that , but i can not discuss to google, sometimes in the courses i saw the instructor

I tried googling that , but i can not discuss to google, sometimes in the courses i saw the instructor assign an arrow function to a variable like that.

const s = ( ) => { }

what are the cases when I need that syntax and not using

   function s( ) { }

My BASIC Question --> when to use

const s = ( ) => { } 

versus

function s( ) => { }

.. why the assignment ... thats my main Question (when and why i assign ?) why not use the arrow function without assigning it to a variable ??

I tried googling that , but i can not discuss to google, sometimes in the courses i saw the instructor assign an arrow function to a variable like that.

const s = ( ) => { }

what are the cases when I need that syntax and not using

   function s( ) { }

My BASIC Question --> when to use

const s = ( ) => { } 

versus

function s( ) => { }

.. why the assignment ... thats my main Question (when and why i assign ?) why not use the arrow function without assigning it to a variable ??

Share Improve this question edited Jun 6, 2019 at 1:46 mercury asked Jun 5, 2019 at 22:50 mercurymercury 2,7955 gold badges32 silver badges44 bronze badges 7
  • 2 "what are the cases when I need that syntax and not using" s() is calling the function. For that to work a function has to be assigned to s first. That's what the first example is doing. They pliment each other. – Felix Kling Commented Jun 5, 2019 at 22:54
  • 1 The first line declares a function, the second - invokes it. – zerkms Commented Jun 5, 2019 at 22:54
  • Why assignment call the function!?? @Zerkms – mercury Commented Jun 6, 2019 at 0:00
  • 1 @HosMercury it does not – zerkms Commented Jun 6, 2019 at 0:10
  • Just added function before s( ) { } – mercury Commented Jun 6, 2019 at 0:24
 |  Show 2 more ments

5 Answers 5

Reset to default 1

Your examples are showing 2 ways to declare a function.

This is an example of a function declaration.

function s() {
// some code
}

This is another way to define a function, called function expression.

const s = function() {
// some code
}

This is an arrow function. With the exception of the way this is treated between the arrow function and the other two, they are pretty much 3 ways to write the same function.

const s = () => {
// some code
}

As stated in the response below, function declaration and function expression are ES5 features and the arrow function is an ES6 feature.

Your examples do different things: the first declares a function s, the second one calls s().

For the sake of clarity...

// ES5
var multiplyES5 = function(x, y) {
  return x * y;
};

// ES6
const multiplyES6 = (x, y) => { 
  return x * y;
};

Where Arrow Functions Improve Your Code ( where you should use them ) -

One of the primary use cases for traditional lambda functions, and now for arrow functions in JavaScript, is for functions that get applied over and over again to items in a list.

For example, if you have an array of values that you want to transform using a map, an arrow function is ideal:

const words = ['hello', 'WORLD', 'Whatever'];
const downcasedWords = words.map(word => word.toLowerCase());

An extremely mon example of this is to pull out a particular value of an object:

const names = objects.map(object => object.name);

Similarly, when replacing old-style for loops with modern iterator-style loops using forEach, the fact that arrow functions keep this from the parent makes them extremely intuitive.

this.examples.forEach(example => {
   this.runExample(example);
});

Promises and Promise Chains - Another place arrow functions make for cleaner and more intuitive code is in managing asynchronous code.

Promises make it far easier to manage async code (and even if you're excited to use async/await, you should still understand promises which is what async/await is built on top of!)

However, while using promises still requires defining functions that run after your asynchronous code or call pletes.

This is an ideal location for an arrow function, especially if your resulting function is stateful, referencing something in your object. Example:

this.doSomethingAsync().then((result) => {
  this.storeResult(result);
});

Object Transformations - Another mon and extremely powerful use for arrow functions is to encapsulate object transformations.

For example, in Vue.js there is a mon pattern for including pieces of a Vuex store directly into a Vue ponent using mapState.

This involves defining a set of "mappers" that will transform from the original plete state object to pull out exactly what is necessary for the ponent in question.

These sorts of simple transformations are an ideal and beautiful place to utilize arrow functions. Example:

export default {
  puted: {
     ...mapState({
      results: state => state.results,
      users: state => state.users,
     });
  }
}

Where You Should Not Use Arrow Functions -

There are a number of situations in which arrow functions are not a good idea. Places where they will not only help, but cause you trouble.

The first is in methods on an object. This is an example where function context and this are exactly what you want.

There was a trend for a little while to use a bination of the Class Properties syntax and arrow functions as a way to create "auto-binding" methods, e.g. methods that could be used by event handlers but that stayed bound to the class.

This looked something like:

class Counter {
counter = 0;

  handleClick = () => {
    this.counter++;
  }
}

In this way, even if handleClick were called with by an event handler rather than in the context of an instance of Counter, it would still have access to the instance's data.

The downsides of this approach are multiple,

While using this approach does give you an ergonomic-looking shortcut to having a bound function, that function behaves in a number of ways that are not intuitive, inhibiting testing and creating problems if you attempt to subclass/use this object as a prototype.

Instead, use a regular function and if necessary bind it the instance in the constructor:

class Counter {
  counter = 0;

  handleClick() {
    this.counter++;
  }

  constructor() {
    this.handleClick = this.handleClick.bind(this);
  }
}

Deep Callchains - Another place where arrow functions can get you in trouble is when they are going to be used in many different binations, particularly in deep chains of function calls.

The core reason is the same as with anonymous functions - they give really bad stacktraces.

This isn't too bad if your function only goes one level down, say inside of an iterator, but if you're defining all of your functions as arrow functions and calling back and forth between them, you'll be pretty stuck when you hit a bug and just get error messages like:

{anonymous}()
{anonymous}()
{anonymous}()
{anonymous}()
{anonymous}()

Functions With Dynamic Context - The last situation where arrow functions can get you in trouble is in places where this is bound dynamically.

If you use arrow functions in these locations, that dynamic binding will not work, and you (or someone else working with your code later) may get very confused as to why things aren't working as expected.

Some key examples of this:

  • Event handlers are called with this set to the event's currentTarget attribute.
  • If you're still using jQuery, most jQuery methods set this to the dom element that has been selected.
  • If you're using Vue.js, methods and puted functions typically set this to be the Vue ponent.

Certainly you can use arrow functions deliberately to override this behavior, but especially in the cases of jQuery and Vue this will often interfere with normal functioning and leave you baffled why code that looks the same as other code nearby is not working.

this excerpt is taken from here

I assume you mean function s( ) { } in your update.

Notice how that function declaration contains the name s. This implicitly creates a variable s and assigns the function to it. An arrow function definition does not contain a name. So in other to use/call/reference the function elsewhere you have to assign it to a variable explicitly.

why not use the arrow function without assigning it to a variable ??

The only why do this is to put calling parenthesis after the definition, e.g.

(() => console.log('test'))()

This will define and call the function immediately, printing "test" to the console.

But there is not much point in doing that, since the code is equivalent to just writing

console.log('test')

So in JavaScript we write function expressions all the time, so much so that it was decided that there should be a more pact syntax for defining them. It's another way to write a function.

const square = x => {
  return x * x;
}

I deliberately have no parens surrounding the x because when there is only one argument, current syntax says we can do away with parens.

The above is actually fully functional, you can run square(4); on it and get 16.

Imagine you have nested callbacks written like this:

const square = function(x){
  return x * x;
}

Seeing the keyword function all over the place, could drive you batty after awhile.

Arrow functions are cleaner and leaner, but arrow functions is not just syntactic sugar, there is another difference and that is regarding the keyword, this.

If you do not have extensive knowledge of the keyword this, I highly remend you start to source some solid information out there on the topic, at least as it relates to arrow functions. That research should uncover in what cases you would need to use an arrow function.

As far as why assign it a variable, you have to look at the evolution of the arrow function as outlined by mph85. You go from function declaration:

function isEven(num) {
  return num % 2 === 0;
}

to an anonymous function declaration assigned as a variable named isEven:

const isEven = function(num) {
  return num % 2 === 0;
}

to the anonymous function declaration assigned to a variable called isEven evolving to an arrow function expression assigned to said variable.

const isEven = (num) => {
  return num % 2 === 0;
}

And we can up the ante and make this more concise with an implicit return where we can drop the parens, curly braces and return keyword like so:

const isEven = num => num % 2 === 0;

I think it's important to observe how this evolves so whenever you see the last version above, it will not throw you off.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745340448a4623303.html

相关推荐

  • JavaScript arrow function assignment - Stack Overflow

    I tried googling that , but i can not discuss to google, sometimes in the courses i saw the instructor

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信