console.log(!status) in global scope producing une

2020-02-26 04:28发布

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;
console.log(!status);

I expected it to provide true in the console, but instead I got false. 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 true value in the console?

5条回答
疯言疯语
2楼-- · 2020-02-26 05:05

See the below screenshot which says that status is a property in window. So this directly refers to the window.status. It is not advisable to reuse certain variables and properties that are having default meaning(reminding about keywords in oops languages)

enter image description here

查看更多
够拽才男人
3楼-- · 2020-02-26 05:13
(function ( ) {
  var status = false;
  console.log(!status);
})();

This will give you expected output.

"status" is a predefined name of implementation-dependent JavaScript objects, methods, or properties. It is better avoid the identifiers as names of JavaScript variables. If you are using it outside the function then it means you want to implement any other thing by status value.

查看更多
别忘想泡老子
4楼-- · 2020-02-26 05:22

MDN

var statu = false;
console.log(!statu);

window.status exists already. so you can't use status variable .

查看更多
等我变得足够好
5楼-- · 2020-02-26 05:22

Check the type for status like this:

typeof status

The output will be: "string".

Note that false and "false" are not same.

When you define:

var status = false; //which is actually "false"

That's why you are not getting true.

查看更多
\"骚年 ilove
6楼-- · 2020-02-26 05:26

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
})();
查看更多
登录 后发表回答