Javascript tips and tricks Javascript best practices 2022
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
Useful techniques to reduce the lines of code
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
Sort String Array 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);// 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!"
7. Arrow Functions in javascript
const person = {name: 'Krishna',sayName() {return this.name;}}person.sayName();// Output"Krishna"
8. Shuffle an Array in javascript
const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];list.sort(() => {return Math.random() - 0.5;});// Output(9) [2, 5, 1, 6, 9, 8, 4, 3, 7]// Call it again(9) [4, 1, 7, 5, 3, 8, 2, 9, 6]