Things I wish I would have known about JavaScript

Here are some of the things I wish I would have known when I got started using JavaScript.

Functions are first class object

This means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions.

// A function is an instance of the Object type:
function testFunction(isTrue, anotherFunction) {
    if(isTrue) {
        anotherFunction();
    }
}
alert(testFunction instanceof Object);

// A function can have properties
testFunction.name = "atatus";
alert(testFunction.name);

// You can store the function in a variable
var tempFunction = testFunction

// You can pass the function as a parameter to another function
testFunction(true, function() { alert('hello'); }); //  alerts "world"
testFunction(false, function() { alert('world'); }); // does nothing

IIFE - Immediately Invoked Function Expression (Self executing function)

In JavaScript when you don’t define a variable or a function within another function then these become globally accessible objects. This introduces the problem of corrupting the namespace. To handle this, you can define these variable inside an anonymous function and call that function immediately after you define it.

For example:

var name = 'Atatus'
var action = 'Monitor Errors';
function onErrorFound() {
    // Inform user
}

In the above example, name, action and onErrorFound function are globally defined. Instead you can wrap them around in an anonymous function and call it, therefore the name Immediately Invoked Function Expression (IIFE):

(function(){
  var name = 'Atatus';
  var action = 'Monitor Errors';
  function onErrorFound() {
    // Inform user
  }
})();

Now, if you want to call onErrorFound outside the scope of the IIFE then you need to assign a variable to that function which you can then use to call the internal functions. This is what is called the Module Pattern or Singleton.

var atatusVar = (function(){
  var name = 'Atatus';
  var action = 'Monitor Errors';
  function onErrorFound() {
    // Inform user
  }
  return {
     onerror: onErrorFound
  }
})();
atatusVar.onErrorFound();   // Works

Understand how .prototype works

JavaScript uses a special prototype property to solve the problems that other languages use classes to solve. Consider the following:

function Person(first, last)
{
    this.first = first;
    this.last = last;
}
var john = new Person("John", "Doe");
var mary = new Person("Mary", "Deer");
Person.prototype.full = function() {return this.first + " " + this.last;};
alert(john.full());

There are a lot of things happening here.

  1. We create a function, which will set properties on its this object when called.
  2. We create two separate instances of that function by putting the new keyword before our function calls. This ensures that john and mary refer to completely separate objects, each with their own first and lastproperties.
  3. We create a new function and assign it to the full property on our Person function’s prototypeproperty. The prototype property exists on all functions, and allows you to define fall-back properties that should exist on every object created from that function.
  4. We call the full() function on john. JavaScript sees that the john object doesn’t actually have a fullfunction on it, so it looks for a Person.prototype.full() function and calls that instead. Within that call, however, this still refers to the john object.

This is also called as Prototypical inheritance

JSON (Java Script Object Notation)

JSON was designed as a data interchange format, which happens to have a syntax that is a subset of JavaScript. Before JSON, you have to think of storing them using arrays, strings etc. Imagine trying to save and read back browser data using C alone. That was changed with JSON. It became much simpler to store data and almost all high level languages support JSON parsing.

{
  "apikey"  : "xxxyyyzzz",
  "owner"   : "owner@team.com",
  "score"   : 1234,
  "is_staff": false,
  "joined"  : "23-12-2014"
  "collaborators" : [
    {
      "name"  : "Team Member 1",
      "email" : "one@team.com"
    },
    {
      "name"  : "Team Member 2",
      "email" : "two@team.com"
    }
    ]
}

JSON is a subset of JavaScript’s object notation, but not exactly the same. There are some differences:

  1. The keys must be strings (i.e. enclosed in double quotes “) in JSON.
  2. In JSON, the values can be either:
  • a string
  • a number
  • an (JSON) object
  • an array
  • true
  • false
  • null

There are methods to serialize and de-serialize the JavaScript object into JSON.

// Serialize JavaScript object to JSON
var person = { name: 'Mike', age: 20 };
var jsonString = JSON.stringify(person);


// Parse JSON string into JavaScript object
var jsonString = '{ "prop": "val" }';
var object = JSON.parse(jsonString);

Event Handling

Let’s say you have three possible actions for your user on an issue such as

<ul id="actions">
  <li><a href="http://www.atatus.com/set/to/solved">Solved</a></li>
  <li><a href="http://www.atatus.com/set/to/reopen">Reopen</a></li>
  <li><a href="http://www.atatus.com/set/to/assign">Assign</a></li>
</ul>

then you can handle all these events in a single event handler and take the necessary action in that handler:

(function(){
  var actions = document.getElementById('actions');
  actions.addEventListener('click', handler, false);
  function handler(e) {
    var l = e.target;
    // action for link l
    l.preventDefault();
  };
})();

JavaScript is not just for browsers

JavaScript is not only used in browsers – many applications start supporting it as a means to extend and script for them. Now, technologies like node.js allow JavaScript to be run outside of any browser. There are thousand of command line tools written in node.js. The possibilities are endless.

Fizer Khan

Fizer Khan

Co-Founder & Architect at Atatus
Chennai

Monitor your entire software stack

Gain end-to-end visibility of every business transaction and see how each layer of your software stack affects your customer experience.