Andrew Heid
Andrew Heid

Reputation: 93

Javascript var declaration vs equivalent

This could be insanely inane... But I am still learning.

Let's take the lesson from Code Academy(since I am literally learning at that low of level) at section 1 lesson 28.

Instructions: Write your own if / else statement. The only instruction is that the result of evaluating the statement is a log to the console of "I finished my first course!".

I wrote:

var num = 1;

if(num = 2){
console.log("Testing Fail");
}
else{
console.log("I finished my first course!");
} 

this did not work... but after thinking a moment I gave a shot

var num = 1;

if(num == 2){
console.log("Testing Fail");
}
else{
console.log("I finished my first course!");
}

This worked. So. I named my variable num and set it equal to 1. I then said if num is equivalent to 2 then the console.log would write "testing fail" - else it writes "I finished my first course!"...

It doesn't explain why my first try didn't work. I declared my variable to equal one, but then I said in my if/else statement that if my variable equaled 2 then to do the condition. Why can I not declare a statement twice, or at least in a conditional statement?

I am missing the logic here... probably simple but I am learning.

Upvotes: 0

Views: 154

Answers (4)

potashin
potashin

Reputation: 44581

= is for assignment and == is for logical operator (comparison : equal to). So in the first case (num = 2) you assigned your num value to the 2 (assignment returned value, 2, so evaluated as true) and in the second case (num == 2) you checked if num equals 2 (evaluated as false).

P.S. : There is also === logical operator that checks if values are exactly equal (equal value and equal type).

Upvotes: 2

RaviH
RaviH

Reputation: 3584

Others have already pointed out the difference: if (num = 2) in first case and if (num == 2) in the second case. But nobody has pointed out what exactly happened in the first case. In the first case when you did if (num = 2), the expression num = 2 assigned 2 to the variable num. Javascript assignments return the assigned value. As a result of assignment, number 2 was returned. End result of your expression if (num = 2) is equivalent to if (2) which is equivalent to if (true) because javascript considers 0 as false and any non zero value as true. That is why in the first case you saw Testing Fail printed to console.

Upvotes: 2

KrishnaDhungana
KrishnaDhungana

Reputation: 2684

In first case, = is assignment operator

In second, == is is logical operator.

Actually, it is better to use === instead of ==.

Upvotes: 1

AlexQuezada
AlexQuezada

Reputation: 143

just because of the "=", in te second try you used "==" and works.

This "=" is for assign, for example:

var num=2;

This "==" is to compare for example:

if(num==2)

So you can't use an assignment instruction to evaluate an equality, hope you get it :D, good luck in your coding

Upvotes: 2

Related Questions