Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong too return different types in a javascript function?

Is it wrong to return two different types from a JavaScript function? This is often the case in PHP. For instance PHP's strpos()-function returns an integer telling you the position or false if not found. In Java this would not be possible since it's not a loose typed language and the return type is defined with the function.

So would be be wrong to do the same in JavaScript?

E.g.

function num(x, y) {
  if (x !== y) {return false;}
  if (x < 5) {return 5;}
  return x;
}

In above example we return an integer or boolean. But is it wrong? Would it make the life of the JavaScript engine harder and perhaps force it to de-optimize?

Or in another example, what if I have a function that creates an element and tries to put it into the DOM then returns the newly created element object. But if it can't find the parent element you send as an param it return false.

like image 408
jamietelin Avatar asked Dec 11 '25 05:12

jamietelin


1 Answers

This is not wrong, since Javascript is dynamically typed.

However, it is often considered as bad taste: makes the code less readable, and might make it less efficiently translatable by JIT techniques.

like image 195
Basile Starynkevitch Avatar answered Dec 13 '25 18:12

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!