Understanding ‘Truthy’ and ‘Falsy’ in JavaScript

,

|

|

|

2 minutes

✅ Primitive Types:

💡 Represent single, immutable values. Primitive types in JavaScript include undefined, null, boolean, number, string, symbol, and BigInt.

💡 If a primitive type has a value that is considered falsy (like 0false""nullundefined, or NaN), it will behave as false in a Boolean context.

💡 They are stored directly in the location where the variable accesses them.

✅ Reference Types:

💡 Include objects such as functionarray, and other objects, and they are mutable.

💡 When you create a reference type, JavaScript allocates memory for it and the variable you assign it to holds a reference (or pointer) to that memory space, not the actual data itself.

💡 Since a reference points to an object, and objects in JavaScript are inherently truthy, a reference type cannot be falsy. Even if an object is empty (like {}) or an array has no elements ([]), it is still truthy because a reference to an allocated memory space exists.

🤔 Why are Function Constructors Truthy?

💡 Function constructors like new Number() or new Boolean() create object wrappers around primitive values.

💡 Despite the primitive value inside the object being falsy (like 0, or false), the object wrapper itself is a reference type.

💡 As we’ve established, reference types are always truthy because they refer to a memory location, not the value itself.

✨ Simple Analogy

Think of primitive types as individual pieces of paper with something written on them. If the paper is blank (a falsy value), it’s like having nothing or false. Reference types, on the other hand, are like folders (objects) that can hold these papers. Even if the folder is designed to hold a blank paper, the folder itself still exists and is something (truthy). The function constructors like new Number() and new Boolean() are like special folders that come with a label and even if the label says 0, or false (falsy), the folder is still an item you can reference and use (truthy).

🌟 Remember, in JavaScript, the type of value determines its truthiness or falsiness. Objects will always be your go-to for a guaranteed truthy value!

Happy coding! 🚀

#TruthyAndFalsy #WebDevelopment #Coding #ProgrammingTips #TipsAndTricks #React #JavaScript #HTML #CSS #Frontend #Engineer #Developer