1

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 ??

Hos Mercury
  • 1,256
  • 2
  • 14
  • 22

5 Answers5

1

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;
};
VenomVendor
  • 14,120
  • 11
  • 63
  • 89
A.J. Uppal
  • 17,608
  • 6
  • 40
  • 70
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.

mph85
  • 994
  • 3
  • 11
  • 33
  • What cases the code doesn’t work untill I change the function type to expression function!?? .. like with events it have to be expression to work .. my question basically what is the role to use one or the other? – Hos Mercury Jun 06 '19 at 00:44
  • for `function declaration`, you should read up on `hoisting`. This allows the declared function to be called before or after it's declared. It's available globally. When you don't want that to happen, you would still to `function expression` or `arrow functions` – mph85 Jun 06 '19 at 00:47
  • So why with Callbacks i have to use arrow !? – Hos Mercury Jun 06 '19 at 00:48
  • @HosMercury I also believe that with `function declaration` your function will load right away before any code is executed. With the others, you will get an error until you reach that specific line of code – mph85 Jun 06 '19 at 00:49
  • I didn’t understand, sorry . albeit I understand hoisting – Hos Mercury Jun 06 '19 at 00:51
  • 1
    @HosMercury no worries. `So why with Callbacks i have to use arrow`. Can you give an example? You don't have to use `arrow functions` to use callbacks – mph85 Jun 06 '19 at 00:53
  • read up on arrow functions and `this`, arrow functions can help you avoid having to bind `this` all the time. – mph85 Jun 06 '19 at 00:56
  • when to use |||| const s = ( ) => { } |||| versus ||| function s( ) => { } .. why the assignment ... thats my main Q – Hos Mercury Jun 06 '19 at 01:24
  • 1
    This is a bit harder to answer directly, as you'll come to find out, a lot of why you decide to do stuff depends on what is needed and in what context it is used. Like I said above, when thinking about `this` is when you would decide if you would use a `function declaration` as opposed to `arrow function` – mph85 Jun 06 '19 at 01:28
  • 1
    in React, take a look at this question, https://stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react – mph85 Jun 06 '19 at 01:30
  • I understand( this )in arrow funcs .. i want to understand js logic – Hos Mercury Jun 06 '19 at 01:31
  • https://zendev.com/2018/10/01/javascript-arrow-functions-how-why-when.html – mph85 Jun 06 '19 at 01:33
  • more examples of when to use `arrow function` or other – mph85 Jun 06 '19 at 01:33
1

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 common 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 completes.

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 common and extremely powerful use for arrow functions is to encapsulate object transformations.

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

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

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

export default {
  computed: {
     ...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 combination 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 combinations, 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 computed functions typically set this to be the Vue component.

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

samar taj Shaikh
  • 1,032
  • 10
  • 16
1

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')
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
1

So in JavaScript we write function expressions all the time, so much so that it was decided that there should be a more compact 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 recommend 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.

halfer
  • 18,701
  • 13
  • 79
  • 158
Daniel
  • 9,020
  • 8
  • 63
  • 101