Defined and Undefined in javascript

Something Like that:
Defined and Undefined

First we should check undefined.

For that you need to create first html code.

HTML

<p>Value of a = <span id="demo1"></span></p>
<p>Status a = <span id="demo2"></span></p>

After that add this JS code.

JS

var a;
document.getElementById("demo1").innerHTML = a;

if (a === undefined){
  document.getElementById("demo2").innerHTML = 'a is undefined!';
} else {
  document.getElementById("demo2").innerHTML = 'a is defined!';
}

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”eEpbzG” default_tab=”result” user=”pradeepanvi”]See the Pen Defined and Undefined in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see

Value of a = undefined
Status a = a is undefined!

Now we want a should be Defined

After that add this JS code.

JS

var a = 'hello';
document.getElementById("demo1").innerHTML = a;

if (a === undefined){
  document.getElementById("demo2").innerHTML = 'a is undefined!';
} else {
  document.getElementById("demo2").innerHTML = 'a is defined!';
}

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”WErbKR” default_tab=”result” user=”pradeepanvi”]See the Pen Defined and Undefined in javascript 02 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now we can see

Value of a = hello
Status a = a is defined!

Leave a Reply

Your email address will not be published. Required fields are marked *