# Return whether any two sums to k

For example, given [3, 1, 3, 7] and k of 10, return true since 3 + 7 is 10

``````function toSum(nums, k){

for(var i = 0; i < nums.length - 2; i++){
for(var j = i + 1; j < nums.length - 1; j++){
if(nums[j] + nums[i] === k){
return true;
}
else
return false;
}
}
}

toSum([3, 1, 3, 7], 10);
``````

what is an error…

You are experiencing an early return, because your for loop only checks the first two numbers (3 and 1) and then returns false. When a return statement is encountered, the function is immediately exited even if a loop has not completely iterated.

thank you sir,
problem is solved

``````function toSum(nums, k){
var result = '';
for(var i = 0; i < nums.length - 1; i++){
for(var j = i + 1; j < nums.length; j++){
if(nums[j] + nums[i] === k){
return   'true';
}
else
result = 'false';
}
}
return result;
}

toSum([5, 1, 3, 4], 2);
``````

``````function toSum(nums, k) {
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[j] + nums[i] === k) {
return true;
}
}
}
return false;
}
``````
2 Likes

sir, you are right…

and use array.filter function when false or reduce when true?

1 Like