A simple todo app in javascript

Asked in Box onsite interview. With a node.js server on backend.

$().ready(function() {
   $('#add').on('click', addTask);
   $('#tasks').on('click', markComplete);
   // Alternative way
   // var tasksElement = document.getElementById('tasks');
   // tasksElement.addEventListener('click', markComplete);
   //document.getElementById('task-input').onkeydown = function(e){
   $('#task-input').on('keydown', function(e) {
       if(e && e.keyCode == 13){

   function renderTask(result) {
        var checkboxContainerId = 'check' + result.id;
        var taskTextId = 'tasktext-' + result.id;
        if (result.done == '1') {
            checkedState = ' checked ';
        } else {
            checkedState = '';
        taskHtml = '
  • '; taskHtml += ''; taskHtml += '' + result.data + '
  • '; $('#tasks').append(taskHtml); } function taskAdded(result) { renderTask(result); $('#task-input').val(''); } function renderResults(results) { results.forEach(renderTask); } function addTask(e) { url = 'http://localhost:9898/todo/tasks/create'; inputData = $('#task-input').val(); if (!inputData) { return; } $.ajax({ url: url, type: "POST", data: {data: inputData} , success: taskAdded, }); } function markComplete(e) { var done; if (e.target && e.target.matches("input.task-checkbox")) { var taskId = $(e.target).attr('task-id'); if ($(e.target).is(":checked")) { done = "1"; } else { done = "-1"; } var editUrl = 'http://localhost:9898/todo/tasks/' + taskId + '/edit'; $.ajax({ url: editUrl, type: "POST", data: {done: done}, success: function(result) { } }); } } var getTasksUrl = 'http://localhost:9898/todo/tasks'; $.ajax({ url: getTasksUrl, type: "GET", success: renderResults, }); } );

    Debounce and Throttle in Javascript

    Throttle: the original function be called at most once per specified period.
    Example: while window resizing

    Debounce: the original function be called after the caller stops calling the decorated function after a specified period.
    Example: Validating contents of a text field after using has stopped typing.

    Throttling will delay executing a function. It will reduce the notifications of an event that fires multiple times.

    Debouncing will bunch a series of sequential calls to a function into a single call to that function. It ensures that one notification is made for an event that fires multiple times.

    If you have a function that gets called a lot – for example when a resize or mouse move event occurs, it can be called a lot of times. If you don’t want this behaviour, you can Throttle it so that the function is called at regular intervals. Debouncing will mean it is called at the end (or start) of a bunch of events.

    A far-fetched metaphor, but maybe could also help.

    You have a friend named Chatty who likes to talk with you via IM. Assuming when she talks she sends a new message every 5 seconds, while your IM application icon is bouncing up and down, you can take the…

    Naive approach: check every message as long as it arrives. When your app icon bounces, check. It’s not the most effective way, but you are always up-to-date.
    Throttle approach: you check once every 5 minutes (when there are new ones). When new message arrives, if you have checked anytime in the last 5 minutes, ignore it. You save your time with this approach, while still in the loop.
    Debounce approach: you know Chatty, she breaks down a whole story into pieces, sends them in one message after another. You wait until Chatty finishes the whole story: if she stops sending messages for 5 minutes, you would assume she has finished, now you check all.

    Trulia On Site Questions

    1) How does Oauth work ?

    2) Explain journey of a URL ?

    3) How does caching work in a CDN? How do you push a new file out to CDN?

    4) Emulate the throttle function()

    // Allow callback to run at most 1 time per 100ms
    window.addEventListener("resize", throttle(callback, 500));
    // Allow callback to run on each resize event
    window.addEventListener("resize", callback2);
    function callback ()  { console.count("Throttled");     }
    function callback2 () { console.count("Not Throttled"); }
    function throttle (callback, limit) {
        var wait = false;                  // Initially, we're not waiting
        return function () {               // We return a throttled function
            if (!wait) {                   // If we're not waiting
                callback.call();           // Execute users function
                wait = true;               // Prevent future invocations
                setTimeout(function () {   // After a period of time
                    wait = false;          // And allow future invocations
                }, limit);

    How to achieve static variable in javascript

    2 Ways :

    1) Make use of the fact that functions are objects and can have properties
    (Even using “this” instead of uniqueID inside the function will do)

    function uniqueID() {
        // Check to see if the counter has been initialized
        if ( typeof uniqueID.counter == 'undefined' ) {
            // It has not... perform the initialization
            uniqueID.counter = 0;
        return (uniqueID.counter);

    2) Using closure and function expressions

    var uniqueID = (function() {
       var id = 0; // This is the private persistent value
       // The outer function returns a nested function that has access
       // to the persistent value.  It is this nested function we're storing
       // in the variable uniqueID above.
       return function() { return id++; };  // Return and increment
    })(); // Invoke the outer function after defining it.

    Javascript Questions Set3

    1) What is event delegation?

    Event delegation is when you bind an event listener to a parent (or ancestor) element rather than the element(s) you are particularly interested in. When the event is triggered you can check the event target to make sure it was actually the triggered on the element of interest.

    Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here’s an example of it in practice:

    Let’s say that we have a parent UL element with several child elements:

    • Item 1
    • Item 2
    • Item 3

    Let’s also say that something needs to happen when each child element is clicked. You could add a separate event listener to each individual LI element, but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app. The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?

    Simple: when the event bubbles up to the UL element, you check the event object’s target property to gain a reference to the actual clicked node. Here’s a very basic JavaScript snippet which illustrates event delegation:

    // Get the element, add a click listener...
    document.getElementById("parent-list").addEventListener("click", function(e) {
    // e.target is the clicked element!
    // If it was a list item
    if(e.target && e.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ", e.target.id.replace("post-"), " was clicked!");

    2) What are the 3 ways to bind an event to an element ?
    1) HTML Event Handlers
    < input type="text" id="username" onblur="checkUserName()">
    Not recommended any more. Better to separate JS and HTML

    2) DOM Event Handlers
    function checkUserName() { blah } ;
    var el = document.getElementById(‘username’);
    el.onblur = checkUserName;

    Disadvantage is that you can only attach one function to each event Handler.

    3) DOM Event Listeners
    Advantage : They can deal with more than one function at a time.
    var el = document.getElementById(‘username’);
    el.addEventListener(‘blur’, checkUserName, false);

    3) How do you convert arguments into an actual array. arguments are pseudo array in js.

    var args = Array.prototype.slice.call(arguments);

    4) How would you simulate Function.prototype.bind in older browser that don’t support it

    Function.prototype.bind = Function.prototype.bind || function(context){
      var self = this;
      return function(){
        return self.apply(context, arguments);

    4) How to pass parameters to callback functions?

    By default you cannot pass arguments to a callback function. For example:

    function callback() {
      console.log('Hi human');
    document.getElementById('someelem').addEventListener('click', callback);

    But using closure concept you can do so :

    function callback(a, b) {
      return function() {
        console.log('sum = ', (a+b));
    var x = 1, y = 2;
    document.getElementById('someelem').addEventListener('click', callback(x, y));

    Function overloading in Javascript

    Unique things about arguments in functions in Javascript:

    1) You can pass any number of parameters to a function without causing an error.
    2) You can also pass in no arguments but still make use of arguments inside the function (through arguments array)
    3) you have access to arguments[0], arguments[1] etc in a function
    4) arguments.length will give you number of parameters passed in. This is the way you can achieve function overloading. Based on number of parameters you do one thing or the other.
    5) If you define multiple functions with same name, the one which is defined last will override all others.