JSFiddle - React, Tailwind, and code Playground
by Dinesh Patra
HTML
<h3 id='title'>
Variable scope in javascript function:
</h3>
<p>Result:</p>
<div id='result'></div>
CSS
h3#title {
color : rgb(60, 60, 60);
font-family : Arial;
}
div#result {
background-color : #CCFFCC;
padding : 10px;
border : rgb(190,190,190) 1px
solid;
}
JavaScript
var global=1;
/****
* We have defined the variable local inside the *
* function. So local is visible only inside the
* the function. It can not be accessed from outside
* the function.
*/
function f() {
var local = 2;
global++;
return global;
}
// Calling the defined function.
f();
try {
// Trying to access local from out the function
document.getElementById('result').innerHTML = local;
} catch(e) {
// Print the corresponding error message.
document.getElementById('result').innerHTML = e.message;
}