How is ()=>value is different from directly assign the variable a value?

What I want to ask is what differences are in “const magic = ()=> new Date();” and “const magic=new Date();” if it’s a function that would not be reused again.

Tell us what’s happening:

Your code so far


const magic = ()=> new Date();

Challenge: Use Arrow Functions to Write Concise Anonymous Functions

Link to the challenge:

That line of code would create a function, magic = new Date() would create a date object, and to effectively get a date object from that you would need to write

const magic =  (()=> new Date())()

What I’ve done there is create and immediately call an anonymous function

The description is slightly confusing here. There is no reason that you wouldn’t reuse this function. You would need to actually call this particular function – it won’t do anything at all unless you actually use it. So in a sense, you have to reuse it somewhere, otherwise it won’t do anything.

The reason it says that at the start is that it is because the common use of anonymous functions is ones that you only use in one place in the code:

[1,2,3].map((v) => v * 2)
                 ↑
          anonymous function

same as

[1,2,3].map(function (v) {
  return v * 2;
});

Or with a function that isn’t anonymous:

function timesTwo (number) {
  return number * 2;
}

[1,2,3].map(timesTwo);

This is what the description is talking about: if you’re only using that function in one place, why define it as a separate function? Just use an anonymous function inline instead.


As it is, in the example:

const magic = new Date();

So that will be a date object representing the date/time at the point that part of code is evaluated.

const magic = () => new Date();

This will be a date object representing the date/time at the point magic() is called.

So for example:

const magic = new Date();

for (let i = 0; i < 5; i++) {
  console.log(magic);
}

That will log the same date object 5 times.

const magic = () => new Date();

for (let i = 0; i < 5; i++) {
  console.log(magic());
}

That will log a new date object 5 times (each one will be a millisecond or so later than the previous one)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.