0

How to check if a value has been assigned to a variable?

I start with

var val = '';

//then later I assign a value to val. So before val is used anywhere I need to be sure if there is a value assigned to val. How do I do this?

if (typeof name !== "undefined"){
     //a value is defined
}

or

if (name != null){
   //a value is defined
}
Becky
  • 5,467
  • 9
  • 40
  • 73
  • Wouldn't they both break - based on your initial sentence - if the value of `undefined` or `null` was explicitly and deliberately assigned to those variables? – David Thomas Jun 02 '16 at 12:40
  • @DavidThomas Thank you. Values of `undefined` or `null` will not be assigned deliberately. – Becky Jun 02 '16 at 12:44
  • @naomik Thanks. See my edit. `var val = '';` Then later I assign a value to val. So before val is used anywhere I need to be sure if there is a value assigned to val. How do I do this? – Becky Jun 02 '16 at 12:48

0 Answers0