Matt Zelenak - 7 months ago 72

Javascript Question

I'm having some issues getting a proper boolean return on section 4.1 of Codecademy's Javascript tutorial. Here is the code:

`// Define quarter here.`

var quarter = function(n) {

if (n / 4 ){

return true;

} else {

return false;

}

};

if (quarter(4) === 1) {

console.log("The statement is true.");

} else {

console.log("The statement is false.");

}

From what I can see, I am passing the newly defined quarter variable a function with a parameter of 'n' that I then divide by 4 to see if it returns 1 for true, or 0 (else) for false. I then am using the 'quarter' function in an if loop to check for equality of 1 of the number '4' passed as 'n'.

I'm assuming this is some basic logic that I am just not used to using (as a front end developer looking to get into JavaScript programming) but I would definitely appreciate some thoughts and guidance.

Answer

In JavaScript, the constants `true`

and `false`

are **not** numbers; they're a separate type.

Furthermore, you're comparing with `===`

and that will explicitly prevent type conversion during the comparison.

Note that `n / 4`

is going to be `true`

(non-zero) for all values of "n" except 0 (*edit* you probably meant to use `%`

). And in general, any construction of the form:

```
if (expression) {
return true;
}
else {
return false;
}
```

can be replaced by:

```
return !!(expression);
```

or, alternatively,

```
return Boolean(expression);
```