2

I don't know why, but the code below works in Firefox but NOT in Google Chrome, why ? This should be standard JS.

status = parseInt($('#input-status').val());
// status field is exactly equals to 0
if (status === 0) {
// do something, in Firefox the code reaches here, in Chrome NOT !
}

Here is how #input-status is defined in html :

<input type="hidden" id="input-status" name="input-status" value="00">

In Chrome the code works only if i replace === by == .

Any ideas ?

delphirules
  • 6,443
  • 17
  • 59
  • 108

1 Answers1

5

I'm not sure why this happens but I can reproduce it like this:

jsfiddle

status = parseInt($('#input-status').val(), 10);
test = parseInt($('#input-status').val(), 10);

console.log(typeof status); // string
console.log(typeof test); // number

I guess status is predefined by the browser and can't be parsed. To make it work use var to define a new variable in the current scope:

var status = parseInt($('#input-status').val(), 10);

if (status === 0) {
    // this also works in chrome
}

EDIT

console.log(window.status === status); // true

It seems like status is a reference to the window.status object which changes the status bar in the browser. And it does make sense that this can't be parsed into a number.

@Xotic750 pointed out:

Yes, on Chrome whenever you set the global variable status/window.status to any value window.status = {} then it converts it to a string {value: "[object Object]", writable: true, enumerable: true, configurable: true} jsfiddle lesson: don't use global variables, use var to make them locally scoped

damian
  • 5,314
  • 5
  • 34
  • 63
  • Great, adding 'var' solves it ! :) – delphirules Feb 12 '14 at 16:39
  • 2
    Yes, on Chrome whenever you set the global variable `status`/`window.status` to any value `window.status = {}` then it converts it to a string `{value: "[object Object]", writable: true, enumerable: true, configurable: true}` [jsFiddle](http://jsfiddle.net/Xotic750/9tvDV/), lesson: don't use global variables, use [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) to make them locally scoped. – Xotic750 Feb 12 '14 at 16:48
  • Just want to reiterate that the lesson you should take from this is: Never use implicitly defined global variables. Always use var, and don't use globals whenever possible. – Colin DeClue Feb 12 '14 at 17:01