- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Do JavaScript arrays have an equivalent of Python’s "if a in list"?
In JavaScript Arrays are used to store multiple values in a single variable. This is compared to a variable that can store only one value. Each item in an array has a number attached to it, called a numeric index, that allows you to access it. In JavaScript, arrays start at index zero and can be manipulated with various methods.
This basically tells about true or false. If the item is found then it returns true, else false is returned. You can achieve the same in JavaScript arrays, using includes. Let’s dive into the article to understand more about the equivalent of python’s if. Before that let’s have a quick view on the JavaScript’s array.
Using include()
The includes() method checks to see if a particular value is present in an array's entries and returns true or false depending on the result.
Syntax
Following is the syntax for include() −
string.includes(searchvalue, start)
Let’s look into the following examples for getting better understanding
Example
In the following example, we are running the script to check the JavaScript equivalent of Python.
<!DOCTYPE html> <html> <body style="background-color:#EAFAF1;"> <p id="tutorial"></p> <p id="tutorial1"></p> <script> let myArray = ['Bmw','Benz','Rx100']; document.getElementById("tutorial").innerHTML=(myArray.includes('Rx100')+"<br>") document.getElementById("tutorial1").innerHTML=(myArray.includes('Verna')) </script> </body> </html>
When the script gets executed, it will generate an output consisting of true or false values on the webpage. which are obtained from the checking used in the above script.
Example
Consider the following example, here we are running the script for checking the JavaScript array equivalent of Python.
<!DOCTYPE html> <html> <body style="background-color:#D2B4DE ;"> <p id="tutorial"></p> <p id="tutorial1"></p> <button onclick="check()">Click</button> <script> function check(){ var nameList = [ "John", "David", "Bob", "Carol", "Sam" ] document.getElementById("tutorial").innerHTML=(nameList.includes("Bob")+"<br>"); document.getElementById("tutorial1").innerHTML=(nameList.includes("Adam")); } </script> </body> </html>
On running the above script, the output window will pop up, displaying the click button on the webpage. If the user clicks on the button, the event gets triggered and displays a true or false value on the webpage.