Use Arrow Functions to Write Concise Anonymous Functions

Use Arrow Functions to Write Concise Anonymous Functions
0.0 0

#1

Tell us what’s happening:
I really don’t understand why we would use Arrow functions while we can write
const magic = new Date();
instead of
const magic = () => newdate();

Isn’t easier the first one? And if I’m wrong, please correct me as I didn’t write Javascript days ago.

Your code so far


const magic = new Date();



Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions


#2

const magic = new Date();
This will set magic to the new Date object. If you type magic in the console it will return the date/time when the variable is declared.

const magic = () => new Date();
This sets magic to a function which when called returns new Date() which will be an updated time on each call.

Just try it in the console to see what happens.

The es6 arrow function is showing off it’s concise syntax here. Since there is only one statement in the function it can be written how it is.

It could also be written like this which is slightly less concise but would allow for more lines of code in the function.

const magic = () => {
 return new Date();
}

#3

Oh, thank you.

So, when I declare the vars with the first expression, I give it the date/time when variable is declared but when I give it a function, it gets updated, right?


#4

https://repl.it/@br3ntor/Playing-Around