0

In the following two style of writing code,

<script>
    function foo() {
        // do something;
    }
</script>
<script>
    const foo = function() {
        // do something;
    }
</script>

Is the second way preferred over the first and is there any practical reason?

My "feeling" is that the second way is more modern and is seen more often these days, but couldn't explain why it is actually better.

cr001
  • 655
  • 4
  • 16
  • It's mostly a personal style choice. – Barmar Nov 14 '22 at 09:00
  • 2
    Apart from the linked answer, using `const` here prevents the function name from being reused/accidentally overridden elsewhere further down (as opposed to using `var` or `let`, or simply declaring it as `function foo(){...}` – Edwin Chua Nov 14 '22 at 09:04
  • 1st ex. is function declaration. 2nd ex. is function expression followed by assignment expression. Difference: hoisting & whether identifier can be reassigned (latter cannot due to `const` keyword). Hoisting behavior of function declarations can be useful bec. you can position the function anywhere in scope (even "after" use): if you need this, use this. Edwin highlights a possible advantage of the `const` syntax. Finally, in global context function declarations create properties on global object, `let`, `const` don't. ...and then there are arrow functions (not constructable, not bindable!) – Ben Aston Nov 14 '22 at 09:36

0 Answers0