1
\$\begingroup\$

I want to send a string with the following path, and I want to verify if this is the right way to do that in JavaScript.

  1. Is this the right way to use the return in an if/else, or there is shorter way?
  2. Is the indexOf using correctly?

https://test.com/plugins/plug/pluginr/poc/fact

function isExt(path) {

  if(path.indexOf("/plug/pluginr/")) {

    return true;

  }
  else {

    return false;

  }

}
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

Your code seems not to be correct. In case you don't have the substring /plug/pluginr/ it would still return true since indexOf returns an integer containing the position of the first ocurrence. If theres no ocurrence of the substring then it returns -1 which is evaluated to true in JavaScript.

You better use this instead;

function isExt(path){
    return path.indexOf("/plug/pluginr/") > -1;
}
\$\endgroup\$
4
  • 2
    \$\begingroup\$ I voted to reject your edit on this question. It would be better to mention the gratuitous use of whitespace than to edit it out of OP's question. \$\endgroup\$
    – RubberDuck
    Commented Dec 22, 2014 at 19:02
  • \$\begingroup\$ Thanks voted up just one question what does it mean "/plug/pluginr/ it would still return true since indexOf returns an integer containing the position of the first ocurrence" ,but if I dont have this substring why its still true? \$\endgroup\$ Commented Dec 22, 2014 at 19:07
  • \$\begingroup\$ Have a read at MDN docs. And then have in mind that -1 in JS evaluates to true, not to false \$\endgroup\$ Commented Dec 22, 2014 at 19:15
  • \$\begingroup\$ You can very easily test your code with chrome console \$\endgroup\$ Commented Dec 22, 2014 at 19:16
0
\$\begingroup\$

While not directly address in renatoargh's answer, the answer to your first question is technically yes. If you need to return a result from an in/else block that is how it is done.

However, when the intent is to return a boolean value, you should not use if/else blocks at all. The boolean expression used within the else clause can be directly returned instead of explicitly returning true or false.


Note: Javascript is one of the easiest languages to execute these days and check to see how it is executing. Your second question implies that you are not sure if the code it executing properly. It is very straight forward to call this function with an argument you expect to return true and one you expect yo return false. This will tell you if things are working properly. You don't need to be afraid to get your feet wet and run the code you have written.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.