0

How does the "if" work?

Lets say i have something like: if(checkSomething() && checkSomethingElse()){...} Where checkSomethingElse() does a api call. If checkSomething() returns false, does the second function get called? I was wondering if this would do useless api calls whenever the first function returns false

16th Sep 2024, 4:34 AM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
4 Réponses
+ 6
🍇 Alex Tușinean 💜 you didn't mention which language, but that's no matter. All the languages in which that syntax is valid do short-circuit conditional evaluation as you described. It is evaluated left-to-right. If the first condition is False, then the second condition will not get evaluated. That also means it will not even call the second function.
16th Sep 2024, 4:52 AM
Brian
Brian - avatar
+ 3
In this case you have used logical and operator (&&) where if both are true then it's true otherwise it's false. In addition both functions will be called and return true or false based on the function criteria and if overall it is true it will enter inside the if statement and execute the statements otherwise it won't execute.
16th Sep 2024, 4:57 AM
Aysha
Aysha - avatar
+ 2
2nd function may execute in case by mistake if you used single '&'
16th Sep 2024, 5:55 PM
A͢J
A͢J - avatar
+ 1
checkSomething() will be true if it returns anything that's not explicitly false or the integer, 0, Then checkSomethingElse() will be called no matter what Otherwise checkSomething () is false and only checkSomethingElse() will be called, no matter the condition. In mathematics, these type of expression under logical reasoning are called "bidirectional statement" and "converse statement" for both instances respectively. if P and Q are any statement, the likely result falls under p <=> q p => q in both cases, Q is always evaluated
16th Sep 2024, 9:29 AM
Sharpneli
Sharpneli - avatar