Thursday, June 3, 2021

hiding out from the const cops

 So, some of my coworkers are much more fired up about insisting on the use of const for javascript variables than I am. I think it's a bit of a shame, especially because nothing stops you from doing:

const foo = { bar: 123};
foo.bar = 456;

There are different ways of freezing an object like that, but I think people who care about const think of it like a "Poor Man's Immutable". 

So I was surprised when code like this showed up in a Pull Request:

const someFunction = ( { bar } ) => {
    // some other work
    bar = 456;
}

I guess I assumed properties were const... but no. And in fact, there's not a clean syntax for it, that keeps up with the syntactic sugar.

On the WesBos slack domain, A-J Roos says:

You’d have to destructure from the arguments object if you don’t want the variables to be reassigned.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

TypeScript has a readonly type that you can use to define function arguments that cannot be reassigned during development.

https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype

So, huh. 

No comments:

Post a Comment