[thelist] JavaScript: A Confusion

Liorean Liorean at user.bip.net
Tue Feb 26 15:40:00 CST 2002


At 01:45 2002-02-27 +0500, Syed Zeeshan Haider wrote:
>Hello Experts,
>I am not very old in JavaScript. Therefore, my process of learning is
>still on its way. There are many little things which oftenly confuse me.
>I am still confused about the use of "!" operator in JS. I know the use
>of "!=" but "!" alone confuses me.
>What is the actual meaning of "!" operator? At which places it is needed
>to be used? Where can I use it? And where I cannot use it?
>Thank you,

The ! operator negates the thing you put it in front of.
var booleanValue = !true; // this is false
var booleanValue = !false; // this is true

It also converts other elements to boolean values when you use it:
var booleanValue = !0; // 0, '', null get converted to false. Thus, !0 is
equal to !false and gives true.
var booleanValue = !document.strangeNonExistentProperty; // undefined also
gets converted to false, and gives true when negated.
var booleanValue = !"string"; // Other values get converted to true, and
return false when negated.

var booleanValue = ![] // Objects, arrays and even Boolean objects are
considered to be [object] type, and thus gets converted to true. This means
that they even when empty such as this gives false when negated.
var booleanValue = !Boolean(false) // This might be the most confusing bit
of it. Both Boolean(false) and Boolean(true) are converted to true, and
thus both gives false when negated.



As for when you can use it, it's when checking for the lack of something,
for instance !document.all or !document.layers.
// Liorean




More information about the thelist mailing list