0

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user2998454
  • 147
  • 10
  • 1
    The equality-test operator is spelled `==` or `===`, not `=`. – cHao Jan 04 '14 at 05:16
  • **=** for assignment, not for comparision. Use **==** for comparision. – Kunj Jan 04 '14 at 05:16
  • Also please note that if you execute document.write after the page has loaded, it will wipe the page. Look into innerHTML soon – mplungjan Jan 04 '14 at 05:24
  • In your case, the if statement evaluates the expression (car=9). So it would be if(9).. This condition is true so that your document.write("your code is not working") get executed. Kindly use == or === if you need comparison with type check – Susai Jan 04 '14 at 05:26

4 Answers4

7

= 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 ===

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Thanks, it worked, but some YouTube tutorials use the single equal sign, code academy uses the three like you said. Is one tutorial an outdated version of the other? – user2998454 Jan 04 '14 at 05:17
  • @user2998454 `=` should be used only to assign values. To compare values you always have to use either `==` or `===`. Please check the link which I included in the answer. – thefourtheye Jan 04 '14 at 05:21
  • Regarding the tutorials that use a single equal sign in if statements, that is valid javascript, but it is checking the result of the assignment. In your code it is saying, if car=9 worked without issues, print the statement. – Ali Cheaito Dec 16 '14 at 18:48
0

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)
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
0

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

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

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

    if(car === 9){
      /*Your code goes here*/
    }
Shubham Nishad
  • 52
  • 1
  • 1
  • 7