S.ElBahloul
S.ElBahloul

Reputation: 75

Defining variable within if statement in javascript

I want to assign a value to a variable when a condition is verified like this

if (k<12){

var Case=4;

} 

The problem when i call this variable to be printed in the body of the page i get undefined

document.write(Case);

Upvotes: 0

Views: 841

Answers (3)

user8003769
user8003769

Reputation:

You are getting undefined because you have not actually defined it. You are defining it when the condition is true. You should write the code like this.

var Case = null;
var k = 0;

if(k > 14) {
  Case = 3;
}

document.write(Case);

I hope it was helpful.

Upvotes: 1

Gustav P Svensson
Gustav P Svensson

Reputation: 517

var Case = 0;
if(k<12){
  Case = 4;
}
document.write(Case);

You need to define it first so if k<12 == False it wont be undefined.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

Basically your var statement gets hoisted and assigned with undefined.

Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.

Order of execution:

var Case;        // hoisted, value: undefined

if (k < 12) {
    Case = 4;
}

Upvotes: 3

Related Questions