<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...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features β
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.