1

I have the following code snippet.

$scope.functionName = function(id) { var flag = true; var numbers = [1, 3, 30]; for (var i = 0; i < numbers.length; i++) { if (id == numbers[i]) { flag = false; } else { flag = true; } } if (flag == true) { console.log("this is true"); } if (flag == false) { console.log("this is true"); } } 

What I want to perform is, if the input value is in the array, flag value should be false and if not it should be true. But, in this code snippet although flow goes inside the for loop after that it doesn't go to any of the if conditions. After entering the for loop it directly outputs "this is true". flag is always being true.

4
  • 2
    Why are you using "true" and "false" instead of true and false? Commented Apr 4, 2019 at 8:30
  • Thanks for pointing out that @jonrsharpe. Even though I changed flag to boolean still flow is not going inside comparing if condition. Commented Apr 4, 2019 at 8:34
  • try something shorter, like $scope.functionName = function(id){ return [1,3,30].includes(id)} Commented Apr 4, 2019 at 8:35
  • Both console.log statements say "this is true". Commented Apr 4, 2019 at 16:11

3 Answers 3

2

here is a cleaner approach at what you are trying to achieve

checkIfNumberIsInArray = function(number, arr) { return arr.includes(number) } console.log(checkIfNumberIsInArray(1, [1,2,3,4,5])) // true console.log(checkIfNumberIsInArray(6, [1,2,3,4,5])) // false 

See MDN JavaScript Reference - array.includes

Sign up to request clarification or add additional context in comments.

Comments

0

Add a break statement when your value equal to a value in array.

 $scope.functionName = function(id) { var flag = true; var numbers = [1, 3, 30]; for (var i = 0; i < numbers.length; i++) { if (id == numbers[i]) { flag = false; break; } } if (flag == true) { console.log("this is true"); } if (flag == false) { console.log("this is false"); } } 

1 Comment

The else clause is a waste of time.
-1

You don't need to loop the array, just use indexOf. Also try to use number type for numbers, and boolean type for booleans, you are using string for both

$scope.functionName = function(id) { var numbers = [1, 3, 30]; var flag = numbers.indexOf(parseInt(id, 10)) > -1; // Convert to number just in case if(flag === true) { console.log("this is true"); } if(flag === false) { console.log("this is true"); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.