357

Are there any limits to what types of values can be set using const in JavaScript, and in particular, functions? Is this valid? Granted it does work, but is it considered bad practice for any reason?

const doSomething = () => {
   ...
}

Should all functions be defined this way in ES6? It does not seem like this has caught on, if so.

5
  • 4
    You seem to ask multiple questions: 1) "I am interested if there are any limits to what types of values can be set using const in JavaScript" No. 2) "Is this valid?" Yes. 3) "is it considered bad practice for any reason" I guess it hasn't been around for long enough to say anything about that but I don't see why this should be pad practice. It's not much different from var doSomething = <function def>;. 4) "Should all functions be defined this way in ES6?" Seems to cumbersome to me. I like function declarations. Everyone their own. Oct 9, 2015 at 14:29
  • 1
    The way I see it (opinion, not a fact), it makes sense if you want to disallow redefining functions. Whether it's sane, or whether it has some functional use - that's debatable. If you think it fits your use scenario, I don't think someone can argue your decision and deem it bad practice.
    – Mjh
    Oct 9, 2015 at 14:30
  • 5
    I guess the question is what you want to achieve with const. Do you want to prevent yourself from overriding the function? I'd assume you know your code to not do this anyway. Do you want to express the intent of doSomething, i.e. that it holds a function and does not change its value? I think function declarations communicate this intent clearly as well. So, if you need "runtime protection" from overriding, go for it. Otherwise I don't see much benefit. Of course if you primarily used to use var foo = function() {};, I would use const instead of var. Oct 9, 2015 at 14:35
  • 7
    @FelixKling, "I'd assume you know your code to not do this anyway." - this is pretty bad argument. Otherwise, there's no sense in const at all.
    – meandre
    Nov 29, 2016 at 9:14
  • 3
    I'd like to add that using const instead of function to define a "function" is a regression in readability. I just started JS again after a 4-5 year hiatus and came across a bunch of const to declare function code and it is wrecking my brain. Oct 8, 2021 at 23:05

6 Answers 6

465

There's no problem with what you've done, but you must remember the difference between function declarations and function expressions.

A function declaration, that is:

function doSomething () {}

Is hoisted entirely to the top of the scope (and like let and const they are block scoped as well).

This means that the following will work:

doSomething() // works!
function doSomething() {}

A function expression, that is:

[const | let | var] = function () {} (or () =>

Is the creation of an anonymous function (function () {}) and the creation of a variable, and then the assignment of that anonymous function to that variable.

So the usual rules around variable hoisting within a scope -- block-scoped variables (let and const) do not hoist as undefined to the top of their block scope.

This means:

if (true) {
    doSomething() // will fail
    const doSomething = function () {}
}

Will fail since doSomething is not defined. (It will throw a ReferenceError)

If you switch to using var you get your hoisting of the variable, but it will be initialized to undefined so that block of code above will still not work. (This will throw a TypeError since doSomething is not a function at the time you call it)

As far as standard practices go, you should always use the proper tool for the job.

Axel Rauschmayer has a great post on scope and hoisting including es6 semantics: Variables and Scoping in ES6

2
  • 13
    Would just like to add that es6 classes uses const internally to protect the class name from being reassigned within the class. Jul 21, 2017 at 6:22
  • 8
    One subtle difference between a function a(){console.log(this);} and b const a=_=>{console.log(this);} is if you call it like a.call(someVar);, in a, it will print someVar, in b, it will print window.
    – user1663023
    Feb 19, 2019 at 0:34
207

Although using const to define functions seems like a hack, it comes with some great advantages that make it superior (in my opinion)

  1. It makes the function immutable, so you don't have to worry about that function being changed by some other piece of code.

  2. You can use fat arrow syntax, which is shorter & cleaner.

  3. Using arrow functions takes care of this binding for you.

example with function

// define a function
function add(x, y) { return x + y; }

// use it
console.log(add(1, 2)); // 3

// oops, someone mutated your function
add = function (x, y) { return x - y; };

// now this is not what you expected
console.log(add(1, 2)); // -1

same example with const

// define a function (wow! that is 8 chars shorter)
const add = (x, y) => x + y;

// use it
console.log(add(1, 2)); // 3

// someone tries to mutate the function
add = (x, y) => x - y; // Uncaught TypeError: Assignment to constant variable.
// the intruder fails and your function remains unchanged

9
  • 129
    1. Immutability is a real benefit, but it is very rare for someone to actually overwrite a function. 2. Fat arrow syntax is not shorter unless your function can be an expression. function f(x, y) { is 18 characters, const f = (x, y) => { is 21 characters, so 3 character longer. 3. Keeping this binding only matters if the functions are defined inside a method (or other function which has meaningful this). At the top level script it is pointless. I'm not saying you are wrong, just that the reasons you mention are not terribly relevant.
    – Nakedible
    Feb 12, 2018 at 22:05
  • 61
    One advantage of the old fashioned function syntax is during debugging it has a name.
    – user949300
    Oct 27, 2018 at 3:24
  • 9
    I would use linters to prevent re-binding the function declaration. Jul 26, 2019 at 15:04
  • 2
    @Nakedible - I also prefer using function but in your comparison you're forgetting the function needs return while the other method doesn't. (Unless I'm unaware of a shortcut?)
    – ashleedawg
    Oct 27, 2020 at 22:31
  • 5
    "You can use fat arrow syntax, which is shorter & cleaner." - Sometimes shorter and cleaner isn't better if it makes the code harder to follow for other developers. Good programming isn't just writing short code that works, it's also writing maintainable code among other things.
    – Baba
    May 25, 2022 at 12:18
89

It has been three years since this question was asked, but I am just now coming across it. Since this answer is so far down the stack, please allow me to repeat it:

Q: I am interested if there are any limits to what types of values can be set using const in JavaScript—in particular functions. Is this valid? Granted it does work, but is it considered bad practice for any reason?

I was motivated to do some research after observing one prolific JavaScript coder who always uses const statement for functions, even when there is no apparent reason/benefit.

In answer to "is it considered bad practice for any reason?" let me say, IMO, yes it is, or at least, there are advantages to using function statement.

It seems to me that this is largely a matter of preference and style. There are some good arguments presented above, but none so clear as is done in this article:

Constant confusion: why I still use JavaScript function statements by medium.freecodecamp.org/Bill Sourour, JavaScript guru, consultant, and teacher.

I urge everyone to read that article, even if you have already made a decision.

Here's are the main points:

Function statements have two clear advantages over [const] function expressions:

Advantage #1: Clarity of intent

When scanning through thousands of lines of code a day, it’s useful to be able to figure out the programmer’s intent as quickly and easily as possible.

Advantage #2: Order of declaration == order of execution

Ideally, I want to declare my code more or less in the order that I expect it will get executed.

This is the showstopper for me: any value declared using the const keyword is inaccessible until execution reaches it.

What I’ve just described above forces us to write code that looks upside down. We have to start with the lowest level function and work our way up.

My brain doesn’t work that way. I want the context before the details.

Most code is written by humans. So it makes sense that most people’s order of understanding roughly follows most code’s order of execution.

5
  • 1
    Can you comment slightly more on the clarity of intent? I get #2, but as far as I can tell #1 is just a (pre?) reiteration of #2. I can think of a case, i.e. functions having their own defaultErrorHandler const assigned as an anonymous function that I can then call from promise handlers. This would enable me to optionally 'override' this default error handler within functions as I needed to. Some just need to return an error object and others need to return an http response, varying levels of verbosity. Yet the code structure can be a familiar pattern regardless.
    – Jake T.
    Jul 12, 2018 at 21:26
  • Maybe my idea is too convoluted though! Just wrapping my head around some new practices, haven't spent a ton of time implementing them yet. Just finding I really like .then( res.success, res.error ) a lot more than the anonymous functions I was declaring to just call res.success(value);. Having a .then( ..., defaultErrorHandler) common pattern could be nice, with a top level defined defaultErrorHandler function, and optionally have a const defaultErrorHandler = error => { ... } declared within a function scope as desired.
    – Jake T.
    Jul 12, 2018 at 21:29
  • 7
    @JakeT. RE "Can you comment slightly more on the clarity of intent? ". Well, first of all, that statement was not made my me, but by freecodecamp.org/Bill Sourour, the author of that article. But it makes real common sense to me. If I read "function tomorrow()" then I immediately know it IS a function. But if I read "const tomorrow = () =>", I have stop for a moment and parse the syntax in my head to finally determine, OK, yeah, it's a function.
    – JMichaelTX
    Aug 6, 2018 at 22:39
  • 1
    Another thing, if I have a long script written by someone else, and I want to see all of the functions, I can do a quick search on "function" to find them. Or even better, I can write a quick JS RegEx to extract all of the functions. IMO, the "const" statement is just for data (not functions) that will NOT change.
    – JMichaelTX
    Aug 6, 2018 at 22:39
  • @JMichaelTX - I get what you're saying about reading function tomorrow() { } versus const tomorrow = () => { }, but surely that's just a case of being more used to seeing one as opposed to the other? After a day or two, you should adjust to being just as capable of spotting the new pattern... Also, if you're after the functions during a search or regex, replacing function with ) => { is just as good, if not better, as you avoid any comments that happen to have the word function in it.
    – Jack_Hu
    Jul 28, 2020 at 2:38
16

There are some very important benefits to the use of const and some would say it should be used wherever possible because of how deliberate and indicative it is.

It is, as far as I can tell, the most indicative and predictable declaration of variables in JavaScript, and one of the most useful, BECAUSE of how constrained it is. Why? Because it eliminates some possibilities available to var and let declarations.

What can you infer when you read a const? You know all of the following just by reading the const declaration statement, AND without scanning for other references to that variable:

  • the value is bound to that variable (although its underlying object is not deeply immutable)
  • it can’t be accessed outside of its immediately containing block
  • the binding is never accessed before declaration, because of Temporal Dead Zone (TDZ) rules.

The following quote is from an article arguing the benefits of let and const. It also more directly answers your question about the keyword's constraints/limits:

Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future.

Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference.

The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand.

With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.

Source: https://ponyfoo.com/articles/var-let-const

2
  • 14
    This question is about function vs const not var vs const. And this answer itself is an indication that the use of const to define a function is not a readability enhancement and in fact a readability regression in modern JS. Because this answer already confused it for variables, not functions. Oct 8, 2021 at 22:41
  • noone nowadays uses "var" anyway. Those who do are usually beginner or have been sleeping for 20 years.
    – Welcor
    Apr 16, 2023 at 16:48
10

There are special cases where arrow functions just won't do the trick:

  1. If we're changing a method of an external API, and need the object's reference.

  2. If we need to use special keywords that are exclusive to the function expression: arguments, yield, bind etc. For more information: Arrow function expression limitations

Example:

I assigned this function as an event handler in the Highcharts API. It's fired by the library, so the this keyword should match a specific object.

export const handleCrosshairHover = function (proceed, e) {
  const axis = this; // axis object
  proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // method arguments
};

With an arrow function, this would match the declaration scope, and we won't have access to the API obj:

export const handleCrosshairHover = (proceed, e) => {
  const axis = this; // this = undefined
  proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // compilation error
};

0

Existing Answers Summary

  1. Function Declarations vs. Expressions: Emphasizing the differences in hoisting and scope.
  2. Immutability and Arrow Functions: Discussing the benefits of using const for immutability and arrow function syntax.
  3. Readability and Execution Order: Arguing for traditional function declarations due to clarity and natural flow.
  4. Practical Limitations of Arrow Functions: Highlighting situations where traditional functions are necessary, like needing this context or special keywords.
  5. Benefits of const: Focused on predictability and restrictions that improve code understanding.

Gap Identified

None of the answers deeply explore the implications of using const with async functions, particularly in modern JavaScript development where asynchronous operations are common. They also don't address the modular and scalable design patterns that const functions can encourage, especially in large-scale applications.

MyAnswer

Use Case: Async Functions and Modular Design

In modern JavaScript, especially with the prevalence of asynchronous operations (like API calls), defining functions as constants can be particularly advantageous when combined with async/await syntax. This approach not only ensures immutability but also encourages a modular design pattern.

Using const for async functions promotes a clear and concise structure, especially when these functions are exported from a module. It helps in maintaining a consistent coding style across a codebase, particularly in large-scale applications where readability and maintainability are crucial.

Example

// Defining an async function using const
const fetchData = async (url) => {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

// Usage in an async context
const processData = async () => {
    const data = await fetchData('https://api.example.com/data');
    console.log('Received Data:', data);
};

processData();

In this example, fetchData is an asynchronous function defined with const. This ensures that fetchData won’t be accidentally reassigned elsewhere in the code, maintaining the integrity of the function. Additionally, this style aligns well with the modern async/await syntax, providing a clear, promise-based structure for handling asynchronous operations.

Conclusion

While the traditional function declaration has its merits, especially in terms of readability and hoisting behavior, the use of const for defining functions, particularly async functions, offers significant benefits in terms of code stability, modular design, and adherence to modern JavaScript patterns. This approach is highly recommended in scenarios involving asynchronous operations and when working on large-scale applications that require a consistent and maintainable codebase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.