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.
600+ Free Design resources
Resources. Freebies. Learn.
We're making things easier on Internet.
Visit - 600+ free design resources
JavaScript : Tricks You Should Know
The ternary operator
Noobs:
let hungry = true;
let eat;
if (hungry == true) {
eat = 'yes';
} else {
eat = 'no';
}
Pro:
let hungry = true;
let eat = hungry == true ? 'yes' : 'no';
Number to string / string to number
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
Populating an array
Noobs:
for(let i=0; i < arraySize; i++){
filledArray[i] {'hello' : 'goodbye'};
}
Pro:
let filledArray = new Array(arraysize).fill(null).map(()=> ({'hello' : 'goodbye'}));
Dynamic properties in objects
Noobs:
let dynamic = "value";
let user = {
id: 1,
};
user[dynamic] = "other value";
Pro:
let dynamic = "value";
let user = {
id: 1,
[dynamic] = "other value"
};
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]
Pro:
let array = [100, 23, 23, 23, 23, 67, 45];
let outputArray = Array.from(new Set(array));
//outputArray = [100, 23, 67, 45]
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];
}
}
Pro:
let arr = ["value1", "value2", "value3"];
let arrObject = {...arr};
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' ]
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]]
Short circuit conditionals
Noob:
if (docs) {
goToDocs();
}
Pro:
docs && goToDocs()
Read more => "use strict" in JavaScript
Use ^ to check if numbers are not equal
if(a!=123) // before // NOOBS
if(a^123) // after // PRO
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 }
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
Check if value is an array
const arr = [1, 2, 3];
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true
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]
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
Better way to accept arguments
function downloadData(url, resourceId, searchTest, pageNo, limit) {}
downloadData(...); // need to remember the order
Simpler way to do:
function downloadData(
{ url, resourceId, searchTest, pageNo, limit } = {}
) {}
downloadData(
{ resourceId: 2, url: "/posts", searchText: "WebDev" }
);
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
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.
⚡Thanks For Reading | Happy Coding 🍺
Latest comments (62)
the noob version of populating an array is MUCH more efficient than the pro version, run the benchmarks and see for yourself
I liked the one with the set. Will be using it from now on.
Thank you for the nice post.
For Populating array,
would also work. I prefer to use this ☺
What about this?
And if rename
arraysize
tolength
thenHello, 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.
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...
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. AndtoString()
, 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));
numbers is not defined: Object to Array
This is a bad article that makes me want to unfollow dev.to
Sorry sir. If you don't like it's your wish to do whatever you want. Thank You.
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 thatnum
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.
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 ;)
I agree with you. Readability matters.
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!
I can see someone understanding me. Sigh of happiness finally
ERROR - "Object to Array"
// Noobs:
// Pro:
Everyone has their own perspective sir.
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.
Agreed.
Awesome! Thanks for sharing.
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 thisa ^ 123
is not pro. If I see this, I'll refactor it.If I see this, I'll query it because I'll assume they made a typo.
Now that we know it's a pro move. You won't need to. Haha.
Your code is incorrect
It should be
That comma though. I'm sorry
So is
=
. It should be a colon:
Some comments may only be visible to logged-in visitors. Sign in to view all comments.