## DEV Community

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

### 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
``````

### 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]
``````

### 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]
``````

### 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}
``````

### 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!"
``````

Find Out More Tips on main source of an article.

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))
``````

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

Simc Dev

True

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!

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))
``````

Vasiliy

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

Lou Cyx

If you don't do mutations, this is not a concern tbh.

Awesome, thank you for sharing!

Thanks bro.

Lou Cyx

Just a heads up that you can add highlighting to the code blocks if you'd like. Just change:

... to specify the language:

More details in our editor guide!

About the actual post, maybe not use "best practices" in the title, because:

For 1:

``````const array = Array(5).fill(Array(5).fill(0));
``````

For 2:

``````// For the sum, I would suggest to use better names than `a` and `b`:
array.reduce((total, item) => total + item);

// For max, this is way faster:
Math.max(...array);

// For min this is way faster
Math.min(...array);
``````

For 3:

``````// Better to avoid mutations (that will bite you in libraries like React):
[...stringArr].sort();
[...stringArr].reverse();

// I generally recommend to use `a` and `z` to make it clear:
[...array].sort((a, z) => a - z);
[...array].sort((a, z) => z - a);

// But you could also make it more readable:
[...array].sort((first, second) => first - second);
[...array].sort((first, second) => second - first);
``````

For 4:

``````// You should always do it like this, is faster than the alternative:
[...new Set(array)];
``````

For 5:

``````const table = {};
for (const char of string) {
// Instead of relying on `NaN` as a falsy, ideally you should use `??`:
table[char] = (table[char] ?? 0) + 1;
}

// You can also write it like this, but is less performant:
[...string].reduce(
(table, char) => ({ ...table, [char]: (table[char] ?? 0) + 1 }),
{},
);
``````

For 6:

``````// You could just use an arrow function here,
// and you have a typo, you don't need the last "temp === 97"
// that's the only remaining option
const checkTemperature = temp =>
temp > 97
? "Visit Doctor!"
: temp < 97
? "Go Out and Play!!"
: "Take Some Rest!";
``````

Cheers!

Thanks Luke, this is really helpful!

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
``````
``````// Bad

// Good
if (isLogged(user)) {
else navigateToHome();
``````

Lou Cyx • Edited

I disagree (I have a full article about this same topic). The actual "bad practice" isn't ternaries, it is to write code that is hard to read. If something is hard to read as a ternary, then that means you're putting way too much login in a single place, and you shouldn't. Also if you put everything in a single line, it obviously is harder to read:

``````// inline 🤢

// formatted ✨
return isLogged(user)
? navigateToDashboard()
: navigateToHome()
``````

You could also make use of the fact that functions are values as well and just use the `()` to call them once you figure out which function to call:

``````return (
isLogged(user)
? navigateToDashboard
: navigateToHome
)();
``````

Obviously that's getting complex, but as I said in my article, if something gets complex, is just a sign that we need to separate the logic:

``````const navigateLogged = user =>

// ...

return (isLogged(user) ? navigateLogged(user) : navigateToLogIn)();
``````

Your other example showcases yet another strength of ternaries: Covering all the scenarios. Is pretty common to make the mistake of write an `if` without an `else`, leaving uncovered branches on the logic. It might be intentional to return `undefined` if a condition is met, but ternaries force you to be explicit about it, instead of being implicit:

``````const greetUser = user => {
if (isLogged(user)) {
return `hello \${user}`;
};
// Implicit "else return undefined"
};

const greetUser = user =>
(isLogged(user) ? `hello \${user}` : undefined);
``````

Now, maybe that's the intended behavior, but maybe you actually wanted to greet not logged users as well, the ternary approach makes it obvious, the `if` not so much.

One other thing I don't quite understand is: What do folks find so confusing about ternaries. It was one of the first things I learned when learning to code, and it was as easy (if not more) than `if`, I read them as:

is this true? do this : or do that

Maybe I would have used another operator instead of `:` for the second part of a ternary, but the `?` operator is 🤌🏽💋 (cheff kiss 🤣) ... it actually looks like you're asking a question.

Cheers!

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();
``````

Lou Cyx

So you are against ternaries, but in favor of short-circuiting which is actually "hacky" code and by definition is harder to read. I guess we agree to disagree, then.

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 />}
``````

This is also good:

``````{userPermissions.modules.chatbot ? <Chatbot /> : <PlaceHolder />}
``````

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.

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.

Chandrashekhar Kachawa

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

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

Simc Dev

🔥