JavaScript hoisting refers to a default behavior of moving declarations to the top. JavaScript allows a
variable declared after it has been used , or in other word we can say we can declare a variable after using it. However, JavaScript only hoists declarations but not initialization. For e.g.: you can declare
(var X) but you cannot initialize (var X=3).
Example:
Example:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8"/>
<title>JavaScript Hoisting Tutorials</title>
</head>
<body>
<!-- Declaring Hoisted -->
<h2>Example of Hoisting</h2>
<p>First Number:<span id="first"></span></p>
<p>Second Number:<span id="second"></span></p>
<p>Sum of Two Numbers: <span id="sum"></span></p>
<p>Example of Hoisting</p>
<p>First Number:<span id="a"></span></p>
<p>Second Number:<span id="b"></span></p>
<p>Sum of Two Numbers: <span id="c"></span></p>
<script>
//JavaScript Declarations are Hoisted
function declare() {
//JavaScript Hoisting is the default behavior of moving all declarations to the top of the current
scope
var a, b, c;//declaration
a = 20, b = 15;//assigning value to the variable
c=a+b;
x=document.getElementById("first"); y=document.getElementById("second"); z=document.getElementById("sum"); x.innerHTML=a; y.innerHTML=b; z.innerHTML=c; //You can also declare variable here. eg,vara,b,c works } function initialize(){ //JavaScript initialize are Hoisted var a = 30, b = 40; var c=a+b; document.getElementById("a").innerHTML=a; document.getElementB(
yId"b").innerHTML=b; document
No comments:
Post a Comment