Reputation: 3
I am learning JS through some exercises. One of them is about writing a function that checks whether a number is prime or not. The correct answer to this exercise is this one:
const isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
I'm accustomed to inserting return false;
inside the if
argument and the return num > 1;
or return true;
outside of it, right after the closing bracket that ends the if
argument, as with the if
statement I am usually telling to my function "if this condition fulfilled, return this" and right after having closed the if
statement I'm telling it "...otherwise return that". I cannot understand why in this case both the return instructions have be inserted inside the argument, what's the logic behind that?
Upvotes: 0
Views: 44
Reputation: 343
This
const isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
is equivalent to
const isPrime = num => {
for(let i = 2; i < num; i++){
if(num % i === 0){
return false;
}
}
return num > 1;
}
Explanation
Blocks of codes are usually enclosed in curly braces { code }
. So when some part of code needs to be executed inside a for loop or after if condition we enclose it in curly braces. However, if there is only one statement that needs to be executed after if or inside for loop, we don't have to use braces. The code considers the immediate next line after if condition/for loop belongs to it.
//if
if(condtion){
console.log("hello world");
}
//for
for(let i=0;i<num;i++){
console.log(i);
}
//also equals to
if(condition)
console.log("hello world");
//for
for(let i=0;i<num;i++)
console.log(i);
Upvotes: 2