Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 14, 2022 08:22 am GMT

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 javascriptarray.reduce((a,b) => a+b);// Output: 35MAX in array javascriptarray.reduce((a,b) => a>b?a:b);// Output: 9MIN in array javascriptarray.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 javascriptconst 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);// orconst 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!';}// OutputFever(97): "Take Some Rest!" Fever(100): "Visit Doctor!"

Find Out More Tips on main source of an article.


Original Link: https://dev.to/devsimc/javascript-best-practices-44ll

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To