JavaScript Tips and Tricks

by MD Hasan Patwary

HTML

<h1>JavaScript Tips and Tricks</h1>
<h3>check console</h3>

JavaScript

// ***** 1 *****
// Remove falsy values from any array
let miscellaneous = ['🍎', false, '🍊', NaN, 0, undefined, '🌢️', null, '', 'πŸ₯­'];

// passing Boolean to array.filter() will remove falsy values from array
let fruits = miscellaneous.filter(Boolean);

console.log(fruits); // ['🍎', '🍊', '🌢️', 'πŸ₯­']


// ***** 2 *****
// Convert any value to boolean
// Using !! in front of any value
console.log(!!"mashrafi"); // true
console.log(!!1); // true
console.log(!!0); // false
console.log(!!undefined); // false

// We can also use Boolean() to achieve same
console.log(Boolean("mashrafi")); // true


// ***** 3 *****
// Resizing any array
let animals = ["πŸ•", "πŸ’", "🦊", "πŸ…"];

// We can use array's length property
animals.length = 3;

console.log(animals); // ["πŸ•", "πŸ’", "🦊"]


// ***** 4 *****
// How to flattern a multi-dimensional array
let smileys = ['πŸ₯°', ['πŸ˜„', 'πŸ˜ƒ'], 'πŸ˜‰', ['πŸ₯²', 'πŸ˜‘']];

// We can use array.flat() method to flattern one level array
console.log(smileys.flat()); // ['πŸ₯°', 'πŸ˜„', 'πŸ˜ƒ', 'πŸ˜‰', 'πŸ₯²', 'πŸ˜‘']

// Multi level array
let smileys2 = ['πŸ₯°', ['πŸ˜„', 'πŸ˜ƒ', ['πŸ₯²', 'πŸ˜‘']], 'πŸ˜‰'];

// We can pass 'Infinity' parameter to array.flat function
console.log(smileys2.flat(Infinity)); // ['πŸ₯°', 'πŸ˜„', 'πŸ˜ƒ', 'πŸ₯²', 'πŸ˜‘', 'πŸ˜‰']



// ***** 5 *****
// Short conditionals
const captain = "Mashrafi";

// Instead of doing this
if(captain === "Mashrafi") {
    console.log("❀️");
}

// We can use &&
captain === "Mashrafi" && console.log("❀️");

// And instead of doing this
if(captain !== "Mashrafi") {
    console.log("😑");
}

// We can use ||
captain === "Mashrafi" || console.log("😑");



// ***** 6 *****
// Replace all occurances of a string
const quote = "React is a JS framework & this framework is the most popular front-end framework right now";

// Replace all occurances of 'framework' with 'library'
console.log(quote.replace(/framework/g, "library")); // React is a JS library & this library is the most popular front-end library right now



// ***** 7 *****
// Log values with variable names...