+ 5

Javascript Challenge Query

Can somebody explain to me, what is going on here ? var x = 50, y = 5, z = x % y; var zero = new Number(z); document.write(zero == true); // gives false if (zero) { // but here it executes... document.write(true); }

11th Mar 2023, 1:22 PM
Sp Maurya
Sp Maurya - avatar
11 Answers
+ 6
Hi Sp Maurya I try to explain it in 4 steps😊 var x = 50, y = 5, z = x % y; var zero = new Number(z); //1 .here new number creates an object with value //of z . Result=> {0} document.write(zero == true); // false // 2. Its false because the object {0} itself // is not equal to true // 3. Your can check the value of an object with //valueOf() method . //result=> {0}.valueOf() is equal with 0 if (zero) { document.write(true); } //4. Remember always an object with any value //even falsy values are true when you consider it //as a boolean. So that's why here the code inside // block is running. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean
11th Mar 2023, 2:01 PM
Yasin Rahnaward
Yasin Rahnaward - avatar
+ 2
Sp Maurya here zero is an object Check console.log(typeof zero) if (object) will always return true but object == true will return false
11th Mar 2023, 1:47 PM
AÍąJ
AÍąJ - avatar
+ 1
50 % 5 = 0 So now check what is the value of zero new Number(z) will return object so object == true // false if(object) //true
11th Mar 2023, 1:41 PM
AÍąJ
AÍąJ - avatar
+ 1
Sp Maurya if you just write zero = Number(z) then second will not execute.
11th Mar 2023, 1:53 PM
AÍąJ
AÍąJ - avatar
+ 1
AÍąJ Oh i see... Thanks...
11th Mar 2023, 1:53 PM
Sp Maurya
Sp Maurya - avatar
+ 1
Yasin Rahnaward thanks brother for the effort... You made it a lot clearer...
11th Mar 2023, 2:09 PM
Sp Maurya
Sp Maurya - avatar
+ 1
Yes they are NAN,false,undefined,0,empty string
11th Mar 2023, 2:33 PM
Yasin Rahnaward
Yasin Rahnaward - avatar
+ 1
En résumé, le code teste la conversion de l'objet Number en une valeur booléenne, qui renvoie false car un objet est considéré comme faux lorsqu'il est comparé à une valeur booléenne. Cependant, l'objet est toujours considéré comme "truthy" lorsqu'il est utilisé dans une expression booléenne, ce qui permet à if (zero) de s'exécuter.
13th Mar 2023, 11:59 AM
SANA SIPOU
SANA SIPOU - avatar
0
AÍąJ Yep that much i know... Like if (0) { // not executes } if (zero) { // but this executes }
11th Mar 2023, 1:45 PM
Sp Maurya
Sp Maurya - avatar
0
And if i'm right falsy means the value which when converted to boolean results in false...
11th Mar 2023, 2:11 PM
Sp Maurya
Sp Maurya - avatar
0
Javascript Challenge Query Can somebody explain to me, what is going on here ? var x = 50, y = 5, z = x % y; var zero = new Number(z); document.write(zero == true); // gives false if (zero) { // but here it executes... document.write(true); }
13th Mar 2023, 10:06 AM
Orlando Candelaria
Orlando Candelaria - avatar