In this article I will share with you some news tips about JS that can improve your skills!
Don't use delete
to remove property
delete
is very bad to remove a property from an object (bad performance), moreover it will create a lot of side effects.
But what you should do if you need to remove a property?
You need to use Functional approach and create a new object without this property. You can manage to do this with a function like this π
const removeProperty = (target, propertyToRemove) => {
// We split the property to remove from the target in another object
const { [propertyToRemove]: _, ...newTarget } = target
return newTarget
}
const toto = { a: 55, b: 66 }
const totoWithoutB = removeProperty(toto, 'b') // { a: 55 }
A very simple snippet that will help you a lot!
Add a property to an object only if it exists
Sometimes we need to add a property to an object if this property is defined. We can make something like this π
const toto = { name: 'toto' }
const other = { other: 'other' }
// The condition is not important
const condition = true
if (condition) {
other.name = toto.name
}
β It's not very good code anyway...
β
You can use something more elegant!π
// The condition is not important
const condition = true
const other = {
other: 'other',
...condition && { name: 'toto' }
}
For more explication about spread operator on boolean: https://dev.to/codeoz/comment/1ib4g
If the condition is true, you add the property to your object (it work thanks to the &&
operator)
I could also make this π
// The condition is not important
const condition = true
const toto = { name: 'toto' }
const other = {
other: 'other',
...condition && toto
}
Use template literal string
When we learn strings in javascript and we need to concat them with variable we code something like π
const toto = 'toto'
const message = 'hello from ' + toto + '!' // hello from toto!
β It can become garbage if you add other variables and string!
You can use template literal string
You just need to replace simple or double quotes by back-tick.
And wrap all variables by ${variable}
const toto = 'toto'
const message = `hello from ${toto}!` // hello from toto!
Short-circuits conditionals
If you have to execute a function just if a condition is true, like π
if(condition){
toto()
}
You can use a short-circuit just like π
condition && toto()
Thanks to the &&
(AND) operator, if the condition is true, it will execute toto function
Set default value for variable
If you need to set a default value to a variable
let toto
console.log(toto) //undefined
toto = toto ?? 'default value'
console.log(toto) //default value
toto = toto ?? 'new value'
console.log(toto) //default value
Thanks to the ??
(Nullish coalescing) operator, if the first value is undefined or null, it will assign the default value after the (??
)!
Use console timer
If you need to know the execution time of a function for example you can console timer. It will give you back the time before and after the execution of your function very fastly!
console.time()
for (i = 0; i < 100000; i++) {
// some code
}
console.timeEnd() // x ms
I hope you like this reading!
π You can get my new book Underrated skills in javascript, make the difference
for FREE if you follow me on Twitter and MP me π
Or get it HERE
π«π·π₯ For french developper you can check my YoutubeChannel
π MY NEWSLETTER
βοΈ You can SUPPORT MY WORKS π
πββοΈ You can follow me on π
π Twitter : https://twitter.com/code__oz
π¨βπ» Github: https://github.com/Code-Oz
And you can mark π this article!
Top comments (28)
I understand the objective and the reasoning behind the suggestions, but we shouldn't be totally against the usage of
delete
.It can still be useful in situations where you absolutely need to remove a property from an object before an operation, and the object will no longer be used after this operation.
In this case, personally it seems to be a lot more straightforward than the functional approach you've described. Thoughts?
If you absolutely need to remove a property from an object before an operation and the object will no longer be used after this operation. Why don't use a new object that will no have this property instead of delete it from the original object? If you have any things that depend on this property you will create bug and side effects! If you create a new one, you will not :D
What's the problem with using "splice" to delete an element from an array? Works even in ES5, and I can't imagine that the "functional" approach (in essence copying the whole array except one element) would be faster ...
once you work with pure functions, and data is being transformed and used in a long sequence of functions, moving to store, to state, to helpers... functions that are changing "in place" arrays are very dangerous. Splice, Sort, Push, Pop, Unshift... they need to be used only in the "data formation" phase, but never as part of any data transformation, as they will lead to side effects very fast
Yeah but the point of the original author was that "delete" is slow, and therefore you need to use the approach that he proposed ... to which I replied "what if you don't use delete but splice", probably the argument about performance goes away then.
The FP (functional programming/immutable) approach is cool, but there's still a legit case to be made for the old fashioned way - it's only "dangerous" if you do it wrong, heaps of code are written this way which are perfectly fine.
I said "dangerous" and not "forbidden for any case". Every rule has some exceptions. It's always dangerous to modify arrays in place, that's why it needs double attention, very nice test coverage, and a lot of edge cases coverage, and a good programming team behind.
In this article there is a kind of "show off some syntax hacks", which IMHO opinion, some are hard to read, some are dangerous, especially for immature programmers, and some are "please read Ecma Script latest changes and don't be so cocky" :D
Haha agreed, especially the second paragraph ;)
The techniques in this article are okay-ish, but I'm not blown away if I may put it like that.
is it destructing of boolean variable?
can you help point from where you learnt this? MDN/other?
Thanks
I will divide the answer in two parts to be more clearly!
First it's not destructing but spread operator.
When you use spread for example ->
const toto = { ...anotherObject }
it's a shortcut ofconst toto = Object.assign({}, anotherObject)
Js engine will check all enumerable property (it's like when you make a for...in loop on an object or Object.entries()), for example ->
Object.entries(anotherObject)
and put all key/value to the new object!So now let's get the example from the article.
In case of condition is
true
, JS engine will check the expression, and see that condition is true so it will go to{ name: 'toto' }
. And then we add all property from this object (here name: toto) to the other object.In case of condition is
false
, JS engine will try to do thisObject.assign({}, condition)
but condition is a boolean, not an object! So it will convert it (in really case wrapping it) to an object like thisnew Boolean(false)
. So it will create a boolean object, but this boolean object don't have any enumerable properties! So Js will make thisObject.entries(booleanObject) = []
so it add 0 property to the new object!It not really easy to understand, I will take another example
Imagine this code
const toto = { ...'hello' }
JS Engine will make thisObject.assign({}, new String('hello'))
when you makeObject.entries(new String('hello'))
you will have a list of all value key/pair, and with a string object you will have a value for each char, so JS engine will add all property (except length) to the new object so we will havetoto = {0: 'h', 1: 'e', 2: 'l', 3: 'l', 4: 'o'}
hey I'm looking for the article that explain it! Share it after ;D
I'm agree that short circuit should not be abuse! I love ternary but it cannot be applied in all case!
For the operator I am totally agree that
??
(Nullish coalescing) should be replace by the OR Operator, I made this change thank you a lot LUKE !I agree with some of the suggestions here maybe smart looking but certainly do not make for more readable code, maybe a developer comes to new project and doesn't know the "tricks" of syntax, they would waste time googling what on earth it means and googling syntax tricks is difficult in itself.
Unless they offer significant speed enhancement or use need them for extreme optimization these are more confusing than useful.
Thanks for your comment!
I was this guys that you speak when I come in my first job! I take a few time to understand but when I understand all, I was happy to see that it improve code quality!
It's why I'm trying to help people to understand and know those 'tricks'!
I assume that is not a reason to abuse it!
Good one! Although I personally prefer to avoid short-circuits for that very specific example.
The if block enhances readability and also allows for future modifications easily.
I prefer this approach also! It's more readable, but I have already have discussions with other dev that like this short-circuits π
Hey I miss I mean "side effects " π ! I think benchmark is not the good approach about this, the focus is on "side effect" that can be leads by
delete
operator. In general in programming we don't encourage people to remove property from a current object since some "logic" can be linked to this property and lead to bug.For the example you highlight, I mean that the
if
condition can be avoid, so we should avoid it when we can. In this case we have only one condition and only one property. Imagine that we need to add 10 properties with 10 conditions differents, you will use 10if
?I'm agree that short circuit don't need to be abusing but it can lead to less DRY (don't repeat yourself).
What's the reason for
...condition && { ...toto }
instead of...condition && toto
?Just edit it ! thank you I miss it π
Thanks
happy to help you bro!
Congrats.
We need to pen attention that when create dynamic objects, it can influently directly in v8 optimizations.
totally agree and thanks :D