3

Recently I saw a statement that works in javascript on the internet and I wonder what the meaning of a single equal sign (=) in javascript as I mostly use in if statements is.
It is a comparison function which include double equal sign (==)

if(i = 1) {
    alert(i);
}

This works, I wondered what would happen when the if statement gets assigned to the value of 1 to the variable i and check the value of i which is the same as:

i = 1
if(i) {
    alert(i)
}

But I soon realised that the assignation of a value variable needs to have the keyword var so I changed the code to:

  if(var i = 1) {
        alert(i);
  }

This time the code doesn't work. Why?

Christian Heinrichs
  • 786
  • 1
  • 9
  • 28
dramasea
  • 3,370
  • 16
  • 49
  • 77
  • In JS and any other language the `=` is an assignment, not for comparison in a IF block. – dcodesmith Jul 31 '13 at 15:26
  • 2
    Just to be clear, this convention is bad because at first glance, it looks like you are checking if i is equal to 1, instead it is just always true. I understand this is more of a "why" question, but I can't think of an instance where this is ok to do. – Gray Jul 31 '13 at 15:27
  • The big problem here is that your example is trivial. A real use of this technique would look more like this: `if (x = validate(y)) {alert(x)};` -- here we are assigning an arbitrary value to x and then testing it. It's a shortcut from older times, when code had to be VERY efficient. –  Jul 31 '13 at 15:30
  • Keep in mind that you should always do strict comparison with `===`. There is no case when `==` is correct or can not be better written with `===`. – Halcyon Jul 31 '13 at 15:31
  • Sometimes you are not sure if the thing you are comparing is a 12 or "12". Then == is invaluable. – MightyPork Jul 31 '13 at 15:39

6 Answers6

5

The first part of your analysis is of course correct.

Now, the interesting part might be why your last code if (var ...) { doesn't work.

It doesn't work because

1)

var something

is a statement, not an expression.

2) here's how ECMAScript defines the if statement :

IfStatement :

if ( Expression ) Statement else Statement

if ( Expression ) Statement

You must put an expression in the if clause, not a statement.

More on expressions vs statement in this article.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3

If you check the console, it says Unexpected token var. You're just not supposed to declare variables in the condition of an if statement.

If you ever do actually mean to make an assignment inside the condition, just declare the variable first, like this:

var i;
if(i = 1){
   alert(i);
}

I see that you already know the difference between assignment and comparison, though, which is good :)

SharkofMirkwood
  • 11,483
  • 2
  • 17
  • 25
2

Single = is indeed an assignation, if you put it in the if condition it will not compare i against 1 but assign the variable i with the value 1 and then use that value as the condition itself, making i a truthy value. So yes, it is the same as you second example.

Also, in javascript it is better to use === instead of == if you are expecting the items to be the same type :

if (1 == '1') {
  alert('this is true'); // where you might actually expect it to be false, 

in this case it will work properly if you use triple equals (===).

if (1 === '1') {
  alert('this is false'); // which is expected
}
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
edgarjs
  • 506
  • 2
  • 9
  • 1
    Well, perhaps `it` is not `very` good idea `to` make every other `word` into a `code block`. It makes my eyes jump, really - but it could be just me. Plus, you give examples on something entirely different than the OP asks, but that's another matter. – MightyPork Jul 31 '13 at 15:35
  • @edgarjs sorry for so many edits, I kept seeing something not quite right about it. I think I captured your initial meaning as well as adding information to more accurately answer the question asked – Brett Weber Jul 31 '13 at 15:43
  • Your last one is confusing in that it implies that the `alert` will run even if the if statement is falsy -- try making the if block empty and placing the alert under an else statement. – Qantas 94 Heavy Feb 01 '14 at 03:24
1

Single = is an assignment operator and will always equate to true in an if statement (assuming it is a non negative value).

Double = ,as in ==, is a comparison and will equate to true only if the values on either side of the operator are equal.

Paddyd
  • 1,870
  • 16
  • 26
  • 2
    `if (x = "")` is always false – Alex K. Jul 31 '13 at 15:25
  • 3
    "*assuming it is a non negative value*" should read "*assuming it is not a falsey value*". It is misleading at best to say that "*an assignment operator and will always equate to true*"; you ought to say "*the truth value of an assignment is the same as the truth value of the value being assigned*". – apsillers Jul 31 '13 at 15:25
  • This doesn't answer the question which was why `if( var i = 1 )` doesn't work. – JJJ Jul 31 '13 at 15:25
  • @Juhana You think "it doesn't work cuz of syntax error there" would be a better answer? – MightyPork Jul 31 '13 at 15:27
  • @MightyPork Yes. At least it would answer the question. – JJJ Jul 31 '13 at 15:28
  • 1
    @MightyPork That would certainly at least answer the question as written ("*This time [with `var`] the code doesn't work, why?*"). – apsillers Jul 31 '13 at 15:30
  • Yes, but we are supposed to be constructive and explain the problem as good as possible, for future googlers, no? – MightyPork Jul 31 '13 at 15:33
  • 1
    @MightyPork Juhana's objection is not that the information in this answer is *wrong* (although some of it is, per my first comment), but that it is not *complete*. There is nothing wrong with an answer providing a robust explanation (e.g., to correct a misunderstanding in the question), but a robust explanation that does not actually address the particular question is insufficient. – apsillers Jul 31 '13 at 15:37
1

Single "=" means "assign to the left var".

As a return value for the IF, you get the value assigned, and since it is 1, the "true" branch is executed.

However, if you put "var" into the IF, it won't return the assigned value, and I think it won't even work at all.

Mistaking "=" and "==" is a common typo.

MightyPork
  • 18,270
  • 10
  • 79
  • 133
0

Your assertion is correct, in that the code is essentially assigning the value 1 to i and then evaluating the expression's truthiness (1 coeerces to true, so the condition passes).

The last example fails because you can't declare variables inside condition expression.

When you don't explicitly invoke the var keyword, the value will be assigned to any existing variable called i that's available in your scope, or, if none exists, create a property i and assign it to the global object (window), which are all callable without invoking the global object (which is why calling, say location will refer back to window.location — unless you've defined var location in scope).

Barney
  • 16,181
  • 5
  • 62
  • 76