We can use the JavaScript if not statement to check if a condition is not true. Usually in a JavaScript if-statement, we are looking to see if a certain condition is true. This can be useful in certain scenarios when we only want to know if a condition is false.

Here is the simple code for an if not statement:

if( !(someValue1 > someValue2) ){
  //This will run if the condition above is false
}

In the example above, notice that we use the negation operator !. This is a key part of an if not statement. So if the value someValue1 is greater than someValue2 making that part of the condition true, the not operator would then make the statement False. Which means that the if statement would not run the code inside.

Let’s take a look at a simple example of this to help explain it further.


In this example, we will simply have an if statement compare a couple of variables that represent numbers.

var num1 = 1;
var num2 = 2;
if( !(num2 > num1) ){
  //This code will not run
}

In the above code, since num2 > num1 will return true (since 2 > 1), we negate this result and so the if statement will be false and not run.

Let’s take a look at a couple more examples.

var numsArray = [1,2,3,4,5,6,7,8,9];
if( !(numsArray.includes(10)) ){
  console.log("10 is not included in the array");
}

#Output
10 is not included in the array

The above example uses the includes() method. To learn more about this method, check out this post on it.

And one more example:

var office_workers = [
  {id: 1, firstName: "John", lastName: "Smith"}, 
  {id: 2, firstName: "Jane", lastName: "Smith"}, 
  {id: 3, firstName: "Nicole", lastName: "Williams"}, 
  {id: 4, firstName: "Bill", lastName: "Brown"}, 
  {id: 5, firstName: "Sam", lastName: "Johnson"}
];

for( var i=0; i<office_workers.length; i++ ){
  if( !(office_workers[i].lastName == "Smith") ){
    console.log(office_workers[i]);
  }
};

#Output
{id: 3, firstName: 'Nicole', lastName: 'Williams'}
{id: 4, firstName: 'Bill', lastName: 'Brown'}
{id: 5, firstName: 'Sam', lastName: 'Johnson'}

The above example will check the array of worker objects and return any that Do Not have the lastName value of “Smith”.

Hopefully this article has been useful in helping you understand the JavaScript if not condition.

Learn more.

Categorized in:

JavaScript,

Last Update: May 3, 2024