Phragos
Phragos

Reputation: 75

Vanilla JavaScript if clause executes when false

This is my first post and I am thankful in advance for all the support.

Short background:

I am part of a script team developing a script to make our tasks easier. We are using a MySQL DB to allow the team choose which features we create each wants to use. The DB is working fine, as well as the data retrieval.

Issue:

Even though the cookies we create are set to hold the boolean value False, a function is always executing the if clause it holds.

function tkAlwaysViewAll(snippet) {
    console.log('Viewall: ' + snippet);
    if (snippet) {
            var ticketURL = window.location.href;
            var showAllURL, x;
            x = ticketURL.indexOf('block=');
            // if the string 'block=' does not exist in the URL, it adds the parameter and
            // reloads the ticket to the correct 'view all' URL
            if (x == -1) {
                showAllURL = ticketURL + '&block=15:.a';
                window.location.href = showAllURL;
            } else {
                console.log('Viewall function executed');
            }
    }
} 

The code above should execute only when the value of snippet is set to True. However, it is being executed always, ignoring the value of snippet. Below you see the output of the console.log() which has been included for the debugging only. The first console.log() displays the value of the snippet variable. The second console.log() will be displayed only after the page has been reloaded (or when directly using the link with the 'block' parameter, but we are aware of this and not using it).

When snippet is True:

Viewall: true
Viewall function executed

And when the snippet is False (function should not be executed):

Viewall: false
Viewall function executed

The function is not using any global variables nor being altered by any other events.

What am I doing wrong in this function?

Best regards

Upvotes: 0

Views: 217

Answers (1)

connexo
connexo

Reputation: 56744

The reason is that you pass a String "false" to your function (cookies always store Strings). Putting that in an if() condition internally converts that String to a Boolean value. Non-empty strings are converted to true in that mechanism.

Here's what Javascript does with non-Boolean values when converting:

// converts val to Boolean and returns it
function truthy(val) {
  return Boolean(val) 
}

console.log(truthy("true"))    // true
console.log(truthy("false"))   // true
console.log(truthy(""))        // false

console.log(truthy(1))         // true
console.log(truthy(0))         // false

console.log(truthy([]))        // true
console.log(truthy([].length)) // false

console.log(truthy({}))        // true

Upvotes: 1

Related Questions