Devender Shekhawat
Devender Shekhawat

Reputation: 89

difference between return (function()) and return true in javascript

I have the following sample document

<!doctype html>
<html>
  <head>
   <title>My home page</title>
  </head>
  <body>
    <h1>My home page</h1>
    <p>Hello, I am Marijn and this is my home page.</p>
    <p>I also wrote a book! Read it
    <a href="http://eloquentjavascript.net">here</a>.</p>
  </body> 
</html>

i wrote a recursive function to find out whether a string is in document or not

function talksAbout(node, string) {


 if(node.nodeType == document.ELEMENT_NODE){
      for(var i=0;i<node.childNodes.length;i++){
       if(talksAbout(node.childNodes[i],string))
         return true;
      }
     return false;
   }
  else if(node.nodeType == document.TEXT_NODE){
     return (node.nodeValue.indexOf(string) > -1);
  }
}

console.log(talksAbout(document.body,"wrote"));

but when i change if statement in 3rd line from

if(talksAbout(node.childNodes[i],string))
   return true;

to simple

return taksAbout(node.childNodes[i],string)

it shows wrong answer.can somebody find the difference between two.

Upvotes: 0

Views: 466

Answers (3)

ZeroWorks
ZeroWorks

Reputation: 1638

the function talksAbout doesn't return a boolean value in all cases:

...
else if(node.nodeType == document.TEXT_NODE){
    return (node.nodeValue.indexOf(string) > -1);
}
...

If this condition meets will return a positive integer or -1:

IndexOf docs

Also if this condition doen't meets will return null. When you do check and return true your are assuring that the return value is a boolean if your return (function()) you are returning the return value of the function and as I explained above it could be a boolean an integer or null in your function.

If you want assure you're returning a boolean just return if in all cases in your function.

Hope it helps!

Upvotes: 0

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

You have a simple flow logic error:

There is a difference in the following two blocks of pseudocode:

 foreach item in list
     if (f(item))
        return true;

And

 foreach item in list
     return f(item)

The first block will return true if any item creates a true result.

The second block will simply return true or false depending on the result of the first item.

Your change essentially converted your code block from the first example to the second example.

Upvotes: 1

James Wilkins
James Wilkins

Reputation: 7367

The code

if(talksAbout(node.childNodes[i],string))
   return true;

checks the return of the call and returns true IF the result is true. Doing it this way:

return taksAbout(node.childNodes[i],string)

Returns on the first item of the iteration, without checking the rest. ;)

Upvotes: 1

Related Questions