Reputation: 1
I am learning about Javascript return
statements from functions. I have found a piece of code where the return statement uses the greater than operator, and am not sure what it means. The code is:
return newArr.length > 0;
The code relates to an array variable 'newArr'.
Is the expression saying to return the value if the array length is bigger than 1? Or is it saying return a value bigger than 0, therefore a true value?
Upvotes: 0
Views: 100
Reputation: 847
Please note that, all the conditional operators are always going to return a boolean value.
A true, if the condition satisfies, and a false if it doesn't.
Now consider the above code snippet that you have provided i.e.:
return newArr.length > 0;
What you can add in the above code snippet is something like this:
return Array.isArray(newArr) && newArr.length > 0;
The above line of code is going to return a boolean value as well, after all 'AND' operator is being used.
In addition to the above point, this can be a way to apply validation in the function as well. Consider some user to pass an integer as newArray instead of an Array.
Because of this scenario the expression Array.isArray(newArr) will be evaluated to false, and hence the next expression i.e. newArr.length isn't going to get executed thus, you save your day.
So this is how placement of conditions can matter.
Upvotes: 0
Reputation: 25
Just run this
function test(){
return 2 > 0;
}
console.log(test())
console.log(2 > 0)
Upvotes: 0
Reputation: 505
It returns a boolean (true/false). What it does is it executes the check: is the length of the array newArr greater than zero (i.e. are there items in it)? If it is, return true, else return false.
Upvotes: 2