In this post, I'll show you 5 neat JavaScript tips that will help you become a better developer. Although this post requires some knowledge of JavaScript, I encourage everyone to read through it.
List of neat tips:
- Destructuring
- Console tips
- Dynamic key names
- Set as a data structure
- Callback-based APIs -> Promises
Destructuring
What a better way to explain something than through an example. Let's imagine we have an object with some tiger data and we need a function that will tell if the tiger is endangered.
const tiger = {
specific: 'Bengal',
latin: 'Panthera tigris tigris',
endangered: true,
weight: 325,
diet: 'fox',
legs: 4
}
// Bad code 💩
function isEndangered(tiger){
if (tiger.endangered) {
return `${tiger.specific} tiger (${tiger.latin}) is endangered!`
} else {
return `${tiger.specific} tiger (${tiger.latin}) is not
endangered.`
}
}
// Good code 👍
function isEndangered({endangered, specific, latin}){
if (endangered) {
return `${specific} tiger (${latin}) is endangered!`;
} else {
return `${specific} tiger (${latin}) is not
endangered.`;
}
}
// or
function isEndangered(tiger) {
const {endangered, specific, latin} = tiger;
// the rest is the same
Console tips
Code execution time ⏲️
Use console.time
and console.timeEnd
to determine how fast (or slow) your code is?
Here's an example:
console.time('TEST')
//some random code to be tested
console.timeEnd('TEST')
Loggin with style 😎
To have a custom output, we'll add %c
like below and then have the actual CSS as the second argument.
console.log('%c AWESOME', 'color: indigo; font-size:100px')
Tables
When you want to log an array of objects console.table
will come in handy.
// x,y,z are objects
console.table([x, y, z])
Stack trace logs
If you want to get the stack trace of where a function is being called you can use console.trace
function foo(){
function bar(){
console.trace('test')
}
bar();
}
foo();
Dynamic key names
A super useful tip!
const key = 'dynamic'
const obj = {
dynamic: 'hey',
[key]: 'howdy'
}
obj.dynamic // hey
obj[key] // howdy
obj['dynamic'] //hey
obj.key // howdy
To see the most often use case of the dynamic-keys concept, check out my previous post.
Set as a data structure
If I'd ask you to remove the duplicates from an array of numbers. How would you do it?
Use Set as a data structure to improve the functionality and performance of your app. Here's an example where I'll remove duplicates from an array of numbers using Set object.
const arr = [1, 2, 2, 3]
const newArr = new Set(arr)
const unique = [...newArr]
// unique - [1, 2, 3]
Callback-based APIs -> Promises
To make things cleaner and more efficient you can transform the callback (ourCallbackFn) into a promise being a function.
// we start with this
async function foo() {
const x = await something1()
const y = await something2()
ourCallbackFn(){
// ...
}
}
// the transformation
async function foo() {
const x = await something1()
const y = await something2()
await promiseCallbackFn() //👀
}
function promiseCallbackFn() {
return new Promise((resolve, reject) => {
ourCallbackFn((err, data) => { //👀
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
This was a list of 5 JavaScript tips. Pretty neat, right?
I hope you find my first post useful! Any feedback is greatly appreciated!
Thank You!
Dalibor
Top comments (24)
May i ask some explanation about the "benefits" of destructuring ?
Destructuring improves speed by accessing members by one time assignment. Every a.b member expression is slower as it travels prototype chain for access.
The argument becomes immutable, reassigning destructred variable will not modify the source.
I don't think this would be true if the destructured key was an object, it would still be by reference.
Overall I agree that destructuring is cleaner though!
Should it print undefined or "Akash"?
In no way destructured variable is by reference. Reassigning destructured variable is immutable (not changing property of object held in destructured variable if it is an object).
Yes, you assigned the string, so no not by reference. If name itself was an object, it would be by reference yea?
Try it and show me a working example.
Sir, please, there is no need to be rude.
(and yes, you will say to do
const { name: { first } } = user
, but pls. Pls. Sir, pls.)In which way the word "Reassigning destructured variable" is similar to
name.first = ...
? The whole purpose of destructuring is not to use member expressionname.first
. And yeslet { name: { first } } = user
is the correct way to use desctructering.user
is immutable here. It is important to note that we can pass an object to a function which will not change the original object if function is written correctly using destructering. JavaScript compiler can also optimize it by knowing that the function is pure.Destructuring in itself doesn't make it immutable. In the example @akashkava where you re-assigned value to "name" variable and it didn't affect the original object is because the variable of type String (or any other primitives) are immutable and not because it is coming from a destructured object.
Your example is same as
which makes it immutable because of the data type. @qm3ster 's example showed that destructured values could be mutated which will mutate the origin object.
Destructuring is just syntactic sugar to provide more readability.
const name = user.name
is same asconst { name } = user
Sure.
I remember once a senior dev told me (I was a junior) that it's not just enough to do something. You have to do it the right way. Destructuring makes our code cleaner and more readable.
Destructuring isn't working "with reference". This could be confusing.
Objects in Javascript are mutables, so if you are destructuring an object which one of it properties is another object, the variable created for that property will point to the same object in the Heap.
I had no idea you could style console.logs, that's amazing!
Yep, pretty neat! :)
In the days of ActionScript we were able to use a "with" statement.. kirupa.com/developer/actionscript/...
Is there something similar in JS?! I wonder.. :)
The callback into Promise one is so handy. It means you can use async await as well which is so much easier to write.
Thx For the tip!
Welcome!
There is a typo. You wrote 'trase' instead of 'trace'. Good article though.
Tnx!
FYI there's a Node.js util that does the promisifying for you, you don't need to write your own. Thanks for sharing!
And a lot of nodejs builtins come in proper promise versions now, not by making you promisify them in userspace!
Hurrah!
obj.key
isundefined
, isn't it ?What if I have 15-20 elements which I need to show in component, is it good / good practice to destructure 20 elements as arguments?
Yes! In that case, I would do the 2nd version: function (tiger) { ... and then inside the function: { endangered, latin, ... } = tiger