- Declare and Initialize Arrays in javascript
- Find out the sum, minimum and maximum value in javascript
- Sorting Array of String, Numbers or Objects in javascript
- Remove Duplicates array values in javascript
- Create a Counter Object or Map in javascript
- Ternary Operator in javascript
- Arrow Functions in javascript
- Shuffle an Array in javascript
- Rest & Spread operators in javascript
- 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.
Top comments (19)
For getting maximum and minimum values from an array,
Math.max
andMath.min
are orders of magnitude faster thanreduce
.Also, for filling a 2D array - all you need do is:
There is no need for
map
(but spot the mistake! Fix below)True
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!
I was wondering when someone would notice! Took long enough 😛
But you don't need
map
...its the same like a map :D. Just another variant)
If you don't do mutations, this is not a concern tbh.
Awesome, thank you for sharing!
Thanks bro.
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:
For 2:
For 3:
For 4:
For 5:
For 6:
Cheers!
Thanks Luke, this is really helpful!
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.
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:
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: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:
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 anelse
, leaving uncovered branches on the logic. It might be intentional to returnundefined
if a condition is met, but ternaries force you to be explicit about it, instead of being implicit: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: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!
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: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.
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:
This is also good:
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.
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.
If you are storing unique values, use sets in javascript.
Thanks for this! I am having time learning JavaScript and it is not clicking in my head, So thank you so much for this
🔥