JSFiddle - React, Tailwind, and code Playground
by Dinesh Patra
HTML
<h3 id='title'>
Variable scope in javascript function:
<br/>
(Variable defined without var keyword)
</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 but without var keyword. Now it can
* be accessed from outside
* of the function.
*/
function f() {
local = 'Hello World!!!';
global++;
return global;
}
// Calling the defined function.
f();
// Now try to access the local variable.
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;
}