+ 1

Thats has any way write a function with sentences after the return reserved word? Any functionality with a special alghorithm?

13th Mar 2019, 7:59 PM
Mike Portillo
Mike Portillo - avatar
2 Antworten
+ 2
Yes, you can write after returning, but only if the it returns when an if or else if etc. statement returns true, so the example under this will return and then not do everything what's written after: function doSomething(num){ num++; return num; //this part will be skipped, since we already returned num num *= num; } //or you could do things like this if you want to toggle a variable where you have to pay attention to first switch the boolean otherwise it will skip it function anotherThing(bool){ bool = !bool; return (bool)? "Hello" : "Bye"; } function anotherThing(bool){ return (bool)? "Hello" : "Bye"; bool = !bool; } //Here the boolean wouldn't be switched
13th Mar 2019, 8:13 PM
Roel
Roel - avatar
+ 1
Example : a few sorting algorithms function isDone(array){ for(let i in array){ if(array[i] > array[i+1]){ return false; } } return true; } // returns true if all numbers are smaller then the next one
13th Mar 2019, 8:03 PM
Roel
Roel - avatar