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

Latest comments (80)

Collapse
 
sinvalfelisberto profile image
Sinval Felisberto

Thank you Kindly, Garvit!
Greetings from Brazil!

Collapse
 
bendavies99 profile image
Ben Davies

Hey quick question when changing the length of the array to remove items from the array does this not cause a memory leak because of how arrays are stored, or does the garbage collector understand this change and then clean up the memory as necessary

Collapse
 
filatovv profile image
Yuri Filatov

This is an amazing job!

Collapse
 
iqseviyesi profile image
IQ Seviyesi

Perfect tricks :)

Collapse
 
kasia99472765 profile image
Kasia

it`s ok

Collapse
 
ecemac profile image
Ece

Daaamn, this is very useful.

Collapse
 
mliakos profile image
Emmanouil Liakos

Another nice tip is that arrays passed to template literals get coerced to comma-separated strings like this:

const fruits = ['apples', 'oranges'];
console.log(${fruits}); // 'apples,oranges'

Collapse
 
macnick profile image
Nick Haralampopoulos

Nice article Garvit! I usually use the .map() substitute when creating arrays with pre-filled values. One little mistake though. array.length is a property in JavaScript not a method. It is a method in Java, C++ and others but not in JavaScript.
developer.mozilla.org/en-US/docs/W...
Thank you again for the nice article.

Collapse
 
thangdangblog profile image
thangdangblog

Thank you for sharing! Your post helps me improve my skills in Javascript!

Collapse
 
cubiclesocial profile image
cubiclesocial

We can also use that to swap values fast

Swapping variables with an array isn't going to be faster (performance-wise) than just swapping the variables with the traditional method of using a temporary variable.

stackoverflow.com/questions/162016...

One of the first comments on using a temporary array is that it is roughly two times slower than a variable swap.

Javascript processes most accesses by reference. So assigning to a temporary variable doesn't copy anything but a memory address. Creating an array, on the other hand, is almost certainly going to: Hit the memory allocation pool, add two variables to the array, update the length of the array (for no good reason), then immediately extract them back out of the array, and release the array back into the memory pool. Without even having to test that, the former is obviously faster than the latter. Swapping vars happens often in software, and usually in a loop, so writing performant code vs. one-liners is more important here.

Collapse
 
g0d profile image
George Delaportas (ViR4X)

G R E A T work...

There are also many other great tricks you can do to optimize code, add quality and also provide C#-like or JAVA-like paradigms to JavaScript.

Check my web framework and especially the JS extensions for more cool ideas.

github.com/g0d/micro-MVC
github.com/g0d/micro-MVC/tree/mast...

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

Some awesome tips, thank you!

Not sure if I like overriding length with a constant value of 0 with the intention of emptying an array.

Maybe the garbage collection in JavaScript is awesome and we shouldn't worry about abandoned bits of memory, but to me this really feels like being a spoiled brat that keeps their room like a dumpster just because the family employs a maid who can clean up after them.

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

Hey Garvit, how long it took to copy the content of the first paragraph from here: jstips.co/en/javascript/what-is-a-... ?

Collapse
 
as profile image
Amir Salehi

Nice πŸ‘

Collapse
 
heatxel profile image
Danz

Love it thanks great tricks

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