DEV Community

Cover image for JavaScript: Falsy(False) and Truthy(True) values explanation with example
Muhammad Azfar Aslam
Muhammad Azfar Aslam

Posted on • Updated on

JavaScript: Falsy(False) and Truthy(True) values explanation with example

Bonjour, for a long time at beginning of my career I thought some statement is true if two values comparison is equal and false when some condition does not meet. The above statement is not wrong but incomplete. If we don't understand the all possibilities of truly(true) and falsy(false) values, we will not be able to understand all possible solutions/outcomes we can achieve with this concept. I recently came across a problem/challenge posted by "Hackerrank" in which I am going to explain the concept of True and False statements.

So, the problem is to count all socks whose pairs are available in a pile. The pile may also contain a single sock with no pair available.

Image description

Input Format

  • The first line contains an integer representing the number of socks.

  • The second line contains space-separated integers, the colors of the socks in the pile.

This can be solved by multiple approaches but I am going to use for loop just to explain what I am trying here to share with you guys.

function sockCount(n, ar) {
    let temp = {}
    let count = 0
    for (var i = 0; i < n; i++) {
        temp[ar[i]] = !temp[ar[i]]
        if (!temp[ar[i]]) count++
    }
    return count
}

Enter fullscreen mode Exit fullscreen mode

And I pass values as following

const n = 9;
const ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
sockCount(n, ar)
Enter fullscreen mode Exit fullscreen mode

So, all values are true except false, 0, -0, 0n, "", null, undefined, and NaN.

At the start, temp is initialized by the empty object. It contains no value. This means if we check anything on this object, it'll return false due to undefined properties. So with all that in mind, we check to see if temp[ar[i]] exists.

Case (No) The object temp does not contain the value stored at ar[i]. So in that case, we want to set the value of storage[ar[i]] to the opposite of its current value, which is undefined. Since undefined is falsy, the opposite is true. So we are setting storage[ar[i]] to true. So if our array is temp = { 1: true, 2: false} and we check for temp[3], we get undefined, so we update temp to { 1: true, 2: false, 3: true}

Case (Yes) If sock color is already in temp array, we inverse its value from true to false.

Case (False check) If we get a false in the current iteration, we just increase the count by one.

I hope you guys grab more clear explanation of falsy and truthy values after reading this article. If you do, do like this post.
But if you loved it? man you gotta connect with me on LinkedIn 😉

Top comments (0)