简体   繁体   中英

how to define const function javascript (syntactic sugar)?

I expect to be able to create a function like:

const function doSomething(){...}

Yet looks like the only way to achieve it is:

const doSomething=function(){...}

Am I wrong? or is there actually a syntactic sugar for it?

The only thing const does in JavaScript is prevent re-assignment of a variable. Not to be confused with preventing mutation of a value.

const requires an identifier, an assignment operator, and a right-hand side. The only way to combine const with a function is with a function expression (your second example).

const doSomething = function() {
  // do stuff
};
// will either throw an error or the value of doSomething simply won't change
doSomething = somethingElse;

Many people like to make sure their functions are named so that the name appears in the call stack and as such prefer to use function declarations (your first example). However, it's possible to name a function expression.

const doSomething = function doSomething() {
  // name will appear as doSomething in the call stack
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM