Javascript is one of the most popular programming languages for web development, it is a scripting language, initialy was used for creating interactive elements in html document. It is an easy-to-learn and anyone could start instantly, just by injected js code directly into HTML web page.

The first version of this language was created in 10 days in 1995 by Brendan Eich, while working on Netscape Browser. As time passed new features were introduced in versions such as ES2 1998 and ES3 1999 and the latest version named ECMAScript 6.

So what is javascript ES6? This is the standard for javascript that was released in June 2015 and was introduced in this version some new features like the keywords for block scoping variables Const and Let, arrow functions, javascript classes, multiline strings.

Now in 2021, the evolution of language is ES12 introduces three new features, one is new logical assignment operators which are the following ||= , &&= .The second feature is Promise.any that accept an array of promises and resolve as soon any of them resolved. The third one the numerical separators which give the ability to separate thousands with underscore like this (_).

Did you know that ECMA is the European Computers Manufacturers Association to standardize  information communication technology such as programming languages

Keeping up with news features allows a javascript web developer to create complex user interfaces and single-applications.

Javascript: var

In Javascript variables are containers that store data like strings of text, numbers, and boolean, these values can change over time, so declaring a variable can be done using the keyword var. Using var we declare a function-scoped or globally-scoped variable.

var car = "Ford";

When we declare a variable as above the same time is an instance of the class Object, that means will have properties, methods and event handlers. So a Javascript object can be declared the same way as a single value variable but could contain multiple values in the sense of a real object, as described in the paradigm of object-oriented programming.

A javascript object can be created having the following form, just by defining properties and values inside brackets.

var car = {type:"Ford Fiesta", year:"2001", color:"red"}

A major aspect of variables is the scope which defines the area of the code where the variable is accessible, and if we declare the variable outside of a function has global scope meaning is accessible from anywhere in the code, let's summarize the scopes.

  • global scope is the js execution environment for variables that are not declared as let, const, var
  • function scope are curly bruckets of a function.
  • Block scope variables in curly bruckets loops, if statements only defined by let and const

On the other hand, if a variable is declared inside a function could be accessed locally. The need to introduce blocked scoped variables was because in javascript the variables defined by var are function-scoped by default, this can cause some problems on redeclaring the same name variables and conflict with the names on accessing variables.

Javascript: const

This is a block-scoped variable that means it is defined inside a block of curly brackets in if, for, while, etc the variable exists only inside the block and not outside as could happen with a function-scoped variable. The special case with const is that the identifier cannot be redeclared or reassigned is immutable but we can add new properties or change values to existing ones

const car = "Fiat";
car = "Mercedes"; // this cause an error
car.type = "pick up"; // this is ok

In real-world let's examine some code from angular observables

const locations = new Observable((observer) => {
.....
});

const locationsSubscription = locations.subscribe({ });

In the above snippet, it is an observable example where locations are a javascript object from the observable instance this object has a function named subscribe. The name of locations is unique and cannot be redeclared, same time has a new method that named subscribe() returns another object named Subscription Object. The method subscribe method is part of an observer pattern when is called signals that observable will start to receive values from the object that has been subscribed to this.

In the above piece of code, the creation of the instance new Observable is not part of the javascript but it belongs to RxJS a reactive programming library. So Angular makes use of the observer software design pattern that has been implemented using RxJs. The object locations is an observable aka a stream of asynchronous events that capture the geolocation of user through the browser using Geolocation API.

So when making a call to the method subscribe() then the observable start listening for updates. In method subscribe we pass an observer object which is just a simple javascript object that includes key handlers next, error, complete.

Javascript: let

when we declare a variable using let, the variable is active inside the block scope that means curly bruckets {} such as has if statements, loops etc. There are some similarities with keyword var, for example if you define the let variable outside of a function has exactly the same functionality as var, with the only difference that the properties of let variable will not be added as properties of global window object.

If it defined inside a function has exactly the same behavior as local function as var, the basic difference with var is visibility, let's take the case of block scope on for loop and remember the let variable cannot redeclared.

function relatedProducts() {
     // my_product is not visible out here
     for( let my_product = 0; my_product < 5; my_product++ ) {
       // my_product is visible here and to all sub-blocks
    }
  // my_product is not visible out here
}

Javascript Arrow functions

const hello = function() {
     return "hello there";
}

is equalivant to

const hello = () => {
     return "hello there";
}

Javascript Asynchronous programming

one popular features in  ES6 version are promises, a promise is a placeholder for a value that will occur from a future asynchronous operation, it will be the result of an operation or error message upon failure to execute this operation.

The main reason of using this operation is to solve the problem with callbacks, that exist in asynchronous operations and fill the object of javascript.

There are three states of this operation

  • Pending
  • Fulfilled - the result is a value
  • Rejected - the result is an object

A promise can be used with async to write a promise code as to be synchronous without blocking the main thread.

async function is asynchronous function that await is permitted

await works only inside of an async function and forces an asynchronous function to wait until a promise fulfilled or rejected

async function f() {
    let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
   });
  try {
  let result = await promise;
      alert(result);
   } catch (e) {
   console.log(e);
  }
}

and async functions always return a value.

Intersection observer API

One of the coolest features in native javascript is the observer api , this feature allows you to monitor when an element div, p, or any other will become visible in the screen or another related element. This is very useful because you easily add functionality like loading an item efficiently, making split coding, lazy loading of images, and much other stuff.

Let's take the example where there is div with an id that named sharing-tools (could be the addthis widget), if the div is not available in screen on first load but located below the fold, here a simple code to load it intelligently and reduce first and thread execution

const sharingTools = document.getElementById("sharing-tools");
let observer = new IntersectionObserver((entries, observer) => {
    entries.forEach( entry => {
       if( entry.isIntersecting) {
             // load addthis.com tools here by dynamic create a script tag in the head
             var script = document.createElement("script");
             ...

             observer.unobserve(entry.target);
        }
}
observer.observe(sharingTools);

Javascript loop

A new loop was introduced with ES5 the forEach loop, this is an easy way to loop through the array, this can be used only with an array, sets, and maps. Using this someone can implement a callback each element of an array. In the above example, you see the usage when the IntersectionObserver is looping through the entries that have been attached to Intersection to monitor when an element is an intersection.

entries.forEach( entry => {
    if( entry.isIntersecting) {
         ...
     }
}

Split Coding for high performance in mobile devices

When you combine effectively the intersection observer and at the same time implementing this tiny LoadJS library you can split your javascript codes in chunks and improve dramatically the performance in Google PageSpeed Insights.   You can have a maximum on metrics like Time To Interactive, so for apparel and high-quality design and user experience.