Wednesday 3 January 2018

Javascript local and global variable confusion





I am new to JavaScript and I was doing some practices on local and
global variable scopes, following is my code( rel="noreferrer">fiddle):



class="snippet" data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">var myname =
"initial"
function c(){
alert(myname);
var myname =
"changed";

alert(myname);

}
c();





when
the first alert is called, it is showing myname as undefined.
so my confusion is why I am not able to access a global instance of
myname and if I don't define myname
within the function then it will work fine.


class="post-text" itemprop="text">
class="normal">Answer



In
Javascript, the variable declarations are automatically moved to the top of the
function. So, the interpreter would make it look more like
this:




data-hide="false" data-console="true" data-babel="false">
class="snippet-code">
var myname = "initial"
function
c(){
var myname;
// alerts undefined

alert(myname);
myname = "changed";
// alerts changed

alert(myname);

}
c();





This
is called 'hoisting'.



Due to hoisting and the
fact that the scope for any variable is the function it's declared in, it's standard
practice to list all variables at the top of a function to avoid this
confusion.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...