These are the features in ES6 that you should know

ES6 brings more features to the JavaScript language. Some new syntax allows you to write code in a more expressive way, some features complete the functional programming toolbox, and some features are questionable.

ES6 brings more features to the JavaScript language. Some new syntax allows you to write code in a more expressive way, some features complete the functional programming toolbox, and some features are questionable.

let and const

There are two ways for declaring a variable (let and const) plus one that has become obsolete (var).


let

let declares and optionally initializes a variable in the current scope. The current scope can be either a module, a function or a block. The value of a variable that is not initialized is undefined .


Scope defines the lifetime and visibility of a variable. Variables are not visible outside the scope in which they are declared.

Consider the next code that emphasizes let block scope:

let x = 1;
{ 
  let x = 2;
}
console.log(x); //1

In contrast, the var declaration had no block scope:

var x = 1;
{ 
  var x = 2;
}
console.log(x); //2

The for loop statement, with the let declaration, creates a new variable local to the block scope, for each iteration. The next loop creates five closures over five different i variables.

(function run(){
  for(let i=0; i<5; i++){
    setTimeout(function log(){
      console.log(i); //0 1 2 3 4
    }, 100);
  }
})();

Writing the same code with var will create five closures, over the same variable, so all closures will display the last value of i.

The log() function is a closure. For more on closures, take a look at Discover the power of closures in JavaScript.

const

const declares a variable that cannot be reassigned. It becomes a constant only when the assigned value is immutable.


An immutable value is a value that, once created, cannot be changed. Primitive values are immutable, objects are mutable.

const freezes the variable, Object.freeze() freezes the object.

The initialization of the const variable is mandatory.

Modules

Before modules, a variable declared outside any function was a global variable.


With modules, a variable declared outside any function is hidden and not available to other modules unless it is explicitly exported.

Exporting makes a function or object available to other modules. In the next example, I export functions from different modules:

//module "./TodoStore.js"
export default function TodoStore(){}
//module "./UserStore.js"
export default function UserStore(){}


Importing makes a function or object, from other modules, available to the current module.

import TodoStore from "./TodoStore";
import UserStore from "./UserStore";
const todoStore = TodoStore();
const userStore = UserStore();


Spread/Rest

The … operator can be the spread operator or the rest parameter, depending on where it is used. Consider the next example:


const numbers = [1, 2, 3];
const arr = ['a', 'b', 'c', ...numbers];
console.log(arr);
["a", "b", "c", 1, 2, 3]


This is the spread operator. Now look at the next example:

function process(x,y, ...arr){
  console.log(arr)
}
process(1,2,3,4,5);
//[3, 4, 5]
function processArray(...arr){
  console.log(arr)
}
processArray(1,2,3,4,5);
//[1, 2, 3, 4, 5]

This is the rest parameter.

arguments

With the rest parameter we can replace the arguments pseudo-parameter. The rest parameter is an array, arguments is not.


function addNumber(total, value){
  return total + value;
}
function sum(...args){
  return args.reduce(addNumber, 0);
}
sum(1,2,3); //6


Cloning

The spread operator makes the cloning of objects and arrays simpler and more expressive.


The object spread properties operator will be available as part of ES2018.

const book = { title: "JavaScript: The Good Parts" };
//clone with Object.assign()
const clone = Object.assign({}, book);
//clone with spread operator
const clone = { ...book };
const arr = [1, 2 ,3];
//clone with slice
const cloneArr = arr.slice();
//clone with spread operator
const cloneArr = [ ...arr ];


Concatenation

In the next example, the spread operator is used to concatenate arrays:


const part1 = [1, 2, 3];
const part2 = [4, 5, 6];
const arr = part1.concat(part2);
const arr = [...part1, ...part2];


Multiple inheritance

The spread operator, like Object.assign(), can be used to copy properties from one or more objects to an empty object and do multiple inheritance.


const authorGateway = { 
  getAuthors : function() {},
  editAuthor: function() {}
};
const bookGateway = { 
  getBooks : function() {},
  editBook: function() {}
};
//copy with Object.assign()
const gateway = Object.assign({},
      authorGateway, 
      bookGateway);

//copy with spread operator
const gateway = {
...authorGateway,
...bookGateway
};

Property short-hands

Consider the next code:


function BookGateway(){
function getBooks() {}
function editBook() {}

return {
getBooks: getBooks,
editBook: editBook
}
}

With property short-hands, when the property name and the name of the variable used as the value are the same, we can just write the key once.

function BookGateway(){
function getBooks() {}
function editBook() {}

return {
getBooks,
editBook
}
}

Here is another example:

const todoStore = TodoStore();
const userStore = UserStore();

const stores = {
todoStore,
userStore
};

Destructuring assignment

Consider the next code:


function TodoStore(args){
const helper = args.helper;
const dataAccess = args.dataAccess;
const userStore = args.userStore;
}

With destructuring assignment syntax, it can be written like this:

function TodoStore(args){
const {
helper,
dataAccess,
userStore } = args;
}

or even better, with the destructuring syntax in the parameter list:

function TodoStore({ helper, dataAccess, userStore }){}

Below is the function call:

TodoStore({
helper: {},
dataAccess: {},
userStore: {}
});

Default parameters

Functions can have default parameters. Look at the next example:


function log(message, mode = "Info"){
console.log(mode + ": " + message);
}
log("An info");
//Info: An info
log("An error", "Error");
//Error: An error


Template string literals

Template strings are defined with the &nbsp;charter. With template strings, the previous logging message can be written like this:</p><p><br></p><pre class="ql-syntax" spellcheck="false">function log(message, mode= "Info"){ console.log(${mode}: ${message}); } </pre><p>Template strings can be defined on multiple lines. However, a better option is to keep the long text messages as resources, in a database for example.</p><p>See below a function that generates an HTML that spans multiple lines:</p><pre class="ql-syntax" spellcheck="false">function createTodoItemHtml(todo){ return <li>
<div>${todo.title}</div>
<div>${todo.userName}</div>
</li>`;
}

Proper tail-calls

A recursive function is tail recursive when the recursive call is the last thing the function does.

The tail recursive functions perform better than non tail recursive functions. The optimized tail recursive call does not create a new stack frame for each function call, but rather uses a single stack frame.

ES6 brings the tail-call optimization in strict mode.

The following function should benefit from the tail-call optimization.

function print(from, to)
{
const n = from;
if (n > to) return;

console.log(n);
//the last statement is the recursive call
print(n + 1, to);
}
print(1, 10);


Note: the tail-call optimization is not yet supported by major browsers.

Promises

A promise is a reference to an asynchronous call. It may resolve or fail somewhere in the future.

Promises are easier to combine. As you see in the next example, it is easy to call a function when all promises are resolved, or when the first promise is resolved.

function getTodos() { return fetch("/todos"); }
function getUsers() { return fetch("/users"); }
function getAlbums(){ return fetch("/albums"); }
const getPromises = [
getTodos(),
getUsers(),
getAlbums()
];
Promise.all(getPromises).then(doSomethingWhenAll);
Promise.race(getPromises).then(doSomethingWhenOne);
function doSomethingWhenAll(){}
function doSomethingWhenOne(){}


The fetch() function, part of the Fetch API, returns a promise.

Promise.all() returns a promise that resolves when all input promises have resolved. Promise.race() returns a promise that resolves or rejects when one of the input promises resolves or rejects.

A promise can be in one of the three states: pending, resolved or rejected. The promise will in pending until is either resolved or rejected.

Promises support a chaining system that allows you to pass data through a set of functions. In the next example, the result of getTodos() is passes as input to toJson(), then its result is passed as input to getTopPriority(), and then its result is passed as input to renderTodos() function. When an error is thrown or a promise is rejected the handleError is called.

getTodos()
.then(toJson)
.then(getTopPriority)
.then(renderTodos)
.catch(handleError);
function toJson(response){}
function getTopPriority(todos){}
function renderTodos(todos){}
function handleError(error){}

In the previous example, .then() handles the success scenario and .catch()handles the error scenario. If there is an error at any step, the chain control jumps to the closest rejection handler down the chain.

Promise.resolve() returns a resolved promise. Promise.reject() returns a rejected promise.

Class

Class is sugar syntax for creating objects with a custom prototype. It has a better syntax than the previous one, the function constructor. Check out the next exemple:


class Service {
doSomething(){ console.log("doSomething"); }
}
let service = new Service();
console.log(service.proto === Service.prototype);


All methods defined in the Service class will be added to theService.prototype object. Instances of the Service class will have the same prototype (Service.prototype) object. All instances will delegate method calls to the Service.prototype object. Methods are defined once onService.prototype and then inherited by all instances.

Inheritance

“Classes can inherit from other classes”. Below is an example of inheritancewhere the SpecialService class “inherits” from the Service class:


class Service {
doSomething(){ console.log("doSomething"); }
}
class SpecialService extends Service {
doSomethingElse(){ console.log("doSomethingElse"); }
}
let specialService = new SpecialService();
specialService.doSomething();
specialService.doSomethingElse();

All methods defined in the SpecialService class will be added to the SpecialService.prototype object. All instances will delegate method calls to the SpecialService.prototype object. If the method is not found in SpecialService.prototype, it will be searched in the Service.prototypeobject. If it is still not found, it will be searched in Object.prototype.

Class can become a bad feature

Even if they seem encapsulated, all members of a class are public. You still need to manage problems with this losing context. The public API is mutable.


class can become a bad feature if you neglect the functional side of JavaScript. class may give the impression of a class-based language when JavaScript is both a functional programming language and a prototype-based language.

Encapsulated objects can be created with factory functions. Consider the next example:

function Service() {
function doSomething(){ console.log("doSomething"); }

return Object.freeze({
doSomething
});
}

This time all members are private by default. The public API is immutable. There is no need to manage issues with this losing context.

class may be used as an exception if required by the components framework. This was the case with React, but is not the case anymore with React Hooks.

For more on why to favor factory functions, take a look at Class vs Factory function: exploring the way forward.

Arrow functions

Arrow functions can create anonymous functions on the fly. They can be used to create small callbacks, with a shorter syntax.


Let’s take a collection of to-dos. A to-do has an id , a title , and a completed boolean property. Now, consider the next code that selects only the title from the collection:

const titles = todos.map(todo => todo.title);

or the next example selecting only the todos that are not completed:

const filteredTodos = todos.filter(todo => !todo.completed);

this

Arrow functions don’t have their own this and arguments. As a result, you may see the arrow function used to fix problems with this losing context. I think that the best way to avoid this problem is to not use this at all.


Arrow functions can become a bad feature

Arrow functions can become a bad feature when used to the detriment of named functions. This will create readability and maintainability problems. Look at the next code written only with anonymous arrow functions:


const newTodos = todos.filter(todo =>
!todo.completed && todo.type === "RE")
.map(todo => ({
title : todo.title,
userName : users[todo.userId].name
}))
.sort((todo1, todo2) =>
todo1.userName.localeCompare(todo2.userName));

Now, check out the same logic refactored to pure functions with intention revealing names and decide which of them is easier to understand:

const newTodos = todos.filter(isTopPriority)
.map(partial(toTodoView, users))
.sort(ascByUserName);
function isTopPriority(todo){
return !todo.completed && todo.type === "RE";
}

function toTodoView(users, todo){
return {
title : todo.title,
userName : users[todo.userId].name
}
}
function ascByUserName(todo1, todo2){
return todo1.userName.localeCompare(todo2.userName);
}

Even more, anonymous arrow functions will appear as (anonymous) in the Call Stack.

For more on why to favor named functions, take a look at How to make your code better with intention-revealing function names.

Less code doesn’t necessary mean more readable. Look at the next exampleand see which version is easier for you to understand:

//with arrow function
const prop = key => obj => obj[key];
//with function keyword
function prop(key){
return function(obj){
return obj[key];
}
}

Pay attention when returning an object. In the next example, the getSampleTodo() returns undefined.

const getSampleTodo = () => { title : "A sample todo" };
getSampleTodo();
//undefined


Generators

I think the ES6 generator is an unnecessary feature that makes code more complicated.


The ES6 generator creates an object that has the next() method. The next()method creates an object that has the value property. ES6 generators promote the use of loops. Take a look at code below:

function* sequence(){
let count = 0;
while(true) {
count += 1;
yield count;
}
}
const generator = sequence();
generator.next().value;//1
generator.next().value;//2
generator.next().value;//3

The same generator can be simply implemented with a closure.

function sequence(){
let count = 0;
return function(){
count += 1;
return count;
}
}
const generator = sequence();
generator();//1
generator();//2
generator();//3

For more examples with functional generators take a look at Let’s experiment with functional generators and the pipeline operator in JavaScript

Conclusion

let and const declare and initialize variables.


Modules encapsulate functionality and expose only a small part.

The spread operator, rest parameter, and property shorthand make things easier to express.

Promises and tail recursion complete the functional programming toolbox.

For more on JavaScript take a look at:

Discover Functional Programming in JavaScript with this thorough introduction


Learn these JavaScript fundamentals and become a better developer

Let’s explore objects in JavaScript

How point-free composition will make you a better functional programmer

How to make your code better with intention-revealing function names

Make your code easier to read with Functional Programming


By : Cristi Salcescu


JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !

7 Best Javascript Iframe Libraries

7 Best Javascript Iframe Libraries

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

1. Zoid

A cross-domain component toolkit, supporting:

  • Render an iframe or popup on a different domain, and pass down props, including objects and functions
  • Call callbacks natively from the child window without worrying about post-messaging or cross-domain restrictions
  • Create and expose components to share functionality from your site to others!
  • Render your component directly as a React, Vue or Angular component!
    It's 'data-down, actions up' style components, but 100% cross-domain using iframes and popups!

Download


2. Postmate

Postmate is a promise-based API built on postMessage. It allows a parent page to speak with a child iFrame across origins with minimal effort.

Download


3. Iframe Resizer

Keep same and cross domain iFrames sized to their content with support for window/content resizing, in page links, nesting and multiple iFrames

Demo

Download


4. Iframely

Embed proxy. Supports over 1800 domains via custom parsers, oEmbed, Twitter Cards and Open Graph

Demo

Download


5. React Frame component

This component allows you to encapsulate your entire React application or per component in an iFrame.

Demo

Download


6. Seamless.js

A seamless iframe makes it so that visitors are unable to distinguish between content within the iframe and content beside the iframe. Seamless.js is a JavaScript library (with no dependencies) that makes working with iframes easy by doing all the seamless stuff for you automatically.

Demo

Download


7. Porthole

A proxy to safely communicate to cross-domain iframes in javascript

Demo

Download


Thank for read!