Monday, November 25, 2013

JavaScript – Few Things to Know About – Part 1

Recently I participated in a conference for developers and learnt about some of the best practices to follow when writing JavaScript. This post is mainly about how JavaScript concepts and syntax differ from Object Oriented Programming (OOP) languages like C# or Java. Examples I'm providing here are almost same as the ones I learnt during the session and they will definitely help us troubleshoot JavaScript related issues in out projects.

Example 1:
Defining variables with var makes it a local variable for the scope. If the variable is defined without the var it will be a global variable.

<script type="text/javascript">
   var foo = function () {
      var local = 1;
      global = 2;
      alert(local);
   }
   foo();
   //alert(local); //local is ‘undefined’ here.
   alert(global);
</script>

Output = 1, 2

Even though the variable “global” is defined within the function, once the function is called, the variable is available outside the function since it is defined without var. But variable “local” is not accessible outside the function since it is defined with var.

Example 2:
Block concept is not there in JavaScript. No need to define variables as close as to the place we use them.

<script type="text/javascript">
    var foo = function () {
        if (true) {
            var local = 1;
        }
        alert(local);
    }
    foo();
</script>

Output = 1

Variable “local” is defined within the if block and it is still accessible outside the block.

Therefore it is a good idea to define all the variables at the top of the function. So it is easy to keep track of them.

Example 3:
Assign function definitions to a variable and use it.

<script type="text/javascript">
    function foo(n) {
        alert("Foo with " + n);
    }
    foo(5);
    function foo(n) {
        alert("Redefined foo with " + n);
    }
    foo(5);
</script>

Output = Redefined foo with 5, Redefined foo with 5

Even though we expect output to be “Foo with 5, Redefined foo with 5”, it is not the case. The latter definition of the function will run twice.

Since it is very much a possibility to have two JavaScript functions with the same name mistakenly in a long script file (since there are no warnings or errors); we can use following syntax to avoid accidental definitions from overriding the previous one.

<script type="text/javascript">
    var foo = function (n) {
        alert("Foo with " + n);
    }
    foo(5);
    var foo = function (n) {
        alert("Redefined foo with " + n);
    }
    foo(5);
</script>

Output = Foo with 5, Redefined foo with 5

Now it works as variable assignments and output will be as expected. Using the same variable name on both occasions is not an issue.

Example 4:
JavaScript try to be over smart and will add semicolon at the end of the lines.

<script type="text/javascript">
    var foo = function (n) {
        if (n > 1) {
            return
                n * 2;
        }
        return 0;
    }
    alert(foo(-5));
    alert(foo(5));
</script>

Output = 0, undefined

Even though we expect the output to be “0, 10” in the above example, it is not the case. JavaScript will automatically add a semicolon at the end of first return statement. Therefore it won’t process n * 2 segment. Correct syntax in this case is to have the complete return statement in a single line; like:

if (n > 1) {
    return n * 2;
}

Example 5:
JavaScript functions always have variable number of parameters.

<script type="text/javascript">
    var max = function (a, b) {
        if (a > b) {
            return a;
        }
        return b;
    }
    alert(max(1, 2));
    alert(max(3, 1));
    alert(max(2, 4, 1));
</script>

Output = 2, 3, 4

First and second function calls work as we expect. But for the third call we usually expect an error since there are 3 parameters specified. Still it runs with the first 2 parameters taking into the consideration. Third parameter will be safely ignored as it is not used in the function body. If we need to use the 3rd parameter in this case, we can access the value as “arguments[2]

Here you can find more examples on two others posts:
  • Part 2 – JavaScript Methods
  • Part 3 – JavaScript Prototype

Thanks Venkat Subramaniam for the great session!

1 comment:

pacawagar said...

Play the best free slot machine games online - DrmCD
› games › slots › games › games 진주 출장안마 › slots › slots 구미 출장마사지 › games Play the 속초 출장안마 best free slot machine games online and 익산 출장샵 win real money with Dr. Green Casino. Enjoy exciting 김해 출장마사지 jackpots, free spins and other casino games!