Variable Environments in javascript

Something Like that:
Variable Environments

For that you need to create first html code.

HTML

<p>Value of function a =  <span id="demo1"></span></p>
<p>Value of function b =  <span id="demo2"></span></p>
<p>Value of global myvar =  <span id="demo3"></span></p>

After that add this JS code.

JS

//Variable Environments
function b(){
    var myvar;
  document.getElementById("demo2").innerHTML = myvar;
}
function a(){
    var myvar = 2;
  document.getElementById("demo1").innerHTML = myvar;
    b();
}
var myvar = 1;
document.getElementById("demo3").innerHTML = myvar;
a();

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

Now you can see

Value of function a = 2
Value of function b = undefined
Value of global myvar = 1

Why it’s showing function b undefined?
Because you can see in the global my It’s find declared value and function a as well. But and function two var only declared But not assign any value. that’s why.

Leave a Reply

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