Wednesday, December 21, 2016

Javascript-8-strictmode keyword/access global variable



strictmode;

This key is applied to disable all global variables and global functions. Refer the example below

<html>
<body>

-----Display carName below, prior to "strictmode; " -------<br><br>
>>>><p id="demo"></p>
-----Display carName below, after "strictmode; " -------<br><br>
>>>><p id="demo1"></p>
<script>
//strictmode;
myFunction();
document.getElementById("demo").innerHTML =  carName;

strictmode;
myFunction();
document.getElementById("demo1").innerHTML = carName;

function myFunction(){carName = "Volvo";}
</script>
</body>
</html>

O/P:
----Display carName below, prior to "strictmode; " -------
>>>>
Volvo
-----Display carName below, after "strictmode; " -------
>>>>



----------------


Global variables can be accessed in 2 ways

1) directly access the variable name

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = "I can displaynnnnnn " + carName;
</script>

2) access the variable using the window keyword

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = "I can displaynnnnnn " + window.carName;
</script>

Note: Variables created without the keyword var, are always global, even if they are created inside a function.

----------------

The Lifetime of JavaScript Variables

  • The lifetime of a JavaScript variable starts when it is declared.
  • Local variables are deleted when the function is completed.
  • Global variables are deleted when you close the page.


----------------

1 comment: