DEV Community

Simc Dev
Simc Dev

Posted on • Originally published at cmsinstallation.blogspot.com

Javascript best practices🔥

  1. Declare and Initialize Arrays in javascript
  2. Find out the sum, minimum and maximum value in javascript
  3. Sorting Array of String, Numbers or Objects in javascript
  4. Remove Duplicates array values in javascript
  5. Create a Counter Object or Map in javascript
  6. Ternary Operator in javascript
  7. Arrow Functions in javascript
  8. Shuffle an Array in javascript
  9. Rest & Spread operators in javascript
  10. Convert Decimal to Binary or Hexa in javascript

1. Declare and Initialize Arrays in javascript

We can initialize array of particular size with default values like "", null or 0. You might have used these for the 1-D array but how about initializing 2-D array/matrix?

const array = Array(5).fill(''); 
// Output 
(5) ["", "", "", "", ""]

const matrix = Array(5).fill(0).map(()=>Array(5).fill(0)); 
// Output
(5) [Array(5), Array(5), Array(5), Array(5), Array(5)]
0: (5) [0, 0, 0, 0, 0]
1: (5) [0, 0, 0, 0, 0]
2: (5) [0, 0, 0, 0, 0]
3: (5) [0, 0, 0, 0, 0]
4: (5) [0, 0, 0, 0, 0]
length: 5
Enter fullscreen mode Exit fullscreen mode

2. Find out the sum, minimum and maximum value in javascript

const array  = [5,4,7,8,9,2]; 
Sum in array javascript
array.reduce((a,b) => a+b);

// Output: 35
MAX in array javascript
array.reduce((a,b) => a>b?a:b);
// Output: 9

MIN in array javascript
array.reduce((a,b) => a<b?a:b);
// Output: 2
Enter fullscreen mode Exit fullscreen mode

3. Sorting Array of String, Numbers or Objects in javascript

const stringArr = ["Joe", "Kapil", "Steve", "Musk"]
stringArr.sort();
// Output
(4) ["Joe", "Kapil", "Musk", "Steve"]

stringArr.reverse();
// Output
(4) ["Steve", "Musk", "Kapil", "Joe"]

### Sort Number Array in javascript
const array  = [40, 100, 1, 5, 25, 10];
array.sort((a,b) => a-b);
// Output
(6) [1, 5, 10, 25, 40, 100]

array.sort((a,b) => b-a);
// Output
(6) [100, 40, 25, 10, 5, 1]
Enter fullscreen mode Exit fullscreen mode

4. Remove Duplicates array values in javascript

const array  = [5,4,7,8,9,2,7,5];
array.filter((item,idx,arr) => arr.indexOf(item) === idx);
// or
const nonUnique = [...new Set(array)];
// Output: [5, 4, 7, 8, 9, 2]
Enter fullscreen mode Exit fullscreen mode

5. Create a Counter Object or Map in javascript

let string = 'kapilalipak';
const table={}; 
for(let char of string) {
  table[char]=table[char]+1 || 1;
}
// Output
{k: 2, a: 3, p: 2, i: 2, l: 2}
Enter fullscreen mode Exit fullscreen mode

6. Ternary Operator in javascript

function Fever(temp) {
    return temp > 97 ? 'Visit Doctor!'
      : temp < 97 ? 'Go Out and Play!!'
      : temp === 97 ? 'Take Some Rest!';
}

// Output
Fever(97): "Take Some Rest!" 
Fever(100): "Visit Doctor!"
Enter fullscreen mode Exit fullscreen mode

Find Out More Tips on main source of an article.

Top comments (15)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

For getting maximum and minimum values from an array, Math.max and Math.min are orders of magnitude faster than reduce.

Also, for filling a 2D array - all you need do is:

const matrix = Array(5).fill(Array(5).fill(0))
Enter fullscreen mode Exit fullscreen mode

There is no need for map (but spot the mistake! Fix below)

Collapse
 
devsimc profile image
Simc Dev

True

Collapse
 
bustexz profile image
Vasiliy

Nope man, you cant. All sub arrays are linked in 1 array. If you change matrix[0][0] = 15, all matrix[n][0] = 15. You need map to do this!

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

I was wondering when someone would notice! Took long enough 😛

But you don't need map...

Array.from({length:5},i=>Array(5).fill(0))
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
bustexz profile image
Vasiliy

its the same like a map :D. Just another variant)

Collapse
 
mjcoder profile image
Mohammad Javed

Awesome, thank you for sharing!

Collapse
 
rafimohammad839 profile image
Mohammad Rafi

Thanks bro.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

As the js formatting thingy has already been commented by @lukeshiru just going to add that nesting ternaries are considered a bad practice.
Also don't use them if you need just an if
i.e.

isLogged(user) ? sayHello : ''; // bad

if (isLogged(user)) sayHello; // good
Enter fullscreen mode Exit fullscreen mode
// Bad
isLogged(user) ? isAdmin(user) ? navigateToDashboard() : navigateToHome() : navigateToLogIn();

// Good
if (isLogged(user)) {
    if(isAdmin(user)) navigateToDashboard();
    else navigateToHome();
} else navigateToLogIn();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR 🥇

What I added was a silly example just to showcase.
The fact that you can chain ternaries doesn't mean they are convenient the same way the fact you can use recursivity it doesn't mean it's convenient in most cases.

Yes, ternaries are "new", fancy and so but they are intended to cover a need, and that need is to shorthand an if-else statement with conditions:
You just can have, and should have a single statement on both the cases, when the condition evaluates to true and to falsy in the other hand.

There are other tools intended for whatever case that sits out of this definition.

If you begin chaining ternaries you'll end up with a mess while adding conditions to it, plus most code style guides format them as a single line (for the reasons named above, if you need to chain them, you don't want a ternary).

Last but not least; No, there's no need to cover the "else" always.
In such cases both if and && operators come in handy, depending on the situation.

Plus ternaries can be substituted by && and || operators if you want a generic hammer:

isLogged(user) && doWharever() || doSomethingElse();
Enter fullscreen mode Exit fullscreen mode
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

hahaha that's just the point I want to reach. Anything that the API provides can be used but using it as a single tool to rule them all is not so good.

This is a common pattern in react (as example), nothing wrong with it:

{userPermissions.modules.chatbot && <Chatbot />}
Enter fullscreen mode Exit fullscreen mode

This is also good:

{userPermissions.modules.chatbot ? <Chatbot /> : <PlaceHolder />}
Enter fullscreen mode Exit fullscreen mode

The question would be if you need this component or not.

I'm not against ternaries, I'm against nested ternaries, the same way I'm against short circuit if you are forcing the usage out of reasonable limits.

At the end all this discussion is subjective and we are discussing personal preferences, of course. It is interesting, either way to see other's point of view on that stuff.

Collapse
 
sloan profile image
Sloan the DEV Moderator

Hi there, we encourage authors to share their entire posts here on DEV, rather than mostly pointing to an external link. Doing so helps ensure that readers don’t have to jump around to too many different pages, and it helps focus the conversation right here in the comments section.

If you choose to do so, you also have the option to add a canonical URL directly to your post.

Collapse
 
mjcoder profile image
Mohammad Javed

Thanks Luke, this is really helpful!

Collapse
 
tsukuyomi808 profile image
Froilan Abellanosa

Thanks for this! I am having time learning JavaScript and it is not clicking in my head, So thank you so much for this

Collapse
 
devsimc profile image
Simc Dev

🔥

Collapse
 
ctrix profile image
Chandrashekhar Kachawa

If you are storing unique values, use sets in javascript.