Javascript variable hoisting example -
i have question on variable hoisting in javascript.
consider next example;
var myname = "richard"; // variable assignment (initialization) function myname () { console.log ("rich"); } console.log(typeof myname); // string
i confused why typeof myname
returned string.
as per understanding, illustration proceessed below;
first function declaration (function myname ()
) hoisted top , then js interpreter read line var myname = "richard"
(since function declaration gets precedence on variable declaration). however, since there property name "myname", statement ignored. thus typeof myname
should returned function (and not string)
please allow me know understanding incorrect.
javascript has dynamic type system, i.e. type of variables can alter on time. basically, write correct: first, function declaration gets run (on loading file), function stored in variable myname
beingness overwritten string.
the thing gets ignored phone call var
, variable declared.
but valid re-define variable (and that's here, assigning new value).
in end, sample nil this:
var x = 23; x = 'foo';
this work well, x
'foo'
, , type going string
. difference sample in yours, value of type function
involved.
javascript hoisting
No comments:
Post a Comment