简体   繁体   中英

JavaScript if statement not behaving as expected

Just learning to code JavaScript, trying to learn if statements but my code isn't working:

var car = 8;
if (car = 9) {
    document.write("your code is not working")
}

This executes the write command and I have no idea why. I'm using the tab button for indents, is that not allowed?

= is called assignment operator in JavaScript, it assigns the value of the right hand side expression to the variable on the left hand side.

You have to use comparison operator instead of assignment operator like this

if (car === 9)

We have two comparison operators in JavaScript, == and === . The difference between them is that,

== checks if the values are the same, but === checks if the type and the value is also the same.

Go through the wonderful answers, to know more about == and ===

This line assigns car to the value of 9 and check if it is truthy (which 9 is).

if (car=9)

I think you want to use a comparison operator, like this:

if(car == 9)

use this code

var car = 8;
if (car==9)
  {
  document.write("your code is not working")
  }

you need to understand about operators '=' is an assignment operator whereas '==' is a comparision operator.

See Tutorial

If you want to compare if car is equal to 9, then you have to use code

    if(car === 9){
      /*Your code goes here*/
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM