Sunday, 29 August 2021

Functional Programming Using JavaScript

 Programming languages are classified in number of ways. One popular method for classfying is Programming paradigm

Let's look at couple of paradigm that are relevant to current topic. 

Imperative is where  programmer instruct a machine how to change its state. Procedural and object oriented programming are derived from Imperative Programming. 

Declarative is where a programmer only defines properties of results leaving how to compute it. Functional programming falls under this category. The desired result is declared as the value of series of function applications.

Fundamental difference between procedural, object-oriented, and functional programming.

Procedural Programming

It can be represented as assembly lines. 

"Raw Input → Step 1 → Step 2 → … → Step n → Final Product. 

  • Raw input is changed (mutated) at every step. 

  • Each step is depend upon previous step. 

  • There is no meaning of an individual step in isolation. 

  • We get only one specific product. If we need a slightly different change in product, then we need new assembly line. 

In terms of programming, the global mutable state (raw material is changing at every step) creates interdependencies. 

Object-Oriented Programming

Same as procedural but with some modularisation. The global state is broken down into objects a part of instruction can change only a part of state. Albeit, interdependencies still exist.

Functional Programming

It takes completely different approach. Programs are formed by appying and composing functions. A programmer tries to bind everything into purely mathematical function style. Using pure function instead of procedures avoids mutable state. The main focus is on what to solve in contrast to how to solve in imperative programming.

// Imperative
const list = [1, 2, 3, 4, 5];
const item = list[list.length - 1];
 
 
// Declarative
const list = [1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 15, 16, 18, 20];
const item = getLastItem(list);

Basic Concepts in Functional Programming : 
 
A programming language is said to have first-class functions when a function in that language is treated like any other variable.
 
A function can be : 
  • assigned to a variable
  • passed as an argument
  • returned by another function
// Assign a function to a variable
const foo = function() {
   console.log("foobar");
}
foo(); // Invokve using variable


// Pass a function as an argument
function sayHello() {
   return "Hello, ";
}
function greeting(helloMessage, name) {
  console.log(helloMessage() + name);
}
greeting(sayHello, "JavaScript!"); // Pass `sayHello` as an argument to `greeting` function


// Return a function
function sayHello() {
   return function() {
      console.log("Hello!");
   }
}
 
 

Higher-Order Function

Takes a function as an argument or returns a function or both.

 
// Takes function as an argument - map
const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(number => number * 2); // [2, 4, 6]

// Returns a function
function sayHello() {
   return function() {
      console.log("Hello!");
   }
}
 
 

Immutability : 

Immutable means unchangeable. Once array/object is defined, it can't be modified. To change properties of object or change element of an array, one should create a new copy of an array or an object with a changed value.

 
var myCar = {
    make: 'Ford',
    model: 'Mustang',
    year: 1969
};
myCar.model = 'Mercedes';

myCar.year= 1999;

// Instead should be achieved as -

const myCar = {
    make: 'Ford',
    model: 'Mustang',
    year: 1969
};

const updatedCar = {
    ...myCar ,
    model: 'BMW',
};

const latestYear = {
    ...updatedCar ,
    year: 2021,
};
 
 
// Get all evens

const numbers = [2, 4, 5, 6, 8, 10];
numbers.splice(2, 1);
console.log(numbers); // [2, 4, 6, 8, 10]

// Instead should be achieved as -

const numbers = [2, 4, 5, 6, 8, 10];
const evens = [...numbers.slice(0, 2), ...numbers.slice(3)];
console.log(evens); // [2, 4, 6, 8, 10]
 
 

Pure Function

 A pure function is a function that given the same input will always return the same output and does not have any observable side effects.

 
Side effects include - 
  • changing a file system
  • inserting a record in a DB
  • querying DOM
  • mutations

 

// Impure
const list = [1,2,3,4,5];

list.splice(0,3); // [1,2,3]

list.splice(0,3); // [4,5]

list.splice(0,3); // []

// Pure
const list = [1,2,3,4,5];

list.slice(0,3); // [1,2,3]

list.slice(0,3); // [1,2,3]

list.slice(0,3); // [1,2,3]
 
 
 
const list = [1,2,3,4,5];

// impure
const addToList = (list, number) => {
  list.push(number);
  return list;
}

// pure
const addToList = (list, number) => {
  const newList = [...list];
  newList.push(number);
  return newList;
}
 

Currying

Currying is where you can call a function with fewer arguments than it expects. It then returns a function that takes the remaining arguments.

 
const discount = (price, percent) => (price * percent);
discount(100, 0.1); // 10

// Currying

const discount = percent => price => price * percent;

const flat10Percent = discount(0.1);
const flat50Percent = discount(0.5);
const newYearDiscount = discount(0.7);

flat10Percent(100); // 10
flat50Percent(100); // 50
newYearDiscount(100); // 70
 
 
function sum(a, b) {
  return a + b;
}

// Actual    : sum(1, 2);
// Expected  : sum(1)(2);

function curry(f) {
  return function(a) {
    return function(b) {
      return f(a, b);
    };
  };
}
let curriedSum = curry(sum);
curriedSum(1)(2); // 3
 

Composition

Composition simply is to compose 2 functions to create a new function.

 

 
f(x) = x * 2
g(y) = y + 1

g.f = g(f(x))

composition:    g(f(x)), for x = 2; Result = 5


f: x -> y
g:      y -> z
h: x    ->   z
__________________________
For x = 2:

f: 2 -> 4
g:      4 -> 5
h: 2    ->   5 


const f = x => x * 2;
const g = y => y + 1;

const compose = (g, f) => x => g(f(x));
const h = compose(g, f);
h(2); // 5

Pointfree

Pointfree simply means we don’t explicitly specify what data is being passed to a function.

f(x) = g(x)

// Point free
f = g

-------------------------------------

const numbers = [1, 2, 3, 4, 5];
const doubles = numbers.map(x => x * 2);

// Making it pointfree

const double = x => x * 2
const numbers = [1, 2, 3, 4, 5]
const doubles = numbers.map(double); // Point free
 
Instead of grasping all difficult principles of functional programming, one could start small by breaking large functions into smaller reusable ones and then composing them together.
 
Hope the tiny gists help you understand the concepts. 
 

Checkout very powerful and helpful funnel & web page builder which automates Traffic, Leads, Commissions and Sales
 
Thanks for reading :) 

Tuesday, 24 August 2021

Power of console.table() in JavaScript

 Debugging is the skill that all developers should have in their toolbox. 

Console.log() is a very powerful, quick and useful method for debugging in JavaScript. Every developers use this method to debug code in everyday life. There's nothing wrong with this. 

But today I'm going to share a tip that makes you debug JavaScript code more efficiently.  

console.table()

So, what is console.table()

console.table() allows to print arrays and objects in tabular form in the console. Tabular format works like a charm because you will get greater insight into your data. Thus, makes you debug your code just faster. You can also sort columns quickly. 

Syntax : 


console.table(data,columns); 
//or
console.table(data);


data:- The data to fill the table with. It must be either an array or an object.
• columns:- array containing the names of the columns to be included in the table.

How to implement console.table()

console.table() can be implemented in the following ways:

 a. Array : 

If  the value of data argument is an array, then the index column willl be incremented by one, ith the starting value being 0.

 

var fruits=["apple","mango","grapes"];
console.table(fruits);

 

Output :

Screenshot (402).png 
 
 To sort the column, click on the header of that column. 

b. Array of arrays

When we print an array of arrays then the column names will be incremented in the same way as the index column values

var teams=[["John","Jari"],["Claus","Andrew"],["Marti","Martha"]];
console.table(teams);
 

Output : 

 
Screenshot (403).png 

 C. Object

 

If the data argument is an object, then index column represents key and value column represents the value corresponding to that particular key.

 
var user={
     name:"Rajvi",
     age:20,
     gender:"female",
}
console.table(user);
 

Output : 



 

d. Array of Objects

If the value of the data argument is an array of objects then their properties are enumerated in the row, one per column.

 
var users = [
    {
        name: "john",
        age: 22
    },
    {
        name: "bella",
        age: 25
    },
    {
        name: "Shinchan",
        age: 30
    }
];
console.table(users);

 

Output :


e. Nested Objects

If the value of data argument is nested objects which means objects whose properties are themselves objects, then console.table() method labels index appropriately with the nested object properties.

var employees = {
    leader: {
        firstname: "Rajvi",
        lastname: "Sudo",
        email: "Rajvi@gmail.com"
    },
    manager: {
        firstname: "Vihan",
        lastname: "Bhatt",
        email: "Vihan@gmail.com"
    },
    developer: {
        firstname: "Smith",
        lastname: "reddy",
        email: "Smith@gmail.com"
    }
}
console.table(employees);
 

Output : 

 
 

What if you have an Object that has 10+ properties

 
If you've very large object,  this table can become very large and data can be difficult to read. But thankfully, console.table provides  an optional second argument that will specify the columns we want and only print those out.
 
 
 
var employees = {
    leader: {
        id:"10001",
        firstname: "Andrew",
        lastname: "Story",
        email: "andrew@gmail.com"
    },
    manager: {        
        id:"10002",
        firstname: "Amit",
        lastname: "Bhatt",
        email: "amit@gmail.com"
    },
    developer: {
        id:"10003",
        firstname: "Param",
        lastname: "Dutta",
        email: "param@gmail.com"
    }
}
console.table(employees,["id","firstname"]);
 

Output : 

 

Screenshot (407).png

 
 
If you require only one column, this could be done like this: 
 
 
console.table(employees,"id");
 

 Output : 

 Screenshot (408).png

That's all for this article. If you enjoyed and found it useful, do like and share so it reaches to others as well. Thanks for reading :)


Sunday, 22 August 2021

Must Know HTML Tags That Almost Nobody Knows

Web developers are expected to work with multiple languages these day. So it's inconvenient to learn everything a language has to offer and obvious to find them not utilizing full potentialof some specialized features. 

We use HTML everyday. But still there is enough left to know about it. It's never too late to get back into game and start writing code that taps into the power of some under-used tags.

Here are 5+  HTML tag that almost nobdy knows.

1. Fieldset Tag

The <fieldset> tag  is used to group related form elements. By using fieldset and legend tag, you can make your form design clearer.
 
<!DOCTYPE html>
<html>
   <head>
      <title>HTML fieldset Tag</title>
   </head>
   <body>
      <form>
         <fieldset>
            <legend>Details</legend>
            Student Name: <input type = "text"><br />
            Subjects:<input type = "text"><br />
            Course Link:<input type = "url" name = "websitelink">
         </fieldset>
      </form>
   </body>
</html> 

Output : 
 

 

2. DataList Tag:

The <datalist> tag is used to provide an autocomplte feature to an input element. Users will get drop-down list of pre-defined options as they input data.

 

<!DOCTYPE html>
<html>
<body>

<h1>The datalist element</h1>

<form action="/action_page.php" method="get">
  <label for="browser">Choose your browser from the list:</label>
  <input list="browsers" name="browser" id="browser">
  <datalist id="browsers">
    <option value="Edge">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
  <input type="submit">
</form>

</body>
</html>

Output :
 

datalist.jpeg 

 

3.Time Tag:

The <time> tag defines a specific time (or datetime). The datetime attribute of this element is used to translate the time into a machine-readable format so that browsers can offer to add date reminders through the user's calendar, and search engines can produce smarter search results.

 

<!DOCTYPE html>
<html>
<body>

<h1>The time element</h1>

<p>Open from <time>10:00</time> to <time>21:00</time> every weekday.</p>
</body>
</html>

Output : 

time.jpeg

 

4. Color Picker Tag:

The <color> tag  defines a color picker. It provides the user interface that lets a user specify a color, either by using a visual color picker or by entering hexadecimal value of a color.


<!DOCTYPE html>
<html>
 <head>
 </head>
 <body>
   <label for="colorpicker">Color Picker:</label>
   <input type="color" id="colorpicker" value="#0000ff">
 </body>
</html>
 
 
Output : 
 colorpicker.jpeg

 

5. Progress Tag:

The <progress> HTML element displays an indicator showing progress of a task, typically displayed as a progress bar.

 

<!DOCTYPE html>
<html>
<body>

<h1>The progress element</h1>

<label for="file">Downloading progress:</label>
<progress id="file" value="32" max="100"> 32% </progress>

</body>
</html>

Output : 

 

 

6. Abbreviation Tag:

The <abbr> tag is used to define acronym or abbreviation of an element. It is used to provide useful information to the browsers, translation systems, and search engines. Learn in-depth about abbreviation tag here.



<!DOCTYPE html>
<html>
<body>

<h1>The abbr element</h1>

<p>The<abbr title="Alabama">AL</abbr>is in USA</p>

</body>
</html>
 
 
Output : 
 
 
abbr.jpeg
 
 

 

7. Template Tag:

The <template> tag is used to hold some HTML content hidden from the user when the page loads. The content inside can be rendered later with JavaScript. See more about this tag here.
 
 
<!DOCTYPE html>
<html>
<body>

<h1>The template Element</h1>

<p>Click the button below to display the hidden content from the template element.</p>

<button onclick="showContent()">Show hidden content</button>

<template>
  <h2>Flower</h2>
  <img src="https://www.deadlinenews.co.uk/wp-content/uploads/2020/10/andrew-small-EfhCUc_fjrU-unsplash-scaled.jpg" width="214" height="204">
</template>

<script>
function showContent() {
  var temp = document.getElementsByTagName("template")[0];
  var clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
}
</script>

</body>
</html>
 
 
Output : 
 
 template.jpeg
I hope that you got something useful today. If that so let me know in the comments. Thanks for reading :)

Wednesday, 18 August 2021

What is HTML, CSS and JavaScript?

Hello  there, my gorgeous friends on the internet ? What's going on ? 

Today's article is all about why should you learn HTML, CSS and JavaScript and what is it actually. How these forms skeleton for developing a website. 

So let's get started. 

What is HTML, CSS and JavaScript

1. What is actually HTML?

According to the internet, it is Hyper Text Markup Language. Now let's look at what's this mean. 

Hyper-Text are texts, images, tables, and other representative formats that are been displayed on a computer, this includes what we see on our browsers.

While Markup Language in computer science refers to languages that are human-readable and are written within tags. 

Which means HTML are ways of writing human-readable contents with tags. 

Web page only written in HTML looks like human with skeleton only. Which is very scary and unattractive. HTML are skeleton without flesh.  So it will be very difficult to get job as an HTML Developer. 

HTML only project 

Skeleton

 
Below is how FaceBook page will look like with just HTML 

facebook without css.png

Will anyone use FaceBook with this look ? No one will. 

2. What is actually CSS?

It stands for cascading style sheet. It decides how HTML content will be represented on browser. 

This design and description includes colors, layout, background-colors, visibility, display and much more. Here CSS is missing flesh in skeleton. So now it is less scary and more attractive. 

See the image below. 

Skeleton-with-body

Now, we've good looking figure, let's see how FaceBook page looks with CSS. 

FaceBook-with-CSS.png

Friendly and attractive, right ? 

Now, the good news for you is you can earn income by just mastering HTML and CSS. A company can hire you to build their website or rebuild their portfolio. 

Below are some project ideas to showcase your HTML and CSS skills. 

1. Small Business Portfolios

Have you noticed small shop down your street ? You can approach the owner and offer them to build them a portfolio (free or with a discount) and get a chance to be recommended to their networks/ colleagues. 

2. Company Landing Page 

Every small scale to large scale business want their online presence to market their work,  a website, which you're good at building, reach out to such businesses and show them what you can build with explanation why they should consider your design. Ask them if they want something similar or better than your sample.

3. Individual Portfolio 

Every professional, from engineer, model, photographer, farmer needs online presence to showcase their work experience and talent. You can approach them with reasons to have a portfolio that make them stand out in market. This in turn makes them your next client and plus 1 project in your portfolio. 

These are just very few opportunity turn your skill into profession. 

Check out these article which may be helpful for building your portfolio. 

A List of CSS resources for beginners - by devin ford 

Over 10 Frontend Challenges - by Ayodele Samual Adebayo 

Top 10 project for Beginners to practice HTML and CSS