1

What is the difference between this (a 'standalone' function):

function standaloneFunction () {
    console.log('standaloneFunction runs, success')
}

standaloneFunction()

...and this (a function inside a variable):


let variableFunction = function variableFunction () {
    console.log('function inside let has same name as the variable, runs? - yep, does.')

}

variableFunction() 

Is it a problem that the variable and the function share the same name? it doesnt seem so - i speculate this is because it has something to do how variables and functions are saved in memory? Functions in their entirety, and variables only their declaration?

When i do console.log(this), i can't find the 'variableFunction' in the execution context of 'this' - however, 'standaloneFunction' does appear.

Have you, as a beginner, also asked yourself such questions? Am i being too picky about such details?

Should i already use es6 syntax?

Please also don't hold back with any advice regarding articulating my question.

Thanks to everyone who has taken their time to read this.

fal lout
  • 9
  • 2
  • This is ES6 syntax. You might be referring to `() => {}` syntax which is known as an "arrow function", but even though similar, they're not equivalent to normal functions. – evolutionxbox Jul 15 '20 at 18:54
  • One thing you'll notice is that if you overwrite the `let` variable with some other value, inside the function, the name will still be referring to the function. This is because the named function expression's name is scoped to the *inside* of the function, so as you wrote it, the inner name is *shadowing* the outer `let` variable name. –  Jul 15 '20 at 19:25

1 Answers1

-1

The first is a function declaration, which will be hoisted. The second is a named function expression, but I think an anonymous function expression would be better in this case since there’s no need to name the function, e.g. let variableFunction = function() {…}.

Please see What is the difference between a function expression vs declaration in JavaScript?

Ted Whitehead
  • 1,731
  • 10
  • 18
  • That's not a typo. By removing the name, it's no longer a named function expression. You're now just assigning an anonymous function to a variable. –  Jul 15 '20 at 19:24
  • Thanks! I meant an anonymous function expression, which I thought the author wanted since the function name was the same as the variable. Will edit my answer. – Ted Whitehead Jul 15 '20 at 19:49