ES6: Use Arrow Functions to Write Concise Anonymous Functions

Tell us what’s happening:
This isn’t an issue. Just started going through Arrow functions here, and wanted to understand a few things.

  1. The example over here performs a simple assignment of “value” to the constant myFunc.
const myFunc = () => "value";

Is there any benefit to doing that as opposed to performing this assignment simply by

const myFunc = "value";

2. This may seem silly, but the exercises here always require me to make sure I’m not using var anywhere. I need to either use const or let. Is that just for practice, or does ES6 encourage developers to never use var?

The first is an actual function, so you must call it to get the value.

The two would be more alike if you wrote it like:

const myFunc = () => "value";
const val = myFunc(); // val is now "value"

const let’s you assign a value to a variable and the variable can not be reassigned. It “protects” the variable from accidental assignment.

For example, var would still let you reassign the variable something else as seen below:

var myVar = "can be changed";
myVar = "new value";

With const, you will get a Type error, because myVar was declared using const:

const myVar = "can not be changed";
myVar = "this will result in an error";

In general, always use const unless you need the variable’s value to be reassigned within the scope you are working. In the latter case, use let. Both const and let have block scope where var does not. It is not just new syntax for the sake of new syntax. It is very powerful and useful syntax which was missing in earlier versions of JavaScript.

Understood. Thanks for the quick help, Randell