+ 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); }
11 ответов
+ 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
+ 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
+ 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
+ 1
Sp Maurya
if you just write zero = Number(z)
then second will not execute.
+ 1
A͢J
Oh i see... Thanks...
+ 1
Yasin Rahnaward thanks brother for the effort... You made it a lot clearer...
+ 1
Yes they are NAN,false,undefined,0,empty string
+ 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.
0
A͢J
Yep that much i know...
Like
if (0) {
// not executes
}
if (zero) {
// but this executes
}
0
And if i'm right falsy means the value which when converted to boolean results in false...
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);
}