Home > Enterprise >  How do I check if condition is true and run code? It's not working code below
How do I check if condition is true and run code? It's not working code below

Time:02-02

I tried to check if iteam1 is in the array iteamList and then run the code.

var itemsLists =  ["item1", "item2", "item3", "item4","item5"]; 
if (itemsLists === "item1") {
console.log("Here is iteam 1");} 
else{
console.log("it's not iteam 1");};

//output it's not iteam 1

I was expecting Here is iteam 1

CodePudding user response:

A scalar value will never be equal to an array - as you said you need to check if it is IN the array. The simplest way is to use array.includes() but arrays also have find and filter methods to search for matches....

if (itemsLists.includes('item1')) {

CodePudding user response:

Use this to check if this string exists in the list:

var itemsLists =  ["item1", "item2", "item3", "item4","item5"]; 
if (itemsLists.includes("item1") == true) {
    console.log("item in list");
}
else {
    console.log("item not in list");
}

Output:

"item in list"

This should help you with your problem. Also, please try to research and resolve your problem before posting to stack overflow.

CodePudding user response:

Use the includes function to check if this string exists in the list:

For example:

if (itemsLists.includes("item1")) {
    console.log("Here is item 1");
} else {
    console.log("it's not item 1");
}
  •  Tags:  
  • Related