Last Updated: March 22, 2020
·
3.381K
· avenger7x

JavaScript code organization

Preface

Hi. I am a follower of functional programming, and I like the simplicity and readability of code. Every time I write any part of the application, I imagine that I am creating a thing. This thing must have certain details and they have to stand in the right places. So all these things are similar to each other and form one large application.

I am a JavaScript-developer. I think it's a great language with expressive features. Someone said that the language is not enough elements of the OOP, so JS can not be taken seriously. I'm pretty sure that JS has one of the best implementations of functional programming.

Template

Based on my experience, I have created my own template for organizing the code in each file.

(function(){
    'use strict';
    // variables declaration and initialization

    // functions declaration

    // another variables initialization

    // global events subscribing

    // global API declaration

})();

This is a sample module to monitor any information and store this information in localStorage

(function(){
    'use strict';
    // variables declaration and initialization
    var data = localStorage.hasOwnProperty('data') ? JSON.parse(localStorage.data) : {}, 
        startTime;

    // functions declaration
    function updateField(key, value){
        if(!data.hasOwnProperty(key)){
            data[key] = 0;
        }
        data[key] += value;
    }

    function saveData(){
        localStorage.data = JSON.stringify(data);
    }

    // another variables initialization
    if(data.hasOwnProperty('timer')){
        updateField('visit', 1);
    }

    // global events subscribing
    document.addEventListener('customeventstart', function(event){
        startTime = event.timeStamp;        
    });
    document.addEventListener('customeventend', function(event){
        updateField('timer', event.timeStamp - startTime);
    });
    document.addEventListener('anotherevent', saveData);

    // global API declaration
    window.monitor = {
        save: saveData,
        update: updateField
    };
})();

I hope this template will be useful for someone.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside