2

Why is it that when I'm returning, what I think is, a boolean variable from a javascript function, it is detected in the calling function as a string, but if I return a boolean literal, the calling function detects it as a boolean?

So, for example:

$( document ).ready(function(){
    $('#result').text(typeof validate());
    $('#result2').text(typeof validate2());
});

function validate(){
    status = true;
    status = false;
    return status;
}
    
function validate2(){
    return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello</p>
<div id="result"></div>
<div id="result2"></div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
anishthecoder
  • 940
  • 6
  • 20

2 Answers2

7

You don't declare the status status variable.

Therefore, the global one (window.status) is overwritten.

However, the HTML 5 spec defines that property as a DOMString:

interface Window : EventTarget {
  attribute DOMString status;
};

Therefore, it has a setter (either exposed or internal) which stores the stringified value.

To fix it, just declare your local variable using the var statement.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • I don't find the setter part of your explanation, do you have a link to it ? – nobe4 Apr 16 '15 at 20:37
  • @Nobe4 On Firefox you can use `Object.getOwnPropertyDescriptor(window, 'status').set`. Chrome doesn't expose the setter, but the value is still stringified before being stored, as specified in HTML5. – Oriol Apr 16 '15 at 20:49
1

$( document ).ready(function(){
    $('#result').text(typeof validate());
    $('#result2').text(typeof validate2());
});

function validate(){
    var status = true;
    status = false;
    return status;
}
    
function validate2(){
    return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello</p>
<div id="result"></div>
<div id="result2"></div>

EDIT: I was building the answer and something go wrong, anyway, the reason is explained well by @Oriol: The global window.status variable is the one which has the string value type.

Leandro Carracedo
  • 7,233
  • 2
  • 44
  • 50
  • You should explain why using a local variable makes a difference for this. – Barmar Apr 16 '15 at 20:35
  • I found that there is a gobal variable named `status`. Maybe that is related... `> typeof window.status ` => `string` – nobe4 Apr 16 '15 at 20:36
  • @Barmar really sorry, something go wrong while building the answer, do you think I should delete this answer to leave the Oriol answer? – Leandro Carracedo Apr 16 '15 at 20:50
  • 1
    Since his answer doesn't include the corrected code, your answer is also helpful. – Barmar Apr 16 '15 at 20:51