DEV Community

Cover image for 8 JavaScript Tips & Tricks That No One Teaches πŸš€
Garvit Motwani for World In Dev

Posted on • Updated on

8 JavaScript Tips & Tricks That No One Teaches πŸš€

JavaScript is no doubt one of the coolest languages in the world and is gaining more and more popularity day by day. So the developer community has found some tricks and tips after using JS for quite a while now. Today I will share 8 Tips & Tricks With You!

So let's get started

Functional Inheritance

Functional inheritance is the process of receiving features by applying an augmenting function to an object instance. The function supplies a closure scope which you can use to keep some data private. The augmenting function uses dynamic object extension to extend the object instance with new properties and methods.

They look like:

// Base function
function Drinks(data) {
  var that = {}; // Create an empty object
  that.name = data.name; // Add it a "name" property
  return that; // Return the object
};

// Fuction which inherits from the base function
function Coffee(data) {
  // Create the Drinks object
  var that = Drinks(data);
  // Extend base object
  that.giveName = function() {
    return 'This is ' + that.name;
  };
  return that;
};

// Usage
var firstCoffee = Coffee({ name: 'Cappuccino' });
console.log(firstCoffee.giveName());
// Output: "This is Cappuccino"
Enter fullscreen mode Exit fullscreen mode

Credits to @loverajoel for explaining this topic in depth here - Functional Inheritance on JS Tips which I've paraphrased above

.map() Substitute

.map() also has a substitute that we can use which is .from():

let dogs = [
    { name: β€˜Rio’, age: 2 },
    { name: β€˜Mac’, age: 3 },
    { name: β€˜Bruno’, age: 5 },
    { name: β€˜Jucas’, age: 10 },
    { name: β€˜Furr’, age: 8 },
    { name: β€˜Blu’, age: 7 },
]


let dogsNames = Array.from(dogs, ({name}) => name);
console.log(dogsNames); // returns [β€œRio”, β€œMac”, β€œBruno”, β€œJucas”, β€œFurr”, β€œBlu”]
Enter fullscreen mode Exit fullscreen mode

Number to string/string to number

Usually, to convert a string to a number, we use something like this:

let num = 4
let newNum = num.toString();
Enter fullscreen mode Exit fullscreen mode

and to convert a string to a number, we use:

let num = "4"
let stringNumber = Number(num);
Enter fullscreen mode Exit fullscreen mode

but what we can use to code fast is:

let num = 15;
let numString = num + ""; // number to string
let stringNum = +s; // string to number
Enter fullscreen mode Exit fullscreen mode

Using length to resize and emptying an array

In javascript, we can override a built-in method called length and assign it a value of our choice.

Let's look at an example:

let array_values = [1, 2, 3, 4, 5, 6, 7, 8];  
console.log(array_values.length); 
// 8  
array_values.length = 5;  
console.log(array_values.length); 
// 5  
console.log(array_values); 
// [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

It can also be used in emptying an array, like this:

let array_values = [1, 2, 3, 4, 5, 6, 7,8]; 
console.log(array_values.length); 
// 8  
array_values.length = 0;   
console.log(array_values.length); 
// 0 
console.log(array_values); 
// []
Enter fullscreen mode Exit fullscreen mode

Swap Values with Array Destructuring.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. We can also use that to swap values fast, like this:

let a = 1, b = 2
[a, b] = [b, a]
console.log(a) // result -> 2
console.log(b) // result -> 1
Enter fullscreen mode Exit fullscreen mode

Remove duplicates from an Array

This trick is pretty simple. Let's say, I made an array that is containing numbers, strings, and booleans, but the values are repeating themselves more than once and I want to remove the duplicates. So what I can do is:

const array = [1, 3, 2, 3, 2, 1, true, false, true, 'Kio', 2, 3];
const filteredArray = [...new Set(array)];
console.log(filteredArray) // [1, 3, 2, true, false, "Kio"]
Enter fullscreen mode Exit fullscreen mode

Short For Loop

You can write less code for a loop like this:

const names = ["Kio", "Rio", "Mac"];

// Long Version
for (let i = 0; i < names.length; i++) {
  const name = names[i];
  console.log(name);
}

// Short Version
for (let name of names) console.log(name);
Enter fullscreen mode Exit fullscreen mode

Performance

In JS you can also get the time that the code was executed in like Google does:

google example

It looks like this:

const firstTime = performance.now();
something();
const secondTime = performance.now();
console.log(`The something function took ${secondTime - firstTime} milliseconds.`);
Enter fullscreen mode Exit fullscreen mode

⚑️ Giveaway ⚑️

We are giving away any course you need on Udemy. Any price any course.
Steps to enter the giveaway
--> React to this post
--> Subscribe to our Newsletter <-- Very important
--> Follow me on Twitter <-- x2 Chances of winning

The winner will be announced on May 1, Via Twitter


Thank you very much for reading this article.

Comment any tricks & tips you know!

PLEASE LIKE, SHARE, AND COMMENT

Follow me on Dev and Twitter

Oldest comments (80)

Collapse
 
afif profile image
Info Comment hidden by post author - thread only accessible via permalink
Temani Afif

can you please remove the CSS tag since this post is not about CSS? thanks

Collapse
 
garvitmotwani profile image
Garvit Motwani

Ya sorry actually I wrote it before because I wanted to create a CSS post πŸ˜… thanks for the reminder

Collapse
 
buriti97 profile image
buridev

awesome bro, thanks for sharing

Collapse
 
garvitmotwani profile image
Garvit Motwani

Welcome Bro!! πŸ™

Collapse
 
ignaciojvig profile image
Info Comment hidden by post author - thread only accessible via permalink
JoΓ£o Victor Ignacio

Thanks for sharing Garvit! About your first topic, Functional Inheritance, I don't actually agree with what you've said. Since the idea is to hide the object within a function, it kinda works, BUT, that's totally different from the concept of 'private' as data encapsulation. You can still get the object and do whatever you want. All that you doing there is hiding an object inside another, and then retrieving it. Also, be careful when using 'var', especially when talking about concepts like hoisting and closures. Your variables were actually globally scoped and their memory will not be immediatly freed after using that function.

Collapse
 
garvitmotwani profile image
Garvit Motwani

Thanks For Sharing The Tip! Noted!

Collapse
 
geminii profile image
Jimmy

Really nice tips.
Question : what is the best option between using performance.now() and console.time() πŸ€”

Collapse
 
garvitmotwani profile image
Garvit Motwani

I usually use performance.now() so I would recommend that but console.time() is also good!!

Collapse
 
sebring profile image
J. G. Sebring

console.time will be limited to output in console, hence it is more suitable for temporary debugging/test situations.

Any other cases I'd use performance.now, like displaying time in html, sending to backend etc.

Collapse
 
geminii profile image
Jimmy

Good to know thanks for this tip πŸ˜€πŸ‘

Collapse
 
davidsanwald profile image
Info Comment hidden by post author - thread only accessible via permalink
David Sanwald

Map an array without .map()

Pick one. You can't say one is difficult and complicated and nobody will understand it.
And the other one is surprising, rarely taught or known but way easier to understand?

Collapse
 
garvitmotwani profile image
Garvit Motwani

Actually, I really like that method and it is way easier than .map(), that's why I recommended that, but noted! Thanks for reading the article

Collapse
 
nickjohnmorton profile image
Nick Morton

Please explain how your method is "way easier than .map()"?

I just don't understand your thinking here, the concepts are exactly the same, the syntax is almost exactly the same (actually longer), and you're introducing a somewhat unfamiliar syntax to most to achieve something that everyone likely understands already with .map().

Collapse
 
vikirobles profile image
Vicky Vasilopoulou

thanks for sharing Garvit!

Collapse
 
garvitmotwani profile image
Garvit Motwani

welcome bro!

Collapse
 
devtalhaakbar profile image
Muhammad Talha Akbar • Edited

Great, Garvit! It's always great to know the language so well and bring about these unconventional ways to solve problems. However, it's always recommended to write code that is self-explanatory. And, I find majority of these tricks to be confusing (to an average eye). Use them when you really have to and leave a comment to make your intention clear.

Collapse
 
garvitmotwani profile image
Garvit Motwani

Noted! and thanks for reading the article!

Collapse
 
strativd profile image
Strat Barrett

On that note – which I completely agree with – it's interesting how readable this is Array.from(dogs) compared to dogs.map() if map wasn't so widely adopted :)

Collapse
 
arealsamurai profile image
An actual, Real Samurai • Edited

On that note, I'd love to see how performant Array.from() is compared to .map() that I know doesn't perform very well

Thread Thread
 
killshot13 profile image
Michael R.

Now you've inspired a more ambitious project. Building a custom standalone performance measurement tool for Javascript.

It could be something similar to Runkit, but strictly for benchmarking the various methods and approaches to the same end goal. Like which is faster?

capsLockNames = names.map(capitalize)
Enter fullscreen mode Exit fullscreen mode

OR

capsLockNames= []
for x = 0; x < names.length; x++
  capsLockNames[x] = capitalize(names[x]))
Enter fullscreen mode Exit fullscreen mode

πŸ€”πŸ€”πŸ€”

Thread Thread
 
arealsamurai profile image
An actual, Real Samurai

I can tell you for sure that the for loop is way more performant than map. But if you do compare everything, I'm definitely interested to read.

Collapse
 
yobretyo profile image
Bret

The problem with JavaScript is that.... it’s not taught β€œin context”, it’s mainly always a β€œconsole.log” that is used for the answer, instead of truly implementing it into real examples.... it’s been tough for me to learn it

Collapse
 
garvitmotwani profile image
Garvit Motwani

Ya

Collapse
 
vicropht profile image
Vicropht

Make projects to learn it! Helps a lot!!!

Collapse
 
killshot13 profile image
Michael R.

Liquid syntax error: Tag '{%' was not properly terminated with regexp: /\%\}/

Collapse
 
shadowtime2000 profile image
Info Comment hidden by post author - thread only accessible via permalink
shadowtime2000

8 JavaScript Tips & Tricks That No One Teaches πŸš€

This title makes it seem like these are tips and tricks worthwhile to use that are not that popular but extremely useful.

Most of these tips are actually well known among JS developers and aren't ones "That No One Teaches", such as the performance tip, the short for loop, using sets to remove duplicates from arrays, and swapping values with destructuring. The only ones that aren't as known are the first couple, which don't seem to be that useful.

Sorry, if that sounds rude because that isn't my intention. I am just trying to point out that most of these tips are either well known or not useful and the title is pretty misleading then.

Collapse
 
garvitmotwani profile image
Garvit Motwani

Noted

Collapse
 
johannchopin profile image
johannchopin

You're right and I like your avatarπŸ‘

Collapse
 
garvitmotwani profile image
Garvit Motwani

Thanks! I don’t remember how I created that

Collapse
 
juniordevforlife profile image
Jason F

Great article. I'm particularly fond of the map without map.

Collapse
 
garvitmotwani profile image
Garvit Motwani

Ya I use that at often nowadays

Collapse
 
tryhendri profile image
tryhendri

Thanks for sharing Garvit
It seems a typo on Map an array without .map(), it should return dogsNames rather than friendsNames.

Collapse
 
garvitmotwani profile image
Garvit Motwani

Noted! Thanks!

Collapse
 
ychanov profile image
Yavor Chanov

Hi, thanks for the article.
I think there is a small mistake in the "Number to string/string to number" part...
The example for converting string to number is:
let num = "4"
let stringNumber = Number(s); //doesn't that have to be Number(num);?

Collapse
 
garvitmotwani profile image
Garvit Motwani

Welcome and Noted!!

Collapse
 
coderdaiyan profile image
Abdallah Daiyan

For me remove duplicates in an array was interesting.....past I removed in another way. It seems like this is so easy....Thank you so much man...It was awesome πŸš€πŸ”₯

Collapse
 
garvitmotwani profile image
Garvit Motwani

Welcome Bro!!

Collapse
 
bmehder profile image
Brad Mehder

I found this article super useful!

Collapse
 
garvitmotwani profile image
Garvit Motwani

Thanks For Reading!!

Collapse
 
garvitmotwani profile image
Garvit Motwani

It varies from person to person like you like it but I personally find it sometimes complicated so I listed it in but thanks for the suggestion!!

Some comments have been hidden by the post's author - find out more