DEV Community

Cover image for Improve your JS skills with those tips #2
Code Oz
Code Oz

Posted on • Edited on

Improve your JS skills with those tips #2

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 }
Enter fullscreen mode Exit fullscreen mode

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 
}
Enter fullscreen mode Exit fullscreen mode

❌ 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' }
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

❌ 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!
Enter fullscreen mode Exit fullscreen mode

Short-circuits conditionals

If you have to execute a function just if a condition is true, like πŸ‘‡

if(condition){
    toto()
}
Enter fullscreen mode Exit fullscreen mode

You can use a short-circuit just like πŸ‘‡

condition && toto()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
matheusgoncalves profile image
Matheus Goncalves

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?

Collapse
 
codeoz profile image
Code Oz

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

Collapse
 
leob profile image
leob

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 ...

Collapse
 
silverium profile image
Soldeplata Saketos

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

Collapse
 
leob profile image
leob

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.

Thread Thread
 
silverium profile image
Soldeplata Saketos

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

Thread Thread
 
leob profile image
leob

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.

Collapse
 
manoharreddyporeddy profile image
Manohar Reddy Poreddy • Edited
const condition = true
const other = {
   other: 'other',
   ...condition && { name: 'toto' }
}
Enter fullscreen mode Exit fullscreen mode

is it destructing of boolean variable?
can you help point from where you learnt this? MDN/other?
Thanks

Collapse
 
codeoz profile image
Code Oz

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 of const 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 this Object.assign({}, condition) but condition is a boolean, not an object! So it will convert it (in really case wrapping it) to an object like this new Boolean(false). So it will create a boolean object, but this boolean object don't have any enumerable properties! So Js will make this Object.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 this Object.assign({}, new String('hello')) when you make Object.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 have toto = {0: 'h', 1: 'e', 2: 'l', 3: 'l', 4: 'o'}

Collapse
 
codeoz profile image
Code Oz

hey I'm looking for the article that explain it! Share it after ;D

Collapse
 
codeoz profile image
Code Oz

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 !

Collapse
 
justummar profile image
Justummar

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.

Collapse
 
codeoz profile image
Code Oz

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!

Collapse
 
ihton profile image
IhToN

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.

Collapse
 
codeoz profile image
Code Oz

I prefer this approach also! It's more readable, but I have already have discussions with other dev that like this short-circuits πŸ˜†

Collapse
 
codeoz profile image
Code Oz

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 10 if?

I'm agree that short circuit don't need to be abusing but it can lead to less DRY (don't repeat yourself).

Collapse
 
nickmessing profile image
Nick Messing

What's the reason for ...condition && { ...toto } instead of ...condition && toto?

Collapse
 
codeoz profile image
Code Oz

Just edit it ! thank you I miss it πŸ˜ƒ

Collapse
 
ayabouchiha profile image
Aya Bouchiha

Thanks

Collapse
 
codeoz profile image
Code Oz

happy to help you bro!

Collapse
 
leandroandrade profile image
Leandro Andrade

Congrats.

We need to pen attention that when create dynamic objects, it can influently directly in v8 optimizations.

Collapse
 
codeoz profile image
Code Oz

totally agree and thanks :D