0

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);
7
  • @NenadVracar it's true Commented May 13, 2017 at 9:58
  • It should work then jsfiddle.net/Lg0wyt9u/1902 Commented May 13, 2017 at 9:59
  • @NenadVracar its false statement .Because k is undefined .And case also defined inside the if is true .So you get undefined .declare the case as a global one.And don't forget define the k Commented May 13, 2017 at 10:00
  • @NenadVracar i have big code and the var declaration is in a function in the head and the call is in the body Commented May 13, 2017 at 10:00
  • what default value should Case have in advance? Commented May 13, 2017 at 10:03

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.