PDA

View Full Version : Javascript Wicked Behavior



[s]
07-02-2011, 08:00 AM
Hello , i would like to share this interesting thing about the java script ..

i was writing one program in JS for my client yesterday night ...

In every programming , if you declare a variable globally or in the function then it must execute with proper declared value .. but it is not working properly :P

here is the example



var g4h="h4x0r-l33t";
function h4x0r()
{
alert(g4h);
var g4h = l337;
}


the output of this program will be ? l337 or h4x0r-l337 ...... But the output of the program is :) " undefined " yes it is undefined...

I don't why this happening ... Another ugly thing is this fake OOP is js

"vinnu"
07-04-2011, 09:29 AM
Its not the weird behaviour, but rather scope confusion. Within the function scope you are once again defining same variable with var... oh leave it u'll say it will be local, yes but interpreter confuses to mix the global and local within same block and thats why doesnt mix globals with locals.

So if you are instantiating same name variable, again the earlier instructions will not resolve it as now global variable is not mapped to same function scope (block).

To access the value of global variable, just ommit the "var" withing the function.

[s]
09-14-2011, 10:55 AM
Yes , Exactly i got it now :) the problem of local and global variable but i want to say say every OOPS has the functionality to avoid this kind of problems

4vk
12-15-2011, 10:34 AM
This is known as variable hoisting.
one of the known and famous behavior of javascript
Adequately Good - JavaScript Scoping and Hoisting - by Ben Cherry (http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting)