Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Comparison Issue in JavaScript

I was looking at a Function that Django uses to get the CSRF Token, when you need to validate a user session, using Jquery and JavaScript. Here is the code:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

You can also see the code online here on the djangoproject website, here.

Okay, now when I paste this code, I get a light warning from my IDE saying this:

Binary operation argument type String is not assignable to type HTMLCollection

What does it mean by this? The error is on this line:

document.cookie && document.cookie != ''
like image 875
Games Brainiac Avatar asked Oct 03 '22 16:10

Games Brainiac


1 Answers

The problem is that Jetbrains PyCharm/Webstorm has "document.cookie" defined as @type {HTMLCollection}, as you can see when Ctrl-clicking on the 'cookie' variable (that will open the file "DHTML.js" containing the definition). That definition is wrong, all technical docs for 'document.cookie' describe it as a string, see for instance http://www.w3schools.com/jsref/prop_doc_cookie.asp Actually it was also reported as bug WEB-11410 in Jetbrains tools, and seems to be fixed now in the newer builds.

If you want to remove the warning, either add the inline comment as suggested by gztomas, or press Alt-Enter on the warning and go to "inspection 'type mismatch' options" and then "suppress for statement", that will disable the warning for the current statement only.

Changing the comparison to !== as suggested by Gannon does not help. Actually the comparison works correctly with !== also, most probably because this is just an issue with the IDE, 'document.cookie' is a string in all browsers.

(I don't have enough reputation for commenting on previous answers, so adding this as extra answer...)

like image 123
Ariel Avatar answered Oct 07 '22 20:10

Ariel