Trent Scott
Trent Scott

Reputation: 2028

JS Cookie Plugin + If Statement Not Working

I'm trying to use the JS Cookie Plugin to read the value of a cookie and include a notification bar (Hello Bar) if the value is not 1.

Here's my code:

<!-- HelloBar code start -->
<script type="text/javascript" src="//www.hellobar.com/hellobar.js"></script>
<script type="text/javascript">
if($.cookie('returning_user') !== '1') {
    new HelloBar(12345,12345);
}
</script>
<!-- HelloBar code end -->
  1. Is !== the right operator to test for inequality here?
  2. By putting 1 in quotes, am I testing for a string when I really want an integer?

Right now, the interior part of the code (new HelloBar ...) is never executed.

Upvotes: 0

Views: 73

Answers (1)

!== will check the Type and value Both

so if you want to match Integer

than use

if($.cookie('returning_user') !== 1) {

=== and !== are strict comparison operators:

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===). [I.e. Null==Undefined (but not Null===Undefined)]

Comparison Operators - MDC

0==false   // true
0===false  // false, because they are of a different type
1=="1"     // true, auto type coercion
1==="1"    // false, because they are of a different type

Upvotes: 1

Related Questions