It’s all about javascript cool tips and tricks which help day-to-day programming and reduce the time of the developer.
1. Use == instead of ===
== only check Equality and === check Equality as well as type.
[1] === 1 // is false
[1] == 1 // is true
'1' == 1 // is true
'1' === 1 // is false
[] == 0 // is true
[] === 0 // is false
'' == false // is true but true == "a" is false
'' === false // is false
2. undefined, null, 0, false, NaN, ” (empty string) are all falsy.
3. Empty an array
var arr = [1, 2, 3];
arr.length = 0; // arr will be equal to [].
Read more: Javascript array
4. while loop power
var no = 4;
while (no--) console.log(no); // 3 2 1 0
Read more: Javascript loop
5. Iterate object in forEach
var obj = { name: "xyz", age: 23 };
[obj].forEach((val)=>{
console.log(val); //{ name: "xyz", age: 23 }
});
Read more: Javascript loop
6. Power of join
var arr = ['one', 'two', 'three'];
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
console.log(list);
//<ul><li>one</li><li>two</li><li>three</li></ul>
Read more: Javascript array
7. Create object clone
var obj = { 'name': 'xyz' };
var clone = Object.assign({}, obj);
clone.age = 23;
console.log(obj); // { 'name': 'xyz' };
8. Power of logical and/or
var bol = false;
bol || console.log(bol); // false
var bol = true;
bol && console.log(bol); // true
9. Power of Double negation
var no = 2;
console.log(no); // 2
console.log(!no); // false
console.log(!!no); // true boolean conversion of no value
// it’s just converting the value into the boolean form
10. toFixed is awesome
var no = 2.44567890;
no = no.toFixed(2);
console.log(no); // 2.45