Category Archives: Javascript

JAVASCRIPT: CALLBACK

JavaScript: Callback

Callback functions is a theory derived from functional programming and specifies the use of functions as arguments.

In JavaScript every function is a first class object, which means that every function is an Object and can be used like any other object. This enables the use of a function as a parameter in another function which is the fundamental idea of callback functions.

PARAMETERS TO CALLBACK FUNCTIONS:

We can also pass parameters to callback functions, just similar to any other function. In the below instance we pass as a parameter the name of the author of the function.

var author = “FF”;
function namedCallback(param){
alert(“namedCallback() called by “+param);
}
function testFunction(callback){
callback();
}
testFunction(namedCallback(author));

MULTIPLE CALLBACK FUNCTION:

Multiple callback functions can be used as parameters of another function.

Var someUlr = …;
function successCallback(){
//success code
}
function completeCallback(){
//complete code
}
function errorCallback(){
//error code
}
$.ajax({
url: someUrl,
success: successCallback,
complete: completeCallback,
error: errorCallback
})

WHY DO WE NEED CALLBACKS?

For one very key reason — JavaScript is an event driven language. This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events.

function first(){
console.log(1);
}
function second(){
console.log(2);
}
first();
second();

As the user would expect, the function first is executed first, and the function second is executed second.

// 1
// 2

THE VERDICT

You can now understand what a callback is and how it works. This is just the tip of the iceberg with callbacks, there is still a lot more to learn!

JAVASCRIPT CUSTOM EVENTS

JavaScript Custom Events

Despite the huge number of events JavaScript provides out of the box for a whole horde of scenarios, there will be times when the user wants to fire his/her own events for their certain needs.

There are many reasons for why the user might want to do that. Events provide a level of decoupling between the thing that fires the event and the thing that listen for that event. In the event-driven world that we live in, the DOM elements doesn’t need to be familiar with the inner workings of the code. By relying on events, the user has a great deal of flexibility in changing things around in the UI or in the code without breaking things and doing a lot of clean-up afterwards. This makes the built-in events and custom events created by the user more useful.

To take advantage of this usefulness, JavaScript provides the user with just what they need. The user might have named Custom Event that does all sorts of amazing things, and in this article, we’ll take a detailed look at it.

JavaScript Custom Events

CREATING EVENTS

The user can use the Event constructor to create an event. The first and most important argument is the name of the event.

1 const customEvent = new Event(‘custom’);
2
3 document.addEventListener(‘custom’, function(event) {
4 console.log(customEvent === event); // true
5 });
6
7 document.dispatchEvent(customEvent);

The event will not bubble by default. To change the behaviour the user has to pass additional options to the constructor.

const customEvent = new Event(‘custom’, { bubbles: true });

Events such as the above are generally referred as synthetic. The function dispatchEvent used above invokes event handlers synchronously, instead of doing it asynchronously through the event loop.

Custom Event

1 const profilePicture = document.querySelector(‘#profilePicture’);
2 profilePicture.addEventListener(‘userSignedIn’, function(event) {
3 event.target.src = event.details.profilePicture;
4 });
5
6 signInUser(credentials)
7 .then(function(userData){
8 const userSignedInEvent = new CustomEvent(‘userSignedIn’, {
9 detail: userData
10 });
11 profilePicture.dispatchEvent(userSignedInEvent);
12 }))

Just remember that if the user would like to stop the propagation of the events at some point, the user need to add cancellable: true to the event options.

BUILT-IN EVENTS

The user might want to simulate an event, that occurs natively in the browser. The instance of that is the “click” event. Imagine having a checkbox:

1 <input type=”checkbox” />

const checkbox = document.querySelector(‘input[type=”checkbox”]’);
checkbox.addEventListener(‘change’, function(event) {
console.log(‘State was changed’);
});

The difficulty will occur when the user will try to change its state programmatically, through the JavaScript code:

checkbox.checked = true; // the event wasn’t fired

Running the code above will not cause the event to be fired. The user can easily fix that with a custom event.

const clickEvent = new MouseEvent(‘click’);

checkbox.dispatchEvent(clickEvent); // the event was fired

This code will cause “State was changed” to be displayed in the console.

Just note that due to some implementation changes between browsers, trying to dispatch the same MouseEvent twice might fail.

The code below works fine on Firefox, but on Chrome the second dispatchEvent does not work.

2 checkbox.dispatchEvent(clickEvent); // “State was changed”
checkbox.dispatchEvent(clickEvent); // nothing happens

To ensure that the event is dispatched every time, use a brand new event.
checkbox.dispatchEvent(new MouseEvent(‘click’));

CONCLUSION

In our opinion custom events are just better all around. We do think they require a bit more communication though. The user will probably have to write up some comments somewhere that explain what custom events are fired and when and how to make that easy to discover.

PROTOTYPE INHERITANCE IN JAVASCRIPT

Prototype Inheritance in JavaScript

INHERITANCE

Inheritance refers to an object’s capability to access methods and other properties from another object. Objects can inherit things from other objects. Inheritance in JavaScript works through prototypes and this form of inheritance is often called prototypal inheritance.

Prototype Inheritance in JavaScript

In this article, we will be covering a detailed note on prototypal inheritance and implementing inheritance.

PROTOTYPE

Almost all objects in JavaScript have the prototype property. The prototype is a reference to another object and it is used whenever JS cannot find the property the user is looking for in the current object. In simple, whenever the user wants to call a property on an object and it does not exist, JavaScript will go to the prototype object and look for it there. If it finds it will use it, if not it will go to that object’s property and look there. This can bubble up all the way to Object.prototype before returning undefined. This is the principle of the prototype chain and the behaviour that sits behind JavaScript’s inheritance.

THE PROTOTYPE CHAIN

To understand object prototypes, we need to discuss object lookup behaviour. When we look for a property of an object, the JavaScript engine will first check the object itself for the existence of the property. If not found, it will go to the object’s prototype and check that object. If found, it will use that property.

If not found, it will go to the prototype’s prototype, and on and on until it finds an object with a __proto__ property equal to null. So if the user is going to attempt to lookup the property someProperty on obj object from above, the engine would first check the object itself.

If it wouldn’t find it and would then jump to its __proto__ object which is equal to Object.prototype. It wouldn’t find it there either and upon seeing that the next __proto__ is null, it would return undefined.

This is called the prototype chain. It is normally described as a chain going downwards, with null at the very top and the object which the user is using at the bottom.

While performing a lookup, the engine will pass through up the chain looking for the property and return the first one it finds, or undefined if it is not present in the prototype chain.

__proto__ === null
|
|
__proto__ === Object.prototype
|
|
{ object literal }
FUNCTION PROTOTYPES

Functions all have a prototype property distinct from their __proto__ property. It is an object. A function’s sprototype’s __proto__ property is equal to Object.prototype.

function fn() {}
console.log(fn.prototype.__proto__ === Object.prototype);
// -> true

EXECUTING INHERITANCE

The user can work with a function’s prototype property directly and safely. By placing methods and other properties on a function’s prototype, and can allow all objects created by that function to access those properties through inheritance.

function Fn() {}
Fn.prototype.print = function() {
console.log(“Calling Fn.prototype’s print method”);
};
var obj = new Fn();
obj.print(); // -> Calling Fn.prototype’s print method

This works in a different way because, each object created by calling new Fn() will have its own version of print placed directly on the object. There will be different functions in memory. The difficulty with this is performance and memory usage.

PERFORMANCE

There may be times the user might need thousands of new objects created from a constructor function. Using this second way of attaching print, we now have thousands of copies of print, each one attached to one of the objects.

Using the prototype chain, no matter how many objects the user creates out of a Fn, the user will have one print sitting on Fn.prototype.

Big programs, however, often have tens of methods that objects need. If an object needs access to 20 methods and we create 100,000 objects, the JavaScript engine has created 2,000,000 new functions. If this needs to happen multiple times, this will cause visible speed and memory issues.

Using console.time and console.timeEnd, the user can directly show the difference in how long it takes.

THE VERDICT

Prototypes are more of a delegation tool and they do not really behave like classes. Now with the latest approach the user can create normal class hierarchies and use understandable syntax for them, but be cautious of possible problems that may occur. This syntax is only a beautiful facade for what’s going on inside.

JAVASCRIPT ES6

JavaScript ES6

JavaScript ES6 brings new syntax and amazing features to make the users code more up-to-date and readable. It allows the user to write less code and do more. ES6 introduces the user to many great features like arrow functions, template strings, class destruction, Modules, and much more. So, let’s dive deep in and study the new features on JavaScript ES6.

CONST & LET

Const is a new keyword in ES6 for declaring variables. const is more influential than var. Once it is used, the variable cannot be reassigned. In other words, it is an immutable variable except when it used with objects. This is really useful for targeting the selectors.

const a = 50;
a = 60; // shows error. You cannot change the value of const.
const b = “Constant variable”;
b = “Assigning new value”; // shows error.

LET

Let is similar to var but let has scope. Let is only accessible in the block level it is defined.

JavaScript ES6
if (true) {
let a = 40;
console.log(a); //40
}
console.log(a); // undefined
In the above example variable ‘a’ is defined inside If statement and so it’s not accessible outside the function.

ARROW FUNCTIONS

The arrow function makes the users code more readable, more structured, and look like modern code.

// Old Syntax
function oldOne() {
console.log(“Hello World..!”);
}
// New Syntax
var newOne = () => {
console.log(“Hello World..!”);
}
The new syntax may be confusing a bit.
There are two parts of the syntax.
var newOne = ()
=> {}

The first part is declaring a variable and assigning the function () to it.
The second part is declaring the body part of the function. The arrow part with the curly braces defines the body part.

DEFAULT PARAMETERS

If you are familiar with other programming languages such as Ruby, Python then default parameters is not new to you.

Default parameters are parameters which are given by default while declaring a function. But the value can be changed when calling the function.

let Func = (a, b = 10) => {
return a + b;
}
Func(20); // 20 + 10 = 30

In the above example, we are passing only one parameter. The function makes use of the default parameter and executes the function.

MAPS

Map holds key-value pairs, it is similar to an array but we can define our own index and indexes are unique in maps. In maps, all indexes are unique and we can use any value as key or value.

var NewMap = new Map();
NewMap.set(‘name’, ‘John’);
NewMap.set(‘id’, 2345796);
NewMap.set(‘interest’, [‘js’, ‘ruby’, ‘python’]);
NewMap.get(‘name’); // John
NewMap.get(‘id’); // 2345796
NewMap.get(‘interest’); // [‘js’, ‘ruby’, ‘python’]

GETTERS AND SETTERS

Getters and setters are one of the useful feature introduced in ES6. It will come in handy if you are using classes in JS.

class People {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
setName(name) {
this.name = name;
}
}
let person = new People(“Jon Snow”);
console.log(person.getName());
person.setName(“Dany”);
console.log(person.getName());
Output:
Jon Snow
Dany

WHAT ARE THE PROS AND CONS OF USING JAVASCRIPT ES5 VERSUS ES6?

What are the pros and cons of using JavaScript ES5 versus ES6?

Pros

ES5:

You have a lot of browser support.

ES6:

You have tail call optimization.
You have import statements.
Lamba’s are pretty amazing.
Immutable and block scoping objects with “const” and “let”.
Classes and OO Inheritance.
Functors, and all that functional goodness.
String templates that handle interpolation for you.

Cons

ES5:

It doesn’t have everything that ES6 has.

ES6:

It doesn’t have all the support that ES5 has, but you can always transpile your ES6 code.

WHAT ARE THE PROS OF USING THE HANDLEBARS TEMPLATE OVER UNDERSCORE.JS?

What are the pros of using the Handlebars template over Underscore.js?

Picking one over the other is a subjective thing – it really comes down to your preferred programming style – but when compared, handlebars edges out underscore.js as below:

Logic-less templates do a great job of forcing you to separate presentation from logic.

Clean syntax leads to templates that are easy to build, read, and maintain.

Compiled rather than interpreted templates.

Better support for paths than mustache (ie, reaching deep into a context object).

Better support for global helpers than mustache.

Requires server-side JavaScript to render on the server.

Clean syntax leads to templates that are easy to build, read, and maintain.

Compiled rather than interpreted templates.

Better support for paths than mustache (ie, reaching deep into a context object).

Better support for global helpers than mustache.

Requires server-side JavaScript to render on the server.

MACHINE LEARNING IN JAVASCRIPT

Machine Learning in JavaScript

Machine learning libraries are growing faster and more available with each passing year, showing no signs of breaking down. While traditionally Python has been the go-to language for machine learning, now-a-days neural networks can run in any language, including JavaScript!

The web system has made a lot of development in recent times and although JavaScript and Node.js are still fewer performers than Python and Java, they are now dominant to handle many machine learning hitches.

Most of the JavaScript machine learning libraries are fairly new and still in improvement, but they do exist and are ready for the users to try them. In this article, we will look at some of these libraries, as well as a number of cool AI web app instances to get you started.

BRAIN

The brain is a library that makes the user to easily create neural networks and then train them depending on input/output data. As training takes up a lot of resources, it is better to run the library in a Node.js location, though a CDN browser version can also be loaded directly onto a web page. There is a small demo on their website that can be trained to identify color contrast.

SYNAPTIC

It is the most vigorously maintained project on the list, Synaptic is a Node.js and browser library that is architecture-agnostic, allowing the developers to build any type of neural network they want. It has some narrow built-in architectures, making it likely to test and relate different machine learning algorithms. It also features a well-published introduction to neural networks, a number of practical demos, and many other great tutorials illustrating how machine learning works.

FLAPPYLEARNING

FlappyLearning is a JavaScript project that is of hardly few lines of un-minified code copes to build a machine learning library and implement it in a fun demo that learns to play Flappy Bird like a virtuoso. The AI method used in this library is called Neuroevolution and applies algorithms motivated by nervous systems found in nature, dynamically learning from each iteration’s success or failures. The demonstration is super easy to run – just open index.html in the browser.

CONVNETJS

Though it is no longer actively maintained, ConvNetJS is one of the most progressive deep learning libraries for JavaScript. It works directly in the browser, supports several learning techniques, and is rather low-level, making it appropriate for people with better experience in neural networks.

NEUROJS

Framework for building AI systems based on reinforcement learning. Miserably, the open-source project does not have a right documentation but one of the demos, a self-driving car experiment, has a great description of the different parts that make up a neural network. The library is in pure JavaScript and made using modern tools such as web pack and babel.

CONCLUSION

Although the JavaScript machine learning ecosystem is not completely developed yet, we suggest using the resources on this list to make your first steps in ML and get a feel for the core techniques. As the experimentations in this article show, there are loads of exciting stuff you can make by using only the browser and some familiar JavaScript code.

JAVASCRIPT ES8

Javascript ES8

EcmaScript 8 or EcmaScript 2017 was officially released at the end of June by TC39. It seems that we are talking a lot about EcmaScript in the 2016. The standard is to publish a new ES specification version once a year. ES6 was published in 2015 and ES7 was published in 2016, but do someone remember when ES5 was released? It happened in 2009, before the magical rise of JavaScript. In this article we are going to discuss about ES8 and its new features. So, explore this article and know more about EcmaScript 8.

OBJECT.VALUES AND OBJECT.ENTRIES

The Object.values method returns an array of a given own object’s enumerable property values, in the same order as that provided on behalf of a loop. The declaration of the function is trivial.

Object.values(obj)

The obj parameter is the source object for the operation. It can be an object or an array.

const obj = { x: ‘xxx’, y: 1 };
Object.values(obj); // [‘xxx’, 1]

const obj = [‘e’, ‘s’, ‘8’]; // same as { 0: ‘e’, 1: ‘s’, 2: ‘8’ };
Object.values(obj); // [‘e’, ‘s’, ‘8’]

2

// when we use numeric keys, the values returned in a numerical
// order according to the keys
const obj = { 10: ‘xxx’, 1: ‘yyy’, 3: ‘zzz’ };
Object.values(obj); // [‘yyy’, ‘zzz’, ‘xxx’]

Object.values(‘es8′); // [‘e’, ‘s’, ‘8’]

The Object.entries method returns an array of a given object’s own enumerable property [key, value] pairs, in the same order as Object.values. The declaration of the function is trivial:

const obj = { x: ‘xxx’, y: 1 };
Object.entries(obj); // [[’x’, ‘xxx’], [’y’, 1]]

const obj = [’e’, ‘s’, ‘8’];
Object.entries(obj); // [[’0’, ‘e’], [’1’, ‘s’], [’2’, ‘8’]]

const obj = { 10: ‘xxx’, 1: ‘yyy’, 3: ‘zzz’ };
Object.entries(obj); // [[’1’, ‘yyy’], [’3’, ‘zzz’], [’10’, ‘xxx’]]

Object.entries(‘es8′); // [[‘0′, ‘e’], [‘1′, ‘s’], [‘2′, ‘8’]]
This section adds two functions to the String object i.e. padStart & padEnd.

As their names, the purpose of those functions is to pad the start or the end of the string, so that the resulting string reaches the given length. The user can pad the specific character or string or just pad with spaces by default. Below are the functions declaration.

str.padStart(targetLength [, padString])
str.padEnd(targetLength [, padString])

As we can see, the first parameter of the functions is the targetLength, that is the total length of the resulted string. The second parameter is optional padString that is for the string to pad the source string. The default value is space.

‘es8′.padStart(2); // ‘es8′
‘es8′.padStart(5); // ‘ es8′
‘es8′.padStart(6, ‘woof’); // ‘wooes8′
‘es8′.padStart(14, ‘wow’); // ‘wowwowwowwoes8′
‘es8′.padStart(7, ‘0’); // ‘0000es8′
‘es8’.padEnd(2); // ‘es8′
‘es8’.padEnd(5); // ‘es8 ‘
‘es8’.padEnd(6, ‘woof’); // ‘es8woo’
‘es8’.padEnd(14, ‘wow’); // ‘es8wowwowwowwo’
‘es8’.padEnd(7, ‘6’); // ‘es86666′

OBJECT.GETOWNPROPERTYDESCRIPTORS

EcmaSript lacks a method for properly copying properties between two objects. This proposal solves this seemingly simple but complex problem that has been implemented at times in almost every JS toolkit or framework. Currently it is a stumbling block for efficient immutability, true composition of ES Classes, something that would benefit Decorators, and just less surprising in general than Object.assign.

ASYNC FUNCTIONS

The async function declaration defines an asynchronous function, which returns an AsyncFunction object. Internally, async functions work much like generators, but they are not translated to generator functions.

function fetchTextByPromise() {
return new Promise(resolve => {
setTimeout(() => {
resolve(“es8″);
}, 2000);
});
}

async function sayHello() {
const externalFetchedText = await fetchTextByPromise();
console.log(`Hello, ${externalFetchedText}`); // Hello, es8
}

sayHello();

The call of sayHello will log Hello in es8 after 2 seconds.
console.log(1);
sayHello();
console.log(2);

async function
And now the prints are:
1 // immediately
2 // immediately
Hello, es8 // after 2 seconds

This is because the function call does not block the flow.

Pay attention that an async function always returns a promise and an expect keyword may only be used in functions marked with the async keyword.

SHARED MEMORY AND ATOMICS

When memory is shared, multiple threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are completed before the next operation starts and that operations are not interrupted. This section introduces a new constructor SharedArrayBuffer and a namespace object atomics with static methods.

The atomic object is an object of static methods such as math, so we cannot use it as a constructor. Examples for static method in this object are:

add / sub— add / subtract a value for the value at a specific position.
and / or / xor — bitwise and / bitwise or / bitwise xor.
load — get the value at a specific position.

THE VERDICT

JavaScript is in production, but it is always getting improved. The process of adopting new features to the specification is very arranged and composed. In the previous stage, these features were confirmed by the TC39 committee and implemented by the core developers. Most of them are already parts of the Typescript language, browsers or other polyfills, so the user can go and try them right now.