-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?

4
  • 1
    Try to read it as return (newArr.length > 0);, now you can see you're returning a boolean value. Commented Aug 30, 2019 at 14:52
  • if the length of newArr is greater than 0 return true, otherwise it will return false Commented Aug 30, 2019 at 14:53
  • 1
    You can try and see the result. That’s how people learn. Commented Aug 30, 2019 at 14:54
  • Thanks. I’m learning about the chrome dev tools so will be able to do this soon Commented Aug 30, 2019 at 14:57

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help
If you feel like it answered your question, you could mark it as "correct" on the left side (where you can vote) for other users to see when they stumble across your question. :)
0

Just run this

function test(){
  return 2 > 0;
}
console.log(test())
console.log(2 > 0)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.