P110
P110

Reputation: 192

Javascript - if else not setting var

I am having a bit of trouble with some javascript, I have searched for a question with an answer to this, but since it is probably one of the easiest things to do, I doubt anyone but myself could get it wrong.

I'm trying to simply make a content switcher, but the if statement that moved onto the next piece of content does not seem to be working:

//Work out next box
if (i == 2){var x=1;}else{var x=i+1;}

I've created a quick js fiddle (http://jsfiddle.net/TuMEa/5/) to try and get this working, I would be glad if someone could help me, thank you :)

(I have very little JS knowledge, but some programming knowledge (so I understand what things do))

Upvotes: 0

Views: 151

Answers (2)

Andrei
Andrei

Reputation: 3106

When you use a variable there are 2 parts to it:

  • declaration
  • definition

Also, {} creates a scope.

A variable lives (can be used) in the scope where it was declared.

Declaration

 var x;

A declaration means telling the program that inside this scope there is a variable called x.

Definition

 x = 3;

A definition means telling the program what value that variable holds ( points to ) and it can only be done if the variable was defined first.

As you can see here, you have to declare your variable outside of the accolades, in a common scope for both the if and the else.

http://jsfiddle.net/2hwG7/

var x, i = 1;
if (i == 2)
    x=1;
else
    x=i+1;

console.log(x);

The ?: operator

Also, as other users mentioned, in javascript there is a ternary operator(conditional operator).

Usage:

condition ? action1 : action2;

The above translates to:

if(condition) action1; else action2;

It is called ternary operator because it is using 3 operands.

Upvotes: 1

Uffo
Uffo

Reputation: 10046

i = 0;
x = 0;


if (i == 2){x=1;}else{x=i+1;}

console.log(x);

http://jsfiddle.net/9TXJ9/

You are using var which creats the variable in the block scope only.

Upvotes: 0

Related Questions