1

I have defined a javascript variable but it returns undefined.

variable = "";

if(somecondition){
      variable=myString.length;
}
alert(variable);

here variable returns undefined. If I keep the alert inside the if condition, I am able to get the value but its not working if I keep the alert outside the if condition.

Panther
  • 8,938
  • 3
  • 23
  • 34
SRM
  • 57
  • 2
  • 10

6 Answers6

1

Your myString does not have an property called length and hence you are getting undefined. Usually, String, array has length property while objects don't have it.

Either you are invoking a wrong property or invoking it on a wrong data type or you have to define one yourself :P

Panther
  • 8,938
  • 3
  • 23
  • 34
0

Using var will do it:

var variable;
Luiz Chagas Jr
  • 149
  • 1
  • 7
0

You need to declare and define your variable.

var variable = "";

if(somecondition) {
      variable = myString.length;
}

alert(variable);
James Monger
  • 10,181
  • 7
  • 62
  • 98
  • No. `var` isn't necessary, since all of the code is in the SAME scope. – Marc B Oct 14 '16 at 17:59
  • 3
    ^ although you should definitely declare your variables with `var` (or some other declaration keyword) to avoid making globals. – Mike Cluck Oct 14 '16 at 18:01
0
var variable = '';
if (true) {
     variable = 'Yes'
}
alert(variable);

This will show alert as Yes.

So in your case myString.length; is probably undefined

Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
0

Are you missing the initialization of mystring?

Look at the following

enter image description here

Pandiyan Cool
  • 6,381
  • 8
  • 51
  • 87
-1

If variable isn't undefined in the function, it's because it is still equal to the initial value, "" (Empty String).

What I bet is happening, is myString is actually a number and not a string. Try the following and see if you are still having a problem:

variable = "";

if(somecondition){
      variable=myString.toString().length;
}
alert(variable);
Andrew Vogel
  • 266
  • 2
  • 4
  • 14