DEV Community

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

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

Garvit Motwani on April 06, 2021

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

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
 
garvitmotwani profile image
Garvit Motwani β€’

Noted! and thanks for reading the article!

Collapse
 
davidsanwald profile image
David Sanwald β€’
Comment hidden by post author
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
 
shadowtime2000 profile image
shadowtime2000 β€’
Comment hidden by post author
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
 
garvitmotwani profile image
Garvit Motwani β€’

Noted

Collapse
 
sonterix profile image
Nick β€’ β€’ Edited

Also, u can convert number to string in this way:

const num = 32
const str = `${32}`
Enter fullscreen mode Exit fullscreen mode
Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

That is interesting and thanks for sharing!!

Collapse
 
aalencar profile image
Alex Alencar β€’

or

num + ''

Collapse
 
sonterix profile image
Nick β€’

This method described in the article :/

Collapse
 
vladimirc profile image
Vladimir C β€’

I believe you meant

const str = `${num}`
Enter fullscreen mode Exit fullscreen mode
Collapse
 
peerreynders profile image
peerreynders β€’

Array.from is notable for its intended use of making Array-like data iterable with array methods, such as strings.

There's another case where it is extremely handy - creating a fresh array with elements initialized from a function.

const init = (_value, index) => (index + 1) * 3;
const length = 4;
const array = Array.from({ length }, init); // [3, 6, 9, 12]
for (let i = 0; i < length; i += 1) console.assert(array[i] === (i + 1) * 3);
Enter fullscreen mode Exit fullscreen mode

The issue with Array.prototype.fill() is that:

  • it requires an existing array (to modify)
  • it only places a single constant value into all the elements it replaces.

And Array.prototype.map() requires an already initialized array.

With Array.from() an array can be created and initialized with element content that varies by index in one fell swoop.

Collapse
 
lkarabeg profile image
lkarabeg β€’

I kind of disagree, finding map much more readable.
Array.from({length: 4}).map((_value, index) => (index + 1) * 3)

Thread Thread
 
peerreynders profile image
peerreynders β€’

With

const array = (new Array(length)).fill().map(init);
Enter fullscreen mode Exit fullscreen mode

it always ground my gears that to arrive at the desired array another disposable array had to be created and "filled" just to convey that I want length elements. And

const array = (new Array(length)).fill();
array.forEach((_v, i, a) => {
  a[i] = (i + 1) * 3;
});
Enter fullscreen mode Exit fullscreen mode

was clunky enough to make me want to use a for loop.

So if I'm are already using Array.from() I might as well use the optional mapFn and thisArg parameters.

function init(_value, index) {
  return (index + 1) * this.factor;
}

const config = { length: 4 };
const two = { factor: 2 };
const three = { factor: 3 };
const array2 = Array.from(config, init, two);
const array3 = Array.from(config, init, three);

const checkArray = (expected, actual) => {
  const actualMatches = (value, index) => value === actual[index];
  console.assert(
    expected.length === actual.length && expected.every(actualMatches),
    'array mismatch - expected: %o actual: %o',
    expected,
    actual
  );
};
const TWOS = [2, 4, 6, 8];
const THREES = [3, 6, 9, 12];
checkArray(TWOS, array2);
checkArray(THREES, array3);
Enter fullscreen mode Exit fullscreen mode

... but that's just me.

Collapse
 
lmorchard profile image
Les Orchard β€’ β€’ Edited

I'd say that Array.from() isn't the most handy as a substitute for Array.map(). Rather, it's handy for transforming iterables that aren't already arrays.

Like, to get the names of commenters on this page, try this in the dev tools console:

Array.from(
  document.querySelectorAll('.js-comment-username'),
  el => el.textContent
)
Enter fullscreen mode Exit fullscreen mode

The NodeList returned from document.querySelectorAll isn't an array, but this lets you convert it to an array while performing a transformation at the same time.

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
 
killshot13 profile image
Michael R. β€’

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

Collapse
 
vicropht profile image
Vicropht β€’

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

Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

Ya

Collapse
 
strativd profile image
Strat Barrett β€’

I'm a big fan of !! which gets the boolean value of (pretty much) anything:

let truthiness = !!12       //=> true
let truthiness = !!0        //=> false
let truthiness = !!'string' //=> true
let truthiness = !!''       //=> false
// BUT LOOK OUT FOR OBJECTS... πŸ‘€
let truthiness = !![]       //=> true
let truthiness = !!{}       //=> true
Enter fullscreen mode Exit fullscreen mode

! is the opposite so !! becomes the boolean value !! πŸ˜„

Collapse
 
parkio profile image
Chris β€’

The Boolean() constructor is another great way to interpret falsey values.

Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

Thanks for sharing! πŸ™πŸ™

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
 
dannyengelman profile image
Danny Engelman β€’
Comment hidden by post author
Collapse
 
crimsonmed profile image
MΓ©dΓ©ric Burlet β€’

for performance you use dates but since you are using console.log you could use console.time()

console.time("track");
// do stuff
console.timeEnd("track")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
afif profile image
Temani Afif β€’
Comment hidden by post author
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
 
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
 
ignaciojvig profile image
JoΓ£o Victor Ignacio β€’
Comment hidden by post author
Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

Thanks For Sharing The Tip! Noted!

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
 
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
 
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
 
rohitw3code profile image
RohitW3code β€’

Very nice , I have a request for you can you publish you articles on our Codeddit Programmer Community it would be a great help to everyone on Codeddit app platform.
play.google.com/store/apps/details...

Collapse
 
lavigi profile image
eva β€’
Comment hidden by post author
Collapse
 
geminii profile image
Jimmy β€’

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

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
 
garvitmotwani profile image
Garvit Motwani β€’

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

Collapse
 
kasia99472765 profile image
Kasia β€’

it`s ok

Collapse
 
buriti97 profile image
buridev β€’

awesome bro, thanks for sharing

Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

Welcome Bro!! πŸ™

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
 
thangdangblog profile image
thangdangblog β€’

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

Collapse
 
as profile image
Amir Salehi β€’

Nice πŸ‘

Collapse
 
heatxel profile image
Danz β€’

Love it thanks great tricks

Collapse
 
abohalema98 profile image
Mohamed Ahmed β€’

thanks for this nots

Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

Welcome bro!

Collapse
 
nol166 profile image
John McCambridge β€’

This is awesome

Collapse
 
bacchusplateau profile image
Bret Williams β€’

Removing duplicates is a good trick. I'll put that one in my back pocket for later.

Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

Yep! Thanks For Reading the articleπŸ™

Collapse
 
jpotts7 profile image
jpotts7 β€’

Great tips - thanks for sharing!

Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

Welcome bro!!

Collapse
 
jobez profile image
Giovanni Bezicheri β€’

Thanks for the article! Anyway some of those are just tricks that could sacrifice code readibility :)

Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

Ya some of them! Thanks for reading tho!

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
 
vikirobles profile image
Vicky Vasilopoulou β€’

thanks for sharing Garvit!

Collapse
 
garvitmotwani profile image
Garvit Motwani β€’

welcome bro!

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

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
 
sinvalfelisberto profile image
Sinval Felisberto β€’

Thank you Kindly, Garvit!
Greetings from Brazil!

Collapse
 
ecemac profile image
Ece β€’

Daaamn, this is very useful.

Collapse
 
nikhilroy2 profile image
Nikhil Chandra Roy β€’

Array.from({length: 10}, (a,b)=> console.log(b)) instant of for loop, Thanks

Collapse
 
damiannelus profile image
damiannelus β€’
Comment hidden by post author

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