Javascript check if variable is defined

Code snippet to check if a given javascript variable is defined. This also covers a variable having null value and non existing entry in an array.

<script type="text/javascript">
var a = ["one"]
var v1 = "s";
var v2 = null;
if (typeof(v1) !== 'undefined') {
  document.write("v1 is defined<br/>");
} else {
  document.write("v1 is not defined<br/>");
if (typeof(v2) !== 'undefined') {
  document.write("v2 is defined<br/>");
} else {
  document.write("v2 is not defined<br/>");
if (typeof(v3) !== 'undefined') {
  document.write("v3 is defined<br/>");
} else {
  document.write("v3 is not defined<br/>");
if (typeof(a[1]) !== 'undefined') {
  document.write("a[0] is defined<br/>");
} else {
  document.write("a[1] is not defined<br/>");

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments