I’m pretty new to javascript and I wasn’t able to make an if doesn't include
statement without changing my array to const
which ruins it. I was wondering if there is an option without const
I also tried
if (array.includes("tom")!=true)
and also tried
if (array.includes("tom")==true)
4
Answers
Just add an exclamation point (
!
) beforearray
to invert the expressionarray.includes("tom")
. You can read it as "if array does not include ‘tom’"I’m not sure why your
array
needs to beconst
, it should not affect the behavior of theincludes()
method. But since the method returns a boolean, to get the logical inverse of a boolean value, you can use the!
(NOT) operator in front of the value. Thus,!array.includes("tom")
is equivalent to saying "does the array NOT include the string ‘tom’".The
Array.prototype.includes()
method is used to determine whether an array includes a certain value among its elements, and returns eithertrue
orfalse
. If the array includes the value, it will returntrue
; otherwise, it will returnfalse
.Here’s how you would use it:
In this case, because "tom" is not in the array, it will log "Tom is not in the array." to the console.
Note that declaring
array
withlet
orconst
doesn’t change howincludes()
works. The difference betweenlet
andconst
is thatlet
allows you to reassign the variable to a new value, while const does not. However, bothlet
andconst
allow you to change the elements within the array, like adding or removing elements.If you want to test if an array does not include a certain value, you can use ! (the logical NOT operator) to negate the result of
includes()
:In this case, it will log "Tom is not in the array." to the console.
Array.prototype.includes() method is used to determine whether the assigned array contains the value mentioned or not and will return a boolean value as True or False as the returned output.
For Example: arr.includes("tom") : arr is an array and if that array contains the value "tom" it will return true or else will return false.
So, in your code you can write the if conditions in various manner:
if (array.includes("tom") !== true)
orif (array.includes("tom") === true)
, making sure it is a strict equality.if (!array.includes("tom"))
orif (array.includes("tom"))
, as we know that the return form the includes() method is a true or false boolean value.