DEV Community

loading...
Cover image for 17 Pro JavaScript tricks you didn't know

17 Pro JavaScript tricks you didn't know

rahxuls profile image Rahul ・3 min read

There are many ways to write code but generally the first way for many people is very long and can take you some time. Here is my latest post that will increase your efficiency and productivity when coding JavaScript.


JavaScript : Tricks You Should Know

The ternary operator

Noobs:

let hungry = true;
let eat; 
if (hungry == true) {
       eat = 'yes'; 
} else {
       eat = 'no';
}
Enter fullscreen mode Exit fullscreen mode

Pro:

let hungry = true;
let eat = hungry == true ? 'yes' : 'no';
Enter fullscreen mode Exit fullscreen mode

Number to string / string to number

Noobs:

let num = 15; 
let s = num.toString(); // number to string
let n = Number(s); // string to number
Enter fullscreen mode Exit fullscreen mode

Pro:

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

Populating an array

Noobs:

for(let i=0; i < arraySize; i++){
       filledArray[i] {'hello' : 'goodbye'};
}
Enter fullscreen mode Exit fullscreen mode

Pro:

let filledArray = new Array(arraysize).fill(null).map(()=> ({'hello' : 'goodbye'}));
Enter fullscreen mode Exit fullscreen mode

Dynamic properties in objects

Noobs:

let dynamic = "value"; 
let user = {
     id: 1,
};
user[dynamic] = "other value"; 
Enter fullscreen mode Exit fullscreen mode

Pro:

let dynamic = "value"; 
let user = {
    id: 1,
    [dynamic] = "other value"
};
Enter fullscreen mode Exit fullscreen mode

Read more => 3 Steps to learn a programming language

Removing duplicates

Noob:

let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = [];
let flag = false; 
for (j = 0; < array.length; j++) {
   for (k = 0; k < outputArray.length; k++) {
      if (array[j] == outputArray[k]) {
         flag = true;
       }
    }
    if (flag == false) {
      outputArray.push(array[j]);
     }
     flag = false;
}
//outputArray = [100, 23, 67, 45]

Enter fullscreen mode Exit fullscreen mode

Pro:

let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = Array.from(new Set(array)); 
//outputArray = [100, 23, 67, 45]
Enter fullscreen mode Exit fullscreen mode

Array to object

Noob:

let arr = ["value1", "value2", "value3"]; 
let arrObject = {};
for (let i = 0; i < arr.length; ++i) {
   if (arr[i] !== undefined) {
     arrObject[i] = arr[i];
   }
}
Enter fullscreen mode Exit fullscreen mode

Pro:

let arr = ["value1", "value2", "value3"]; 
let arrObject = {...arr}; 
Enter fullscreen mode Exit fullscreen mode

Read more => A guide to Geolocation API

Object to Array

Noob:

let number = {
  one: 1, 
  two: 2,
};
let keys = []; 
for (let numbers in numbers) {
  if (number.hasOwnProperty(number)) {
     keys.push(number);
    }
}
// key = [ 'one', 'two' ]
Enter fullscreen mode Exit fullscreen mode

Pro:

let number = {
  one: 1, 
  two: 2,
};
let key = Object.keys(numbers); // key = [ 'one', 'two' ]
let value = Object.values(numbers);  // value = [ 1, 2 ]
let entry = Object.entries(numbers); // entry = [['one' : 1], ['two' : 2]]
Enter fullscreen mode Exit fullscreen mode

Short circuit conditionals

Noob:

if (docs) {
    goToDocs();
}
Enter fullscreen mode Exit fullscreen mode

Pro:

docs && goToDocs()
Enter fullscreen mode Exit fullscreen mode

Read more => "use strict" in JavaScript

Use ^ to check if numbers are not equal

if(a!=123) // before // NOOBS

if(a^123) // after // PRO
Enter fullscreen mode Exit fullscreen mode

Loop over an object

const age = {
   Rahul: 20,  
   max: 16
};

// Solution 1 - Get 'keys' and loop over
const keys = Object.keys(age); 
keys.forEach(key => age[key]++);

console.log(age); // { Rahul: 21, max: 16 }

// Solution 2 - for ..in loop
for(let key in age){
   age[key]++;
}

console.log(age); // { Rahul: 22, max: 18 }
Enter fullscreen mode Exit fullscreen mode

Object keys are stored in insertion order

cosnt obj = {
  name: "Rahul", 
  age: 16, 
  address: "Earth", 
  profession: "Developer", 
}; 

console.log(Object.keys(obj)); // name, age, address, profession
Enter fullscreen mode Exit fullscreen mode

Check if value is an array

const arr = [1, 2, 3]; 
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true
Enter fullscreen mode Exit fullscreen mode

Initialize an array of size n and fill with default values

const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

Truthy and False values

False values => false, 0, ""(empty string), null, undefined, &NaN.

Truthy values => "Values", "0", {}(empty object), &[](empty array)


Difference between double equal and triple equal

// Double equal - Converts both the operands to the same type and then comapares
console.log(0 == 'o'); // true

// Triple Equal - Does not convert t same type
console.log(0 === '0'); // false
Enter fullscreen mode Exit fullscreen mode

Better way to accept arguments

function downloadData(url, resourceId, searchTest, pageNo, limit) {}

downloadData(...); // need to remember the order
Enter fullscreen mode Exit fullscreen mode

Simpler way to do:

function downloadData(
{ url, resourceId, searchTest, pageNo, limit } = {}
) {}

downloadData(
  { resourceId: 2, url: "/posts", searchText: "WebDev" }
);
Enter fullscreen mode Exit fullscreen mode

null vs undefined

null => It is a value whereas undefined is not.

null is like an empty box and undefined it not box at all.

const fn = (x = 'default value') => console.log(x);

fn(undefined); // default value
fn(); // default value

fn(null); // null
Enter fullscreen mode Exit fullscreen mode

When null is passed, the default value is not taken. Whereas, when undefined or nothing is passed the default value is taken.


Need Help

Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.


1.png


⚡Thanks For Reading | Happy Coding 🍺

Discussion

pic
Editor guide
Collapse
michi profile image
Michael Z
// Noobs:

let num = 15; 
let s = num.toString(); // number to string
let n = Number(s); // string to number

// Pro:

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

Sorry, but clever != pro. The "Noob" version much better reveals the intent of the code.

Collapse
aralroca profile image
Aral Roca

Same for

if(a!=123) // before // NOOBS

if(a^123) // after // PRO
Enter fullscreen mode Exit fullscreen mode

a^123 is not very clean IMO. Maybe a better one will be if(a !== 123)

Collapse
aralroca profile image
Aral Roca

And it's not correct for decimal numbers.

Boolean(122^123) // true
Boolean(123.1^123) // false -> is not correct, should be true 123.1 !== 123
Boolean(123^123) // false
Enter fullscreen mode Exit fullscreen mode

Much better to use the !== operator.

Collapse
migueloop profile image
Miguel Ruiz

Also we should think this is something that someone who comes from another Programming Language won't understand easily, just for saving 1 character

Collapse
nucliweb profile image
Joan León

IMHO

if(a!=123) // before // NOOBS

if(a!==123) // after // PRO
Enter fullscreen mode Exit fullscreen mode
Collapse
lvegerano profile image
Luis Vegerano

I would never approve a PR with something like that.

Collapse
rahxuls profile image
Rahul Author

I agree. But you know the pro version is better when you know many things about JS and doing big projects. I too had some doubt when writing this.

Collapse
misobelica profile image
Mišo

Sorry, but I have to strongly disagree. Please don't make people think it's better to complicate things. The Noob version is actually a Pro especially in big projects. I already wrote it here dev.to/misobelica/comment/15b21

JS is not the best language even without these quirks. We should know them but consider them a very sad code smell and not a Pro version.

Thread Thread
rahxuls profile image
Rahul Author

I'm sorry sir. When i will post again something related to this i will surely keep this in mind. Currently i'm writing through my phone so it will be hard for me to do. I'm sorry once again

Collapse
hspaans profile image
Hans Spaans

I wouldn't say better as it reduces the readability and maintainability of the code a lot. Having a language with strict type casting may seem a hassle for some, but it saves you hours of debugging in the long run. It was one of the significant reasons for the development of TypeScript and as a goal for both PHP 7 and Python 4.

Thread Thread
rahxuls profile image
Rahul Author

People write codes with their read comfort ability.

Thread Thread
seanmclem profile image
Seanmclem

Pretty much the #1 rule when learning programming is to not only write for yourself but with future coders and teammates in mind.

Collapse
zhnedyalkow profile image
Zhitomir Oreshenski

It is not readable and maintainable in the long run.

Thread Thread
rahxuls profile image
Collapse
madza profile image
Madza

was going to say that too 😉

Collapse
x1k profile image
Asaju Enitan

I am not so cool with the "pro" code, def not advisable for team based projects

Collapse
jmau111 profile image
Julien Maury

Before anything, thanks for sharing. These are funky tips, and it's always interesting to read posts like yours.

However, I prefer not being "clever", especially in a pro context. I want everybody to understand what I'm doing rather than being regarded as a code ninja. To me, if it's harder to read, it's worse, not better.

Maybe the "pros vs. noobs" presentation is not the best here. Likewise, I can assure you that big projects require clarity. If it's too "clever", it's harder to maintain.

Collapse
rahxuls profile image
Rahul Author

I surely agree with this and i will keep this in mind. I'm sorry actually I'm using my phone for blogging. I'm sorry.

Collapse
jmau111 profile image
Julien Maury

No problem, thanks for sharing :)

Collapse
lukaszahradnik profile image
Lukáš Zahradník

I'm not sure you can call your first example as something a pro would write

let hungry = true;
let eat = hungry == true ? 'yes' : 'no';
Enter fullscreen mode Exit fullscreen mode

hungry == true really?

Collapse
dakujem profile image
Andrej Rypo

Exactly 😆

Collapse
cwraytech profile image
Christopher Wray

Better like this:

hungry ? “Yes” : “No”

Collapse
pozda profile image
Ivan Pozderac

Have you ever worked in a team where you have senior, mid, 2+ juniors and intern?

senior and mid are like fish in the water with 'pro' code while juniors and interns feel like fish on a tree!

Clever code is ok to have on small teams where level of knowledge is similar. Having clever code in a larger teams leads to codebase nightmares.

Code should always be readable and easy to understand for everyone who will work on it. If you have to explain it, then your code is just a bad joke!

Collapse
iamreinder profile image
Reinder

I actually believe it is never okay. Not even in small teams where everybody is on the same level. You don't write the code for yourself. You write it for the company you work for or for a client. Being clever is not what being a good developer is. Code should be readable, maintainable and self-explanatory.

It's like being smart. Using big words doesn't make you smart. Being able to translate what you know into something that anyone can understand, that's smart.

Collapse
pozda profile image
Ivan Pozderac

When I think about it, I have to say that I completely agree with you.

While I'm comfortable to read 'PRO' code, I find myself writing readable code even in personal projects and stuff I'm just trying out that will never be seen by anyone else.

I guess it is a force of habit.

Clever code led us to having 'rockstar ninja developers' - writing 'PRO' code just to look clever and to confuse others to gain leverage and opportunity to explain something that shouldn't need explanation in the fist place.

You are 100% correct on this one!

Thread Thread
rahxuls profile image
Rahul Author

I can see someone understanding me. Sigh of happiness finally

Collapse
bugb profile image
bugb

Your code is incorrect

let dynamic = "value"; 
let user = {
    id: 1
    [dynamic] = "other value"
};
Enter fullscreen mode Exit fullscreen mode

It should be

let dynamic = "value"; 
let user = {
    id: 1,
    [dynamic]: "other value"
};
Enter fullscreen mode Exit fullscreen mode
Collapse
rahxuls profile image
Rahul Author

That comma though. I'm sorry

Collapse
adamazad profile image
Adam Azad

So is =. It should be a colon :

let dynamic = "value"; 
let user = {
    id: 1,
    [dynamic]: "other value"
};
Enter fullscreen mode Exit fullscreen mode
Collapse
dakujem profile image
Andrej Rypo
if(a!=123) // legible to anyone
if(a^123) // wtf
Enter fullscreen mode Exit fullscreen mode

I don't believe this code actually improves anything, like many other snippets presented here. It sacrifices one keyboard hit for legibility.

While I might be dumb for not knowing the trick, the difficulty is to make the code better understandable, not vice versa.

Collapse
aralroca profile image
Aral Roca

And doesn't work as expected.... Boolean(123.1^123) // false, but should be true

Collapse
hoggworks profile image
Brian Hogg

Yeah, the XOR operator isn't doing an equivalence check, at least not in the way the OP is presenting. It's just not a relevant tool to use, I don't think.

Collapse
alicescfernandes profile image
Alice Fernandes
let num = 15;
let s = num + ""; // number to string
let n = +s; // string to number
Enter fullscreen mode Exit fullscreen mode

I don't believe that this is pro javascript. This is playing with types of js and praying that it doesn't break in the future. I believe that converting to other types should be explicit so that it becomes readable to other coders

Collapse
rahxuls profile image
Rahul Author

Yea agree.

Collapse
jcubic profile image
Jakub T. Jankiewicz

Please check your code by running it first:

This is syntax error, because it's not valid JavaScript:

for(let i=0; i < arraySize; i++){
       filledArray[i] {'hello' : 'goodbye'};
}
Enter fullscreen mode Exit fullscreen mode

missing =, another is this, that suppose to be true but the character is not zero is letter o and even lowercase.

console.log(0 == 'o')
Enter fullscreen mode Exit fullscreen mode
Collapse
almostconverge profile image
Peter Ellis

The trouble with some of these is that while they may save a negligible amount of writing time, they certainly do increase reading time. Reason being, nobody reads character by character, it's closer to token by token.

A good example is your Removing duplicates snippet: you're replacing over 20 tokens (some of them loops and ifs, which are even more taxing to parse), with 5 simple ones. Brilliant! Best of all, it doesn't matter how skilled you are, the "pro" option is easier to read for everyone. And this is key.

Because if we look at the convert string/number and back snippet. num.toString() is two simple and verbose tokens in a not-at-all surprising sequence. You don't even have to know that num is a number to understand what's going on. Great! How about "" + num? Well, in terms of tokens it isn't any shorter. However it also includes a non-intuitive use of +. As you're not using the main effect of + (i.e. adding/concatenating) two things but a secondary effect (type coercion).

Same goes for the reverse direction, except there you also add another confounding construct: = +. Which will definitely have most people stop for a moment to re-parse it, because we very rarely put two separate operators after each other.

Some people say "ah, but once you get used to them, it becomes second nature and you can read it as fast as the noob versions". That is true, but note how it isn't actually faster: what you've achieved is that you spent a lot of time learning to read structures "noobs" can't read.

And that's my biggest criticism of lists like these. I don't think it was your intention but the noob/pro distinction creates a gate-keeping effect, where certain coding practices are followed not for any tangible improvement in code quality but to signal belonging to a group, in other words, they're a shibboleth.

Collapse
thr0tt1e profile image
Thr0TT1e

ERROR - "Object to Array"

// Noobs:

let number = {
    one: 1,
    two: 2,
};
let keys = [];
for (let numbers in number) {
    if (number.hasOwnProperty(numbers)) {
        keys.push(numbers);
    }
}

console.log(keys) // [ 'one', 'two' ]
Enter fullscreen mode Exit fullscreen mode

// Pro:

let number = {
    one: 1,
    two: 2,
};
let key   = Object.keys(number) // [ 'one', 'two' ]
let value = Object.values(number) // [ 1, 2 ]
let entry = Object.entries(number) // [ [ 'one', 1 ], [ 'two', 2 ] ]
Enter fullscreen mode Exit fullscreen mode
Collapse
rahxuls profile image
Rahul Author

Everyone has their own perspective sir.

Collapse
mcstepp profile image
Meg Stepp

No he meant your had typos in your variable names. You declared a "number" variable but referenced "numbers" (with an s) in your code examples. The code literally doesn't run.

Thread Thread
rahxuls profile image
Collapse
zoedreams profile image
☮️✝️☪️🕉☸️✡️☯️

1337 chop decimals with bitwise

var f = 3.14159;
var i = f|0
console.log("look ma` no decimal %n", i);
Enter fullscreen mode Exit fullscreen mode

1337 inject args with IoC with literal string reflection using .hasOwnProperty

static inject(clazz) {
    if(!clazz.hasOwnProperty('resource')) {
      throw new Error("All resources of type 'BaseResource' require the static function 'resource'");
    }
    global.talk.express.post(Api.URI[clazz.name], (..._) => clazz.resource(..._));
  }
Enter fullscreen mode Exit fullscreen mode

^github.com/ZoeDreams/talk/blob/mas...

Collapse
glowkeeper profile image
Steve Huckle

Some of the points have already been made, but I'd like to add to the growing number who suggest that many of the 'improvements' are unreadable -> unmaintainable.

Many of us write in multiple languages. I prefer to write code in a style that is recognisable by the majority, not the nuanced minority. In other words, I'd use != every time. And toString(), too.

That said, there are one or two nice examples, so thanks for sharing. For example, this one's good, and much more readable: let outputArray = Array.from(new Set(array));

Collapse
xxholly32 profile image
xx

console.log(0 == 'o'); // true

o -> '0'

Collapse
thesanjeevsharma profile image
Sanjeev Sharma

Well, Make sure you don't apply each one of these. Think before using.

Readability > Pro Hacks

Also, this a != 123 is not noob and this a ^ 123 is not pro. If I see this, I'll refactor it.

Collapse
moopet profile image
Ben Sinclair

If I see this, I'll query it because I'll assume they made a typo.

Collapse
thesanjeevsharma profile image
Sanjeev Sharma

Now that we know it's a pro move. You won't need to. Haha.

Collapse
grenmath profile image
Mathieu Grenier

Curious, anyhow you code noob/pro , performance/optimization will be impacted ?
Personnally i prefer a better readability for the team, but for personnal project im learning toward to code with new learning stuff from pro ;)

Collapse
rahxuls profile image
Rahul Author

I agree with you. Readability matters.

Collapse
chin98edwin profile image
chin98edwin

I usually don't point out spelling mistakes but this one is an exception. I believe you meant .map in pro code of the Populating an array section? 😅

Collapse
rahxuls profile image
Rahul Author

I'm sorry. I will surely change it. Actually i am blogging using my phone. I'm really very sorry sir.

Collapse
chin98edwin profile image
chin98edwin

No worries, no need to apologize. It's your blog post, just tryna help you out 🍻

Collapse
hb profile image
Collapse
rahxuls profile image
Rahul Author

Thank You.

Collapse
differentsmoke profile image
Pablo Barría Urenda

This is a bad article that makes me want to unfollow dev.to

Collapse
rahxuls profile image
Rahul Author

Sorry sir. If you don't like it's your wish to do whatever you want. Thank You.

Collapse
dotorimook profile image
dotorimook

Thank you for the nice post.

For Populating array,

const array = [...new Array(arraysize)].map(() => ({'hello' : 'goodbye'}));
Enter fullscreen mode Exit fullscreen mode

would also work. I prefer to use this ☺

Collapse
iminside profile image
Dan Chu

What about this?

const array = Array.from({ length: arraysize }, () => ({ hello: 'goodbye' }))
Enter fullscreen mode Exit fullscreen mode

And if rename arraysize to length then

const array = Array.from({ length }, () => ({ hello: 'goodbye' }))
Enter fullscreen mode Exit fullscreen mode
Collapse
qq449245884 profile image
qq449245884

Hello, may I translate your article into Chinese?I would like to share it with more developers in China. I will give the original author and original source.

Collapse
rahxuls profile image
Rahul Author

I would love it. Thanks. My article requires an edit a bit .... and use this link as source - >

rahulism.co/2020/11/29/_17-pro-jav...

Collapse
olsard profile image
olsard

Awesome! Thanks for sharing.

Collapse
slidenerd profile image
slidenerd

the noob version of populating an array is MUCH more efficient than the pro version, run the benchmarks and see for yourself

Collapse
hellonearthis profile image
Brett Cooper

numbers is not defined: Object to Array

Collapse
astelvida profile image
Sevda Anefi

I liked the one with the set. Will be using it from now on.

Collapse
john89624036 profile image
John

Great tips!