Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

How does the single equal sign work in the if statement in javascript

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...