Let Vs Var : Battle between modern javascript keywords

Let Vs Var : Let's the battle begins

There are two important javascript keywords ( let and const ) introduced by ECMAScript 2015. These two keywords provide Block scope in Javascript.

Before this, Javascript had only two type of scopes i) Global Scope and ii) Local Scope

JavaScript Block Scope

Variables declared with the var keyword inside a block {} can be accessed from outside the block.


{ 
    var x = 2; 
}
// x CAN be used here

Variables declared with the let keyword can have Block Scope and can't be accessed from outside of the block.


{ 
    let x = 2;
}
// x can NOT be used here

 

Let's check out some examples:


var x = 10;
// Here x is 10
{ 
    var x = 2;
    // Here x is 2
}
// Here x is 2

Here var x can not have block scope. That'why the value of x of line 1  overwrites by the value of x of line 4.


var x = 10;
// Here x is 10
{ 
    let x = 2;
    // Here x is 2
}
// Here x is 10

Here let x can have block scope. It means the value of x with prefix let has scope inside block only. This value doesn't available outside of the block.

Let keyword with Loop Scope


var i = 5;
for (var i = 0; i < 10; i++) {
    // some statements
}
// Here i is 10

Here, using var,  variable declared on line number 1. Then redeclared inside the loop. Value of var i overwrites everytime loop runs.

Using let in a loop:


let i = 5;
for (let i = 0; i < 10; i++) {
    // value of available inside this loop only
}
// Here i is 5

Here, using let,  variable declared on line number 1 has scope globally. Then variable redeclared inside the loop has scope inside the loop.

Redeclaring a var variable with let, in the same scope, or in the same block, is not allowed:

Example


var x = 2;       // Allowed
let x = 3;       // Not allowed

{
    var x = 4;   // Allowed
    let x = 5   // Not allowed
}

Redeclaring a variable with let, in the same scope, or in the same block, is not allowed:

Example


let x = 2;       // Allowed
let x = 3;       // Not allowed

{
    let x = 4;   // Allowed
    let x = 5;   // Not allowed
}

Redeclaring a variable with let, in another scope, or in another block, is allowed:

Example


let x = 2;       // Allowed

{
    let x = 3;   // Allowed
}

{
    let x = 4;   // Allowed
}

With the above explanation, I can surely tell that now you have the total idea about the difference between let and var variables.

Promise Vs Callback function in Javascript

Difference between a promise and a callback in Javascript:

Let's start the battle. Promise Vs Callback

Everything you can do with promises you can do with callbacks.
The deep reason why promises are often better is that
the combination of multiple promises just works, while combining multiple callbacks often doesn't.

Check this link: Promises: A complete explanation of modern JavaScript

For the example you gave of a single callback versus a single promise, it's true there's no significant difference. It's when you have a combination of callbacks (Callback Hell) versus a combination of promises that the promise-based code tends to look much nicer.

Let's check out an example of Callback Hell:

  
fs.readdir(source, function (err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function (filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function (err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function (width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})

It's not easily maintainable.

Promise has an advantage over callback is by the uniform handling of return values and uncaught exceptions. With callbacks, how an exception gets handled may depend entirely on which of the many nested callbacks threw it.

Arrow Function : A concise and fat form of javascript function

Arrow Function both make your code more concise while also making the “this” keyword more manageable. It allows having implicit return without having return keyword.

Benefits of Arrow Function:

  1. It has a shorter syntax than a function expression.
  2. It does not have its own this, super, arguments, new.target.

Read also: How to use Conditional/Ternary Operator in Javascript

Let's see the first benefit:

Let's take a look at the traditional function with one parameter:

 function functionName(arg) {
   return arg + 3;
 }
funcName(2); 

OR


var func = function functionName(arg) {
  return arg + 3;
};
func(2);

Now the same example using arrow function


var func = (arg) => { arg + 2 }
funcName(2);

If { } contains single statement. You can omit the parentheses and write


var func = (arg) => arg + 2 
funcName(2);

Let's take a look at the traditional function with multiple parameters:

 function functionName(x,y) {
   return x + y;
 }
funcName(2,3); 

OR


var funcName = function (x,y) {
  return x + y;
}
funcName(2,3);

Let's check out the same example using arrow functions:


var funcName = (x,y) =>  x + y  
funcName(2,3);

Now I am taking another example of a function with no parameter:

 function functionName() {
   return "Arrow function by DasJs";
 }
funcName(); 

OR


var funcName = function () {
  return "Arrow function by DasJs";
}
funcName();

The same example using Arrow functions:


var funcName = () =>  "Arrow function by DasJs"  
funcName();

 

If you have a single parameter, you can remove parenthesis of the parameter. You can also write as below:


var funcName = arg => arg + 2  
funcName();

 

Signature Pad JS: How to use in websites or apps

Signature Pad is a javascript library using for drawing smooth signature. It works on HTML canvas. It is compatible with all modern browsers. No need to add any external libraries.
It has an ability to record the drawn signature in JSON for later use.

How to use Signature Pad JS:

Include CSS file before closing tag of 'head'. Download

 <link rel='stylesheet'  href='path to css/signature-pad-1.css' type='text/css' media='all' /> 

It has some styles for the body tag. Maybe not suitable for your project. You can change it as per your requirement.

Include this library just before the closing tag of 'body'. Download

 <script src="js/signature_pad.umd.js"></script> 

Now you have included all files required for its working.

Now write some HTML code to run.


<div id="signature-pad" class="signature-pad">
  <div class="signature-pad--body">
    <canvas></canvas>
  </div>
  <div class="signature-pad--footer">
    <div class="description">Sign above</div>

    <div class="signature-pad--actions">
      <div>
        <button type="button" class="button clear" data-action="clear">Clear</button>
        <button type="button" class="button" data-action="change-color">Change color</button>
        <button type="button" class="button" data-action="undo">Undo</button>
      </div>
      <div>
        <button type="button" class="button save" data-action="save-png">Save as PNG</button>
        <button type="button" class="button save" data-action="save-jpg">Save as JPG</button>
        <button type="button" class="button save" data-action="save-svg">Save as SVG</button>
      </div>
    </div>
  </div>
</div>

It's time to make it live. So, write some javascript code make this working.

 


var wrapper = document.getElementById("signature-pad");
var clearButton = wrapper.querySelector("[data-action=clear]");
var changeColorButton = wrapper.querySelector("[data-action=change-color]");
var undoButton = wrapper.querySelector("[data-action=undo]");
var savePNGButton = wrapper.querySelector("[data-action=save-png]");
var saveJPGButton = wrapper.querySelector("[data-action=save-jpg]");
var saveSVGButton = wrapper.querySelector("[data-action=save-svg]");
var canvas = wrapper.querySelector("canvas");
var signaturePad = new SignaturePad(canvas, {
  // It's Necessary to use an opaque color when saving image as JPEG;
  // this option can be omitted if only saving as PNG or SVG
  backgroundColor: 'rgb(255, 255, 255)'
});

// Adjust canvas coordinate space taking into account pixel ratio,
// to make it look crisp on mobile devices.
// This also causes canvas to be cleared.
function resizeCanvas() {
  // When zoomed out to less than 100%, for some very strange reason,
  // some browsers report devicePixelRatio as less than 1
  // and only part of the canvas is cleared then.
  var ratio =  Math.max(window.devicePixelRatio || 1, 1);

  // This part causes the canvas to be cleared
  canvas.width = canvas.offsetWidth * ratio;
  canvas.height = canvas.offsetHeight * ratio;
  canvas.getContext("2d").scale(ratio, ratio);

  // This library does not listen for canvas changes, so after the canvas is automatically
  // cleared by the browser, SignaturePad#isEmpty might still return false, even though the
  // canvas looks empty, because the internal data of this library wasn't cleared. To make sure
  // that the state of this library is consistent with visual state of the canvas, you
  // have to clear it manually.
  signaturePad.clear();
}

// On mobile devices it might make more sense to listen to orientation change,
// rather than window resize events.
window.onresize = resizeCanvas;
resizeCanvas();

function download(dataURL, filename) {
  if (navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") === -1) {
    window.open(dataURL);
  } else {
    var blob = dataURLToBlob(dataURL);
    var url = window.URL.createObjectURL(blob);

    var a = document.createElement("a");
    a.style = "display: none";
    a.href = url;
    a.download = filename;

    document.body.appendChild(a);
    a.click();

    window.URL.revokeObjectURL(url);
  }
}

// One could simply use Canvas#toBlob method instead, but it's just to show
// that it can be done using result of SignaturePad#toDataURL.
function dataURLToBlob(dataURL) {
  // Code taken from https://github.com/ebidel/filer.js
  var parts = dataURL.split(';base64,');
  var contentType = parts[0].split(":")[1];
  var raw = window.atob(parts[1]);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);

  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  return new Blob([uInt8Array], { type: contentType });
}

clearButton.addEventListener("click", function (event) {
  signaturePad.clear();
});

undoButton.addEventListener("click", function (event) {
  var data = signaturePad.toData();

  if (data) {
    data.pop(); // remove the last dot or line
    signaturePad.fromData(data);
  }
});

changeColorButton.addEventListener("click", function (event) {
  var r = Math.round(Math.random() * 255);
  var g = Math.round(Math.random() * 255);
  var b = Math.round(Math.random() * 255);
  var color = "rgb(" + r + "," + g + "," + b +")";

  signaturePad.penColor = color;
});

savePNGButton.addEventListener("click", function (event) {
  if (signaturePad.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad.toDataURL();
    download(dataURL, "signature.png");
  }
});

saveJPGButton.addEventListener("click", function (event) {
  if (signaturePad.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad.toDataURL("image/jpeg");
    download(dataURL, "signature.jpg");
  }
});

saveSVGButton.addEventListener("click", function (event) {
  if (signaturePad.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad.toDataURL('image/svg+xml');
    download(dataURL, "signature.svg");
  }
});

That's it. If you face any problem in adding this in your project. Feel free to comment here. I will try to reply you as soon as possible.

Check following demo:

 

Promises: A complete explanation of modern JavaScript

JavaScript Promises: Allow us to first discuss JavaScript and its concurrency. JavaScript is single-threaded. It means all the things happen in a sequence as it's written, line-by-line. What do you think the results of the following example:

console.log("I am first");
setTimeout(function(){console.log("I am second");},3000);
console.log("I am third");
setTimeout(function(){console.log("I am fourth");},1000);

Your expected answer: 

  1. I am first
  2. I am second
  3. I am third
  4. I am fourth

But actual answer: 

  1. I am first
  2. I am third
  3. I am fourth
  4. I am second

The explanation above example without Promises:

Actually, 1st executed immediately. But the 2nd line has to wait for 3 seconds. So, 3rd line executed after 1st line. 4th line follow this sequence because it has to wait for 1 second. At the end 2nd line executed.

In a web app, You could use multiple asynchronous tasks and any if any task depends on early executed task's response, then you could get unexpected results.

Check this link:  Promise Vs Callback function in Javascript

A promise is a javascript object, represents a value may not available but will be available at some point in the future. It wraps an async task and notifies when it's completed. If you use the promise API for an asynchronous call to a remote web service. You will create a javascript object of promise that holds the data available in the future.

var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…

if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});

This constructor has an argument, is a callback with two parameters i.e. resolve and reject.
When you perform any async task successfully then call resolve otherwise call reject.

promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});

Now promise object has data. It may be resolved data or rejected data.

Check the following demo for a better explanation.

See the Pen An Overview of JavaScript Promises

ScrollReveal Js A javascript library to reveal elements

ScrollReveal Js is a library used to reveal elements when elements enter in the viewport. When you scroll a web page, then you can see the elements appear with some animations. It creates awesome effects. Today we create awesome effects using CSS but Javascript also has been used to create nice animation. There are lots of javascript libraries dedicated to creating animations. ScrollReveal.Js is one of them.

Features of ScrollReveal.Js

  1. It is very small about 3 KB in size.
  2. No dependency. No need to use any dependency js library like jQuery.
  3. Very easy to install
  4. Very simple coding syntax

Install ScrollReveal.Js

Firstly you need this library file. For this, You can download from its GitHub repositories. If you don't want to take it from GitHub you can also use Bower to download.

bower install scrollReveal.js

Now you have a library. You have to add this library in your project before closing tag of the body (</body>).

<script src="path/to/scrollReveal.min.js"></script>

It's time to make a web page animated. Actually, ScrollReveal Js searches elements having attribute "data-src'. So, you just add 'data-src' in all elements in which you want scrollReveal animation working. See the following example of code.

<body>
<div data-sr>first div to animate</div>
<div data-sr>second div to animate</div>
<div data-sr>yet another div to animate</div>
</body>

 

It's time to add a single line of javascript code to make this animation live.

new scrollReveal();

That's it. Run your page and see the magic.

Check out another example on jsfiddle: