JavaScript JavaScript Functions Arrow Functions Create an Arrow Function

Blessed Marufu
Blessed Marufu
1,671 Points

arrow function

would kindly assist me to understand this

script.js
const  greet = 'cool coders'  => { `Hi,cool coders !`};
connor ingold
connor ingold
5,380 Points

Here an example of a working arrow function:

const greet = (someMsg) => { console.log(`the message: ${someMsg}`) }
greet("Hello world")

However, one thing to be aware of with arrow functions is that if they only have 1 parameter (like the example above) they don't need parentheses. So you can also do this:

const greet = someMsg => { console.log(`the message: ${someMsg}`) }
greet("Hello world")

And it's still completely fine.

2 Answers

Steven Parker
Steven Parker
207,597 Points

The example shown isn't valid syntax. In particular:

const  greet = 'cool coders'  => { `Hi,cool coders !`};
               ^^^^^^^^^^^^^
               // this should be a parameter name, not a string in quotes
const  greet = 'cool coders'  => { `Hi,cool coders !`};
                                   ^^^^^^^^^^^^^^^^^^
                                   // this should be one or more complete code statements,
                                   // -or- don't use the brackets
const  greet = 'cool coders'  => { `Hi,cool coders !`};
                                       ^^^^^^^^^^^
                                       // you probably want an interpolation token here,
                                       // as was used in the original version of the function

So, for example, a function that takes a string argument and returns a greeting string that contains it could be defined this way:

const greet = val => `Hi, ${val}!`;

Also, as mentioned in the hint, since arrow functions are not "hoisted", you will need to define the function before the line that calls it.