-
<html>
-
<body>
-
-
<script type="application/javascript;version=1.7">
-
-
function f1(parameter) {
-
alert(parameter);
-
}
-
-
function f2(parameter) {
-
alert(parameter);
-
let parameter = "value";
-
}
-
-
f1("hello");
-
f2("hello");
-
-
</script>
-
-
</body>
-
</html>
Continuing with the “Curiosities” serie, today I bring another one: Javascript doesn’t take too well the definition of a variable with the same name as a function parameter. If you do this, the parameter is lost.
Copy the code to a local file and try it yourself… Surprisingly, the second alert will print “undefined”.
This is because “let” does not work in the same way as “var”. “var” (re)defines a function from that line on; “let” defines a new one with that name in the whole block.
See this rhino session:
jtarrio@vetinari:~$ rhino -version 170
Rhino 1.7 release 2 2009 04 21
js> function a(x) {
> var x = “X”;
> print(x);
> }
js> function b(x) {
> let x = “X”;
> print(x);
> }
js> function c(x) {
> print(x);
> var x = “X”;
> }
js> function d(x) {
> print(x);
> let x = “X”;
> }
js> a(“O”);
X
js> b(“O”);
X
js> c(“O”);
O
js> d(“O”);
undefined
The behaviours of functions a() and b() are clear: a variable “x” is set to the value “X” and that’s what’s shown.
The behaviour of c() is clear too: the value of the parameter is shown, then reassigned.
However, the behaviour of d() is strange until you remember that “let” creates a new variable within the block scope, called “x”. As it is not initialized until after the print() function, what’s printed is its default value, which is “undefined”.
Recommendation: https://developer.mozilla.org/En/New_in_JavaScript_1.7#Block_scope_with_let
PS: Javascript is not really such a strange language. It is quite nice, actually. You should get to know it better before leaving it for a lost cause. I didn’t read it, but I’ve heard lots of good things about the book “JavaScript: the Good Parts”, so perhaps you should read it 🙂
Thank you very much for all your comments and suggestions.
Oh nice code snippets. Thank