Curiosities about parameters and variable declarations in Javascript

  1. <html>
  2. <body>
  3.  
  4. <script type="application/javascript;version=1.7">
  5.  
  6. function f1(parameter) {
  7.  alert(parameter);
  8. }
  9.  
  10. function f2(parameter) {
  11.  alert(parameter);
  12.  let parameter = "value";
  13. }
  14.  
  15. f1("hello");
  16. f2("hello");
  17.  
  18. </script>
  19.  
  20. </body>
  21. </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”.

4 thoughts on “Curiosities about parameters and variable declarations in Javascript”

  1. 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

  2. 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 🙂

Comments are closed.