3

Javascript best practicesđŸ”„

 2 years ago
source link: https://dev.to/devsimc/javascript-best-practices-44ll
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
  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.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK