Wrapper Function vs Wrapper Object

node v8.12.0
version: 1.0.0
endpointsharetweet
+function () { const boolPrim = Boolean(0); // Wrapping function (WF) const boolObj = new Boolean(false); // Wrapping object (WO) // 1. WF returns primitive type while WO reurns reference type console.log('1. WF:', typeof boolPrim); // "boolean" console.log('1. WO:', typeof boolObj); // "object" // 2. WF is friendly with strict equal operator (===), while WO is not. console.log('2. WF:', boolPrim === false); // true console.log('2. WO:', boolObj === false); // false // 3. WF is friendly with "Truthy and Falsy rules" in JS, while WO is not. // See more: https://www.sitepoint.com/javascript-truthy-falsy/ console.log('3. WF:'); if (boolPrim) { console.log('I am truthy'); } else { console.log('I am falsey'); } console.log('3. WO:'); if (boolObj) { console.log('I am truthy'); } else { console.log('I am falsey'); } // 4. Never use WO. Use WF for better readability const arr = []; console.log('4. Truthy WF vs double negativity:', Boolean(arr) === !!arr); // true console.log('4. Common trick to parse boolean:', !!arr === true); // true }();
Loading…

no comments

    sign in to comment