TIL: Improving My JS Code, pt1
As I posted yesterday, I want to start spending some time focusing on making my code a bit cleaner so that it’s a bit better from the start. So today I’m starting to go back through the best practices document I posted yesterday and start implementing some of what they outline
Using computed property names when creating dynamic object properties
This is honestly something that I’ve wanted to know for a loooong time. I guess in theory it might be frowned upon because you don’t know what’s being created for sure, but man… does it make things nice.
Essentially what this allows you to do so create a property in an object with a key set equal to that of one of your variables.
To see what I mean, let’s look at this example:
|
|
Ignoring the fact that this opens yourself up to a can of different problems, let’s look at what it actually does do. A name will be returned by the getKey()
function based on the int that’s passed in. That name that is returned is then set as the key by wrapping it in the brackets []
. Super neat
Defining methods in objects
When defining a method in an object, it’s best to use a shorthand method definition. That is, rather than setting a key equal to a function, simply just define the function right inside the object itself:
|
|
Use property value shortcuts
This is a neat trick that I always forget to use. If you want to assign a property to a variable with the same name as the value, you can simply just put the variable name:
|
|
Don’t call Object.prototype
methods directly
Rather than calling obj.hasOwnProperty(val)
, it’s recommended to actually cache the lookup within the module for faster usage. This makes it clear what’s actually being evaluated, and avoids issues that might come if trying to run the method on something like an empty object:
|
|
Use the object spreader when making shallow copies
This is only when making shallow copies, but it’s recommended to use the spread operator. This can also be used to omit items that you don’t care about:
|
|
💚