PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 21, 2022

[FIXED] Why does an exclamation mark before a variable return 'true' if the variable value is zero?

 December 21, 2022     javascript, operators, syntax, variables     No comments   

Issue

I looked a lot, but I couldn't find an answer for this especific case.

Why does this expression return true?

let variable = 0
!variable // true

I understand that the ! mark checks if a value is null or undefined, but in this case variable is defined. This is tricking me. Isn't 0 really considered a valid value?


Solution

! is known as the logical NOT operator. It reverses the boolean result of the operand (or condition)

0 is also considered as the boolean false, so when you use !variable you are using the logical operator and saying it to change the value of the variable to its opposite, that in boolean is true

0 == false == !1 == !true

1 == true == !0 == !false

in Javascript are considered false: false, null, undefined, "", 0, NaN

are considered true: true, 1, -0, "false". <- the last one is a not empty string, so its true

if( false || null || undefined || "" || 0 || NaN) //never enter
if( true && 1 && -1 && "false") //enter

https://developer.mozilla.org/en-US/docs/Glossary/Falsy



Answered By - Consuelo Sanna
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing