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!

Oldest comments (28)

Collapse
 
majscript profile image
MajScript

Like it !

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

Collapse
 
emmaisa59135261 profile image
Emma Isabella

Nice

Collapse
 
codeoz profile image
Code Oz

thank you Emma :D

Collapse
 
ayabouchiha profile image
Aya Bouchiha

Thanks

Collapse
 
codeoz profile image
Code Oz

happy to help you bro!

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
 
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
 
jzombie profile image
jzombie

Nice article!

Small suggestion: "these" is misspelled in the subject title

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

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

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'}