FrontEnder FrontEnder - 1 year ago 109
Javascript Question

console.log(!val) producing unexpected result

Ran into an interesting issue. I was working on trying to toggle a boolean that was assigned to a variable. It wasn't working and eventually I tried this code.

var status = false;

I expected it to provide
in the console, but instead I got
. I figured that javascript would run the code inside the parenthesis first to find it's value and then console.log the value. Could you please explain why I am not getting a
value in the console?

Answer Source

window.status already exists (it is used to get/set the text of the browser's status bar) and when a value is assigned to it, it is converted to a string. If you do console.log( status ); you will see that status has the string value "false", which causes you to see the output false, since you effectively have !"false" and "false" is a truthy value in JavaScript.

If you do the same thing inside a function you'll get the expected output:

(function ( ) {
  var status = false;
  console.log(!status); // true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download