Skip to main content
search

© 2021 Excellerate. All Rights Reserved

Software Development

JavaScript Tips for Backend Developers

By January 27, 2015June 10th, 2021No Comments

Are you a server side developer who struggles with front end development using JavaScript? This blog post will help!
This blog discusses some tools provided by modern browsers exist that make our life easier; plus some points where JavaScript differs from common server side languages. Here we try to understand those differences and see how to use those to our benefit, rather than getting confused about them.
Let’s take the first step toward understanding JavaScript as a language.
Useful JavaScript tools
Major modern browsers, such as IE, Chrome, Mozilla, are creating built-in extensions known as developer tools. They have very good features that ease a developer’s life. The following discusses two of these tools: Debugger and Console. 
Debugger
JavaScript slows down your development speed considerably if you are debugging using “putting alert statements”. Thanks to developer tools, debugger responds like the debugger provided in eclipse IDE for java.

How to use debugger

Below are simple steps to use debugger:

  1. Start browser and then press f12, which will open developer tools.
  2. Click on “Sources” as shown in the figure below.  It has three panels: left, middle and right.
  3. Left panel has a tree structure where you can find loaded .js files. If you click on a particular .js file, it will open in middle panel.
  4. In middle panel you can add a break-point at line number you want.
  5. Once the code comes to the break-point, it will stop.  Then by using the right panel you can do the debugging line by line.

1stImage
So now instead of putting those tedious alert statements you can debug easily.
Console
When we are working with web application any small change in code, needs start and stop of server, which is time consuming. This is true even if we doing changes in JavaScript code and when we are writing heavy logic it need lot of iterations. In such case console helps a lot. You can develop and test your logic using console. Once logic is finalized, then you can put it in code.
How to use console
Below steps will help you to use console.

  1. Start browser and then press f12, which will open developer tools.
  2. Click on “Console” as show.
  3. Type your js code.

2ndImage
As shown above, first I created HelloWorld function, which displays “Hello World!!” on the console. Then I called that function.
The console has an auto complete feature. The console gives you only one line to type, but you can type multiple JavaScript statements by using a semicolon.
In this blog, I am giving small code snippets which can be directly copied and pasted in the console, so that you can tweak and play around them.
By now, we are ready with JavaScript Debugging tools, Let’s start utilizing it’s real power of JavaScript – 

JavaScript vs. other programming languages.

This section covers the confusing behavior of JavaScript, which can trouble a developer. The reason for this confusion is that we do not know JavaScript basics and expect it should behave like server side languages, such as java, php, etc.
Variable in JavaScript
There are two types of variables: global variables and local variables. The former describes the variable that shares global space, while the later are variables that share function space, as JavaScript supports function scope.
Usually C family language follows block scope, while JavaScript follows function scope – this usually creates a lot of confusion.
What is function scope
Unlike other languages, in JavaScript variables are not define in block scope, but in a function scope. This means the variable defined in a function is not visible outside of that function. However, a variable defined inside a code block, such as “if” or “for”, is visible outside that block but inside same function.
Example to understand function scope


var a = 123;
function f() {
    alert(a);
    if(true){
        var a = 1;
    }
    alert(a);
}
f();

You might expect first alert to display 123 (for global a) and second will show 1 (for local a). But the first alert will show undefined. This is because inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert, a variable was not yet defined (hence the value undefined) but it still existed in the local space.
Things to keep in mind about variables

  • Always try to minimize number of global variables. Imagine two people are working two different functions in the same script and both decided to use the same name for their global variable. This could easily lead to unexpected results and hard to find bugs.
  • Avoid accidental creation of global variables. If you declare a variable inside a function without using “var”, then it will become a global variable. So always use “var” to declare a variable.

Parameters in function
In case of parameters to function many languages are very strict. If you pass less or more parameters than required, then they throw compile time exception. On the other hand, JavaScript is very flexible about parameters.  When defining function, one can specify what parameters it requires. If you forget to pass the required parameter to function, JavaScript will assign undefined to those. If you try to pass more parameters than the function excepts, it will silently ignore the extra parameters.


function sum(a,b){
     return a+b;
}

Consider the above: function sum adds two numbers which are passed as a parameter. If we call sum(1), then it will return NAN as it tries to add 1 + undefined. If you call sum(1,2,3,4) will return 3, ignoring 3 and 4.
Bonus object: ‘arguments’
There is an arguments object automatically created inside each function, which contains all the parameters passed. By using this, we can make the sum function more flexible as shown below.


function sumAll(){
     var total = 0, i;
     var noOfParameter = arguments.length;
     for(i=0; i< noOfParameter; i++){
          total += arguments[i];
     }
     return total;
}

The above function will work for any number of parameters. For sum(1,2,3) it will return 6, for sum(1,2,3,4) it will return 10.
Method overloading
Unlike java, there is no method overloading supported in JavaScript. But by using the arguments object you can achieve effects such as method overloading. Depending upon number of parameters, you can decide behavior.
Accessing properties of object
Objects are map equivalent of java language, which contain key and value for that key as shown below.


var person =  {
                  name: "Amit",
                  occupation:"Service",
              }

There are two ways by which you can access properties of object:

  1. Using dot notation, for example “person.name”.
  2. Using square bracket notation, for example person[‘name’].

for-in loop
Using for-in loop we can iterate over all properties of object. This is helpful if you do not know property keys. However, you want to make sure the key that you get is the actual property of that object and not inherited property from the prototype. For that, use built in method “hasOwnProperty()” which returns true if it is the objects property.


for (var key in person){
     if (person.hasOwnProperty(key)){
          alert(key + " -> " + person[key]);
     }
}

 Augmenting (extending) built in object
JavaScript have many built in objects, such as Array, String, Date, Math, RegExp, Number, etc. These built in objects contain many useful methods. For example, Array has methods such as concat, indesxOf, reverse. String has methods such as replace, search, split, etc. You can create a new method as shown below in built in object.
In java collection, there is method called “contains” that tells you if a value exists in collection; but in JavaScript array, there is no such method. So let’s implement contains in Array.prototype.


Array.prototype.contains = function(value) {
                                for (var i = 0, len = this.length; i < len; i++) {
                                     if (this[i] === value) {
                                          return true;
                                     }
                                }
                                return false;
                           }

Great! our code gets the useful array extension for free. The beauty of augmenting is that, not only the future array will get this extension, but also array created before have this.

Points to consider before using prototype –

Making it future proof
With newer versions of JavaScript, each version supports more features. When you think a feature is missing and decide to create new method for it, it might be a built in method tomorrow. In this case your method is no longer needed.
Here you can avoid such a situation by making your code future proof. For example, checking if that method exists or not and then creating it. As shown below.


if(!Array.prototype.contains){
     Array.prototype.contains = function(needle) {
                                     for (var i = 0, len = this.length; i < len; i++) {
                                          if (this[i] === needle) {
                                               return true;
                                          }
                                     }
                                     return false;
                                }
}

What is Next?
Below are useful links:

  1. http://www.w3schools.com/js/
  2. http://javascript.crockford.com/

Below are some good books on JavaScript:

  1. JavaScript- The Good Parts, by Douglas Crockford
  2. JavaScript Patterns, by Stoyan Stefanov