0

I have just come across some behavior I have never seen before. The javascript in my html page is converting a boolean to a string

I have a html page that looks like the following:

<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8"> 
</head>
<body>

<script type="text/javascript">

   var status = true;

   console.log(typeof status) //returns string

</script>

</body>
</html>

Strangely, when I open the console and type var test = true; and then on the following like type typeof test it returns "boolean".

Can anyone explain why this is happening and why it is not a boolean on both occasions?

peter flanagan
  • 9,195
  • 26
  • 73
  • 127
  • 1
    status is a reserved word, change you var name – Ronnie Apr 12 '17 at 21:43
  • 1
    @Ronnie lol... . – KthProg Apr 12 '17 at 21:44
  • 1
    You are correct, thanks! Clears a lot of confusion up in my head. Just as a matter of interest even though it is a reserved word, why does it convert it to a string – peter flanagan Apr 12 '17 at 21:45
  • Interesting that the behavior of status is such that you can only assign a string to it though. – KthProg Apr 12 '17 at 21:45
  • javascript is weird, dont feel bad – Ronnie Apr 12 '17 at 21:45
  • 1
    It’s not a reserved word; it’s a property on the window that’s a string. – Ry- Apr 12 '17 at 21:45
  • 4
    @Ronnie: It's not a reserved word. It's a predefined global variable in browsers. https://developer.mozilla.org/en-US/docs/Web/API/Window/status – Felix Kling Apr 12 '17 at 21:45
  • 1
    alright well I was close – Ronnie Apr 12 '17 at 21:46
  • you were close @Ronnie dont mind them :-) – peter flanagan Apr 12 '17 at 21:46
  • 2
    If you use `let` or `const`, or wrap your entire script in an IIFE – https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript – you can avoid this problem. – Ry- Apr 12 '17 at 21:47
  • Duplicate? [Javascript treats variable named status as string while treating Status as array](http://stackoverflow.com/q/43172331/218196) – Felix Kling Apr 12 '17 at 21:47
  • It converts to a string because it sets the text in the browser status bar, which obviously must be a string. There is no standard I can find anywhere that makes this behavior required though. – KthProg Apr 12 '17 at 21:50
  • You can also do `delete window.status` in Chrome and then use the variable as usual, but you really shouldn't be declaring variables in global scope for exactly this reason. – KthProg Apr 12 '17 at 21:53

0 Answers0