Why we only return in between if condition. Can anyone help me understand that condition?
if (!name.trim()) {
return;
}
We return in it because we will haven't to run code after the conđition. Increase performance and clean code
The reason we just return is to terminate the execution of the function:
Here is an example with return:
const test = Array(100).fill(1)
const getFifty = (arr) => {
let sum = 0
for(let i = 0; i < 50; i++){
sum += arr[i]
if(sum >= 50){
console.log("Sum is fifty at index" , i)
return
}
}
console.log("Sum is never fifty")
}
getFifty(test)
Here is an example without return:
const test = Array(100).fill(1)
const getFifty = (arr) => {
let sum = 0
for(let i = 0; i < 50; i++){
sum += arr[i]
if(sum >= 50){
console.log("Sum is fifty at index" , i)
}
}
console.log("Sum is never fifty")
}
getFifty(test)
Actually when we use return in this situation, we have found the expected result and we do not need continue remain body of the function. Let's explain with an example. Assume that we would like find 75 from a loop with index and return the result. When we found the result, we do not need to execute the remain of functions body. This example also calculate the time between when you do not execute remain body of function, versus when you execute remain body of function. You will see that it effect on time of the execution, too.
function testWithoutReturn() {
let result = 0;
let t1 =new Date();
for (let i = 0; i < 100; i++) {
if (i == 75) {
result = 75
console.log("result founded but I will continue the loop needles!")
}
console.log(i);
}
let t2 = new Date();
getTimeDif(t1,t2)
}
function getTimeDif(t1,t2){
var dif = t1.getTime() - t2.getTime();
var sconds = dif / 1000;
var result = Math.abs(sconds);;
console.log(result)
}
testWithoutReturn()
function testWithReturn() {
let result = 0;
let t1 =new Date();
for (let i = 0; i < 100; i++) {
if (i == 75) {
result = 75
console.log("result founded and it doesn't need to continue loop")
let t2 = new Date();
getTimeDif(t1,t2)
return;
}
console.log(i)
}
}
function getTimeDif(t1,t2){
var dif = t1.getTime() - t2.getTime();
var sconds = dif / 1000;
var result = Math.abs(sconds);;
console.log(result)
}
testWithReturn()