Technolize Your Future https://techtalkbook.com Better Your Future with Tech Knowledge Sun, 22 Sep 2019 18:50:07 +0000 en hourly 1 https://wordpress.org/?v=5.2.3 https://i0.wp.com/techtalkbook.com/wp-content/uploads/2019/01/cropped-logo.png?fit=32%2C32&ssl=1 Technolize Your Future https://techtalkbook.com 32 32 114221274 Create mac app from a shell script https://techtalkbook.com/create-mac-app-from-a-shell-script/ https://techtalkbook.com/create-mac-app-from-a-shell-script/#respond Fri, 20 Sep 2019 07:50:47 +0000 https://techtalkbook.com/?p=1473 Ever thought of having an application to run it directly instead of multiple shell commands? And won’t it be cool to just convert your shell script into a Mac application and use it just like any other mac applications? So... Continue Reading →

The post Create mac app from a shell script appeared first on Technolize Your Future.

]]>
Ever thought of having an application to run it directly instead of multiple shell commands?
And won’t it be cool to just convert your shell script into a Mac application and use it just like any other mac applications?

So let’s learn today to create mac app from a shell script.

Before jumping into the application creation, we will quickly see how an application folder structure in Mac looks like:

The bare minimum folder structure is something like below that you will find for any applications in Mac.

(app-name).app
├── Contents
│   └── MacOS
│   └── (app-name)
└── Icon

So now let’s get started. We need mainly three things for our application:

  1. An executable shell script which will make your shell script as an application.
  2. Your actual shell script to make it as an application.
  3. Add an icon to your application. (Not Mandatory but looks cool like real app)

Let’s walk through these steps one by one:

  1. An executable shell script which will make your shell script as an application:

    #!/usr/bin/env bash
    
    APPNAME=${2:-$(basename "${1}" '.sh')};
    DIR="${APPNAME}.app/Contents/MacOS";
    
    if [ -a "${APPNAME}.app" ]; then
      echo "${PWD}/${APPNAME}.app already exists. Provide some unique name if you want to create it anyway. ";
      exit 1;
    fi;
    
    mkdir -p "${DIR}";
    cp "${1}" "${DIR}/${APPNAME}";
    chmod +x "${DIR}/${APPNAME}";
    
    echo "${PWD}/$APPNAME.app";

    • Create a file with the above script and save it in /usr/local/bin .
    • Then make the above file as executable with the command from command line/Terminal: sudo chmod +x /usr/local/bin/appify
      Note:

      • You can give it any name and no extension is required for the file.
      • For reference, we will give it a name as ‘appify’
      • We are saving the file at /usr/local/bin  so that we can directly call ‘appify’ script. If you want to save at any other place like your username directory then you will have to call the script with its full path like ‘/User/your-username/appify’
  2. Your actual shell script to make it as an application:
    • Now have your script file with .sh extension ready and run the below command to make you shell script as a Mac application.
      appify your-shell-script.sh "Your App Name"
  3. Add an icon to your application:
    This one is very simple.

    • Just copy any image you want as the app icon.
    • Right-click your new application select “Get Info”.
    • Select the app icon on the top left corner by clicking it just once.
    • and then either hit ⌘ + V to paste it or go to ‘Edit’ from menu link and select paste.
    • With this, it will overwrite the default icon with your new icon.

Now your application is ready to use just like any other application.

Below is a quick simple demo example to see the above process in action:

Mac application creation demo

 

I hope this post will help you learn how to create mac app from a shell script.

References:

The post Create mac app from a shell script appeared first on Technolize Your Future.

]]>
https://techtalkbook.com/create-mac-app-from-a-shell-script/feed/ 0 1473
why 0.1 + 0.2 does not equal to 0.3? https://techtalkbook.com/why-0-1-0-2-does-not-equal-0-3/ https://techtalkbook.com/why-0-1-0-2-does-not-equal-0-3/#respond Sun, 18 Aug 2019 19:19:28 +0000 https://techtalkbook.com/?p=1418 Have you ever discovered a scenario wherever you probably did some arithmetic computation on decimal numbers in a computer and it returned an unexpected weird result? That one question you’d have asked is why 0.1 + 0.2 does not equal... Continue Reading →

The post why 0.1 + 0.2 does not equal to 0.3? appeared first on Technolize Your Future.

]]>
Have you ever discovered a scenario wherever you probably did some arithmetic computation on decimal numbers in a computer and it returned an unexpected weird result?

That one question you’d have asked is why 0.1 + 0.2 does not equal to 0.3?

Examples:
  • 0.1 + 0.2 = 0.3 but computer says 0.30000000000000004
  • 6 * 0.1 = 0.6 but computer says 0.6000000000000001
  • 0.11 + 0.12 = 0.23 but again computer says 0.22999999999999998
  • 0.1 + 0.7 = 0.7999999999999999
  • 0.3+0.6 = 0.8999999999999999 and so on… There are several other such cases.

Note: It is also a interview questions that an interviewer asks “output of 0.1 + 0.2 == 0.3”? true or false? Simply to see how well you know arithmetic computations on decimal numbers by computer.

In straightforward sentences, the explanation behind this is:
  • The computer uses base-2 floating-point number whereas Human(We) use base-10 floating-point numbers.
  • In binary, decimal numbers cannot represent all decimals precisely and have infinite representations.
  • So computers can not accurately represent numbers like 0.1, 0.2 or 0.3 at all as it uses binary floating-point format.
Now let’s understand the elaborated reason behind this:
  • In base 10 system (Used by human/us), fractions can be expressed precisely if it uses a prime factor of the base (10).
    • 2 and 5 are the prime factors of 10.
    • 1/2, 1/4, 1/5 (0.2), 1/8, and 1/10 (0.1) can be expressed precisely as a result of denominators use prime factors of 10.
    • Whereas, 1/3, 1/6, and 1/7 are repeating decimals as a result of denominators use a prime factor of 3 or 7.
  • In base 2 (binary) system on the other hand (Used by computer), fractions can be expressed precisely if it uses a prime factor of the base (2).
    • 2 is the only prime factor of 2.
    • So 1/2, 1/4, 1/8 can all be expressed precisely because the denominators use prime factors of 2.
    • Whereas 1/5 (0.2) or 1/10 (0.1) are repeating decimals.
  • So we end up with leftovers for these repeating decimals and that carries over when we convert the computer’s base 2 number into a human-readable base 10 number.
Let’s take 0.1 as an example to understand binary and decimal representations:
  • 0.1 is one-tenth(1/10) and to get binary representation (bicimal) of 0.1, we need to use the binary long division that is to divide binary 1 by binary 1010 (1/1010) like below:
computation of 0.1 into binary representation

computation of 0.1 into binary representation

  • You can see above that the division process would never end and repeats forever with the digits in the quotient because 100 reappears as the dividend.
  • so the binary representation of our decimal number 0.1 will be as below:
Representation of 0.1 into binary form is 0.000110011001100110011001100110011001100110011001100110011001…

Representation of 0.1 into binary form is 0.000110011001100110011001100110011001100110011001100110011001…

  • Now above result can be slightly greater or Less than 0.1 which depends upon how many bits of precision are used.
    • In half-precision which uses 11 significant bits, the floating-point approximation of 0.1 could be less than 0.1
      so 0.1 rounds to 0.0001100110011 in binary and 0.0999755859375 in decimal.
      
      That's why the result becomes slightly less than 0.1
      0.0999755859375 < 0.1
    • In double-precision floating-point which uses 53 bits, the floating-point approximation of 0.1 could be greater than 0.1
      so 0.1 rounds to 0.0001100110011001100110011001100110011001100110011001101 in binary
      and 0.1000000000000000055511151231257827021181583404541015625 in decimal.
      
      That's why the result becomes slightly greater than 0.1
      0.1000000000000000055511151231257827021181583404541015625 > 0.1

Due to all this, a decimal point may not give exact floating-point result as

  • In pure math, every decimal has an equivalent bicimal (decimal converted to binary)
  • In floating-point math, this is can be simply not true and that we do not get precise value for every decimal number.
    Note: In most calculators, we see 0.1 + 0.2 = 0.3 despite the fact that that’s also a computing device. The explanation is that it uses additional guard digits to get around this downside by rounding off the final few bits.
References:

Below are some useful links you can refer to get even additional dipper into the floating-point arithmetics in computer.

 

I hope this can clear a number of your queries on why the computer does not return an expected output when we do the mathematical operation with decimal numbers.

Also, I believe you would be in a better position now to reply back if someone asks you why 0.1 + 0.2 does not equal to 0.3?

Happy Learning!!!

The post why 0.1 + 0.2 does not equal to 0.3? appeared first on Technolize Your Future.

]]>
https://techtalkbook.com/why-0-1-0-2-does-not-equal-0-3/feed/ 0 1418
JavaScript Generator and how it works. https://techtalkbook.com/javascript-generators-and-how-it-works/ https://techtalkbook.com/javascript-generators-and-how-it-works/#respond Mon, 18 Mar 2019 13:06:12 +0000 http://techtalkbook.com/?p=1293 JavaScript supports Generator functions and Objects similar to Python Generators. Let’s see what is JavaScript Generators and how it works. What is Generator Generator in ES6 is a new way of working with functions and iterators. It appears to be... Continue Reading →

The post JavaScript Generator and how it works. appeared first on Technolize Your Future.

]]>
JavaScript supports Generator functions and Objects similar to Python Generators.
Let’s see what is JavaScript Generators and how it works.
What is Generator
  • Generator in ES6 is a new way of working with functions and iterators.
  • It appears to be a function but behaves like an iterator which simplifies the task of writing iterators.
  • It is different from a normal function in a way that it can stop midway and then continue from where it stopped.
  • In layman’s terms, It is similar to the way we put marker/bookmark to a page of the book we read. Then later we resume reading the book from that particular page instead of start reading all over again. Here we acted as a generator function.
  • It can generate a series of results instead of a single value.
Generator Syntax
  • Creating a generator is similar to normal function with some differences that it requires a * between function keyword and function name.
  • It allows any number of spaces or no spaces in between.
  • It uses a yield keyword to pause and resume the execution.
  • Since it is just a function, we can use it anywhere like normal function i.e. inside objects and class methods.
  • Basic syntax:

    // All below formats are valid with spaces/no spaces in between function keyword, * and function name.
    function * functionName() {
        // Your generator related codes here.
    }
    
    // OR below format.
    function *functionName() {
        // Your generator related codes here.
    }
    
    // OR below format.
    function* functionName() {
        // Your generator related codes here.
    }
    
    // OR below format.
    function  *  functionName() {
        // Your generator related codes here.
    }
    
    // OR below format.
    
    function*functionName() {
        // Your generator related codes here.
    }
    
    // Inside Class method.
    class testClass {
        *functionName() {}
    }
    
    // Inside object
    var testObject = {
        *functionName() {}
    }
Yield in Generator
  • yield keyword is used to return the data and pause the execution of the generator.
  • Every time generator encounters a yield, it halts the execution at that point and returns the value specified.
    Then resumes the execution on calling the next() method on Generator object until it finds the next yield.
  • In the context of Generator, we do not say that it returned a value. We say that it has yielded the value.
  • Using return inside a Generator will set done property to true after which it cannot generate any more values.
    All the codes after the return statement will not execute.
  • Syntax:

    // Generator with yield. 
    function * generator() {
        console.log('First execution.');
        yield 'Yield First execution, saved the state and exit';
        console.log('Second execution will be on next() call.');  
        yield 'Yield second execution, saved the state and exit';
    }
    
    const generatorObj = generator();
next() in generator
  • Generator returns an object on which we can call next().
  • Every invocation of next() will return an object containing returned value and status of generator execution.
  • value property will contain the value and done property will be true or false mentioning generator’s execution status.
  • When done becomes true, generator stops and won’t generate any more values.
    {
        value: Any,
        done: true|false
    }
  • Sample code: ( jsfiddle link: generator example )
    function * generator() {
        console.log('First execution.');
        yield 'Yield First execution, saved the state and exit';
        console.log('Second execution will be on next() call.');  
        yield 'Yield second execution, saved the state and exit';
    }
    
    const generatorObj = generator();
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: 'Yield First execution, saved the state and exit', done: false}
    setTimeout(() => console.log(generatorObj.next()), 1000);
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: 'Yield First execution, saved the state and exit', done: false} 
    setTimeout(() => console.log(generatorObj.next()), 3000);
    
    // After below execution, generator will yield value, return below object and close execution.
    // {value: undefined, done: true}
    setTimeout(() => console.log(generatorObj.next()), 5000);
  • Below example shows the different state of a generator during its execution of how it gets suspended when it is yielded, resumes on next() call and then gets closed after all execution:

  • If we use return then it will not execute any code present after the return statement.
    Sample code: ( jsfiddle link: generator with return statement )
    function * generator() {
        console.log('First execution.');
        yield 'Yield First execution, saved the state and exit';
        return 'Execution ends here due to return and will not execute rest of the codes.';  
        // All below codes will not get executed.
        yield 'Yield second execution, saved the state and exit';
    }
    
    const generatorObj = generator();
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: 'Yield First execution, saved the state and exit', done: false}
    setTimeout(() => console.log(generatorObj.next()), 1000);
    
    // After below execution, generator will yield value, return below object and completes the execution.
    // {value: 'Execution ends here due to return and will not execute rest of the codes.', done: true}
    setTimeout(() => console.log(generatorObj.next()), 3000);
    
    // generator execution is already completed so it will just return value as undefined and done as true.
    // {value: undefined, done: true}
    setTimeout(() => console.log(generatorObj.next()), 5000);
  • We can also pass values to next().
    Sample code: ( jsfiddle linknext() with value passed )
    function * generator() {
        console.log('First execution.');
        yield 'Yield First execution, saved the state and exit';
        console.log('Second execution will be on next() call.');  
        let passedArgument = yield 'Yield second execution, saved the state and exit';
        yield passedArgument;
    }
    
    const generatorObj = generator();
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: 'Yield First execution, saved the state and exit', done: false}
    setTimeout(() => console.log(generatorObj.next()), 1000);
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: 'Yield First execution, saved the state and exit', done: false} 
    setTimeout(() => console.log(generatorObj.next()), 3000);
    
    // After below execution, generator will yield value, return below object and pause execution.
    // {value: "This is the passed value", done: false}
    setTimeout(() => console.log(generatorObj.next('This is the passed value')), 5000);
    
    // After below execution, generator will yield value, return below object and close execution.
    // {value: undefined, done: true}
    setTimeout(() => console.log(generatorObj.next()), 7000);
Why use Generator
  • Implementing Iterables:
    • Implementation of an iterator in JavaScript requires things to do manually like:
      • Manually create an iterator object.
      • Manually implement next() method.
      • Manually make return object of next() in the format:  { value: Any, done: true|false }
      • Manually save the state.
    • Below sample code shows how hard it is to manually implement everything in an iterator.

      const iterableObj = {
          [Symbol.iterator]() {
              var counter = 0;
              return {
                  next() {
                      counter++;
                          if (counter === 1) {
                              return { value: 'step one', done: false};
                          } else if (counter === 2) {
                              return { value: 'step two', done: false};
                          } else if (counter === 3) {
                              return { value: 'step three', done: false};
                          }
                      return { value: '', done: true };
                  }
              }
          },
      }
      
      for (const val of iterableObj) {
          console.log(val);
      }
    • Below sample code shows how easy it is with Generator which handles most of the things on its own.
      function * iterableObj() {
          yield 'step one';
          yield 'step two';
          yield 'step three';
      }
      
      for (const val of iterableObj()) {
        console.log(val);
      }
  • Lazy execution:
    Generator helps to delay the evaluation of an expression until its value is required.
    So If we don’t need a value, it won’t exist and is calculated only we need it.
  • Memory efficient:
    It is memory efficient because we generate only the values that are required.
    We need to pre-generate all the values in case of normal functions and keep them in case we use them later but generators can defer the computation of any expressions/codes until we need it.
Limitations
  • Generators are one-time access only. Once you’ve exhausted all the values, you can’t iterate over it again.
    To generate the values again, you need to make a new generator object.
  • Generators do not allow random access as possible with arrays. Since the values are generated one by one, accessing a random value would lead to computation of values till that element. Hence, it’s not random access.

 

I hope you will get some idea of JavaScript Generator and its basic functionalities from this post.

Happy coding!!!

View at Medium.com

The post JavaScript Generator and how it works. appeared first on Technolize Your Future.

]]>
https://techtalkbook.com/javascript-generators-and-how-it-works/feed/ 0 1293
JavaScript promises and how it works. https://techtalkbook.com/javascript-promises-and-how-it-works/ https://techtalkbook.com/javascript-promises-and-how-it-works/#respond Thu, 07 Mar 2019 16:40:58 +0000 http://techtalkbook.com/?p=1280 JavaScript has many ways to handle asynchronous calls and Promise is one of the mostly used built-in object nowadays. so let’s understand what is Promise and how it works. Promises: It’s a built-in object in JavaScript ES6 to handle asynchronous calls. Before... Continue Reading →

The post JavaScript promises and how it works. appeared first on Technolize Your Future.

]]>
JavaScript has many ways to handle asynchronous calls and Promise is one of the mostly used built-in object nowadays.

so let’s understand what is Promise and how it works.

Promises:

  • It’s a built-in object in JavaScript ES6 to handle asynchronous calls.
  • Before Promises were introduced in ES6, callback functions were used to handle async calls.
  • Promises provide a cleaner and more refined syntax to handle async calls.


Promise structure: (It has 2 parts)

  • First part: Create the Promise and define conditions for success or failure of calls.
    basic syntax: let promise1 = new Promise( (fn1, fn2) => { ...} );

    • During instantiation of the object using new keyword, it takes a function (fn1, fn2) as an argument which itself has 2 arguments as functions f1 and f2.
    • We can name them anything as these are just functions but resolve & reject, is the standard naming for better understanding.
      let promise1 = new Promise((resolve, reject) => { ... });
    • So resolve and reject arguments in Promises are nothing but callback functions.
    • These functions accept no argument or a single argument (Of type string, number, boolean, array or object).
    • On resolve(), it executes then() method and on reject(), it executes catch() method.
  • Second part: Describes action to take when a successful condition is met with the resolve() definition.
    Also, an action to take when a failure condition is met with the reject() definition.
    promise1.then( (message) => {
        // Execute code inside this on resolve().
    }).catch( (message) => {
        // Execute code inside this on reject().
    });

    Example:jsfiddle links: reject() example and resolve() example )
    In below code, change isCallResolve to true or false to see the action for resolve() and reject() calls.
    // First part: Create the Promise and define conditions for success or failure.
    let promise1 = new Promise( (resolve, reject) => {
        let isCallResolve = false; 
    
        if (isCallResolve) {
            resolve('Promise is successful and resolve method is called that is code inside then() !');
        }
    
        if (!isCallResolve) {
            reject('Promise failed and reject method is called that is code inside catch() !');
        }
    });
    
    
    // Second part: Define the actions to take when the conditions are fulfilled as success or failure.
    promise1.then( (message) => {
        // then() method is the definition for resolve() callback method.
        // Execute code inside here if the promise is resolved i.e. is successful.
        console.log(message);
    }).catch( (message) => {
        // catch() method is the definition for reject() callback method.
        // Execute code inside here if the promise is is rejected that is not successful.
        console.log(message);
    });


Promise properties:

  • The resulting promise object has two internal properties:
    • state: Set to ‘pending’ during initialization and then changes to either ‘fulfilled’ or ‘rejected’ after the execution.
    • result: value. Initially set to undefined.
  • After execution, it calls either resolve() or reject() based on success or failure.
    • resolve(value): Indicates that the execution has finished successfully.
      • state: set to ‘fulfilled’.
      • result: set to the value.
    • reject(error): Indicates that an error has occurred.
      • state: set to ‘rejected’.
      • result: set to an error.
  • See the below screen for a different state of promise before and after execution.


Promise.finally():

  • finally() always runs when the promise finishes its execution no matter it’s a resolve or reject.
  • It is useful for cases where we want to execute some code anyhow after resolve or reject. For example, variable cleanup, stop loader after async calls, close popups etc.
    Example: jsfiddle link: promise.finally() example )
    new Promise(function(resolve, reject) {
        setTimeout(() => resolve(5), 1000);
    }).then( (result) => {
        alert('Resolve executed');
    }).catch( (result) => {
        alert('Reject executed');
    }).finally( (result) => {
        alert('Finally will execute no matter it is a resolve or reject');
    });


Promises chaining:

  • Multiple promises can be chained together with .then() one after another and pass the result of the previous promise to the next Promise, and so on.
  • It is useful to handle multiple async calls to execute one task after another by using the result of the previous async call.
  • Below example shows that the next promise is called only after the success of previous promise and uses the result from the previous promise.
    Example: jsfiddle link: Promise chaining example )
    new Promise(function(resolve, reject) {
        setTimeout(() => resolve(5), 1000);
    }).then( (result) => { // Promise #1
        alert(result); // 5
        return result * 3;
    }).then( (result) => { // Promise #2
        alert(result); // 15
        return result * 4;
    }).then( (result) => { // Promise #3
        alert(result); // 60
        return result * 2;
    });


Promise.all():

  • It evaluates all Promises and executes .then() only after all the Promises within the array list finishes is execution.
    Example: jsfiddle link: promise.all() example )
    It executes the .then() method only after the successful execution of all other three promises.
    promise3 has 3 seconds delay so it will wait for promise3 to finish its execution.
    let isCallResolve = true;
    
    let promise1 = new Promise((resolve, reject) => {
        if (isCallResolve) {
            resolve('promise1 successfully executed.');
        }
    });
    
    let promise2 = new Promise((resolve, reject) => {
        if (isCallResolve) {
            resolve('promise2 successfully executed.');
        }
    });
    
    let promise3 = new Promise((resolve, reject) => {
        setTimeout(()=> {
            resolve('promise3 successfully executed.');
        }, 3000);
    });
    
    Promise.all([promise1, promise2, promise3]).then( (message) => {
        console.log(message);
    });


Promise.race():

  • It doesn’t wait for all the Promises and executes as soon as anyone promise from the array list completes its execution.
    Example: jsfiddle link: promise.race() example )
    It will output result from promise1 or promise2 whichever executes first.
    The result from promise3 will not output as there is a delay of 2 seconds for its execution so it will not wait for promise3 to complete its execution.
    let isCallResolve = true;
    
    let promise1 = new Promise((resolve, reject) => {
        if (isCallResolve) {
            resolve('promise1 successfully executed.');
        }
    });
    
    let promise2 = new Promise((resolve, reject) => {
        if (isCallResolve) {
            resolve('promise1 successfully executed.');
        }
    });
    
    let promise3 = new Promise((resolve, reject) => {
        setTimeout(()=> {
            resolve('promise3 successfully executed.');
        }, 2000);
    });
    
    Promise.race([promise1, promise2, promise3]).then( (message) => {
        console.log(message);
    });


Real world implementation to see Promise in action:

  • Promise.race():
    Example
    : ( jsfiddle link: promise.race() real-world example )
    Here we are calling 2 open APIs, jsonplaceholder and GitHub.
    With race() method, the promise which finishes its execution first will return the output and will not wait for any other promises to complete its execution provided in the array.
    let promise1 = new Promise((resolve, reject) => {
        let request = new XMLHttpRequest();
        request.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
        request.send();
    
        request.onreadystatechange = () => {
            if (request.readyState === 4) {
                console.log('jsonplaceholder API, request status: ' + request.status, ', readyState: ' + request.readyState);
                resolve('jsonplaceholder API responded faster!');
            }
        }
    });
    
    let promise2 = new Promise((resolve, reject) => {
        let request = new XMLHttpRequest();
        request.open('GET', 'https://api.github.com/users/mojombo/repos');
        request.send();
    
        request.onreadystatechange = () => {
            if (request.readyState === 4) {
                console.log('GitHub API, request status: ' + request.status, ', readyState: ' + request.readyState);
                resolve('GITHUB API responded faster!');
            }
        }
    });
    
    Promise.race([promise1, promise2]).then((message) => {
        console.log(message);
    });
  • Promise.all():
    Example:jsfiddle link: promise.all() real-world example )
    Here we are calling 2 open APIs, jsonplaceholder and GitHub.
    With all() method, it will wait for both promises to finish its execution and output from both will be returned.
    let promise1 = new Promise((resolve, reject) => {
        let request = new XMLHttpRequest();
        request.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
        request.send();
    
        request.onreadystatechange = () => {
            if (request.readyState === 4) {
                console.log('jsonplaceholder API, request status: ' + request.status, ', readyState: ' + request.readyState);
                resolve('jsonplaceholder API responded!');
            }
        }
    });
    
    let promise2 = new Promise((resolve, reject) => {
        let request = new XMLHttpRequest();
        request.open('GET', 'https://api.github.com/users/mojombo/repos');
        request.send();
    
        request.onreadystatechange = () => {
            if (request.readyState === 4) {
                console.log('GitHub API, request status: ' + request.status, ', readyState: ' + request.readyState);
                resolve('GITHUB API responded!');
            }
        }
    });
    
    Promise.all([promise1, promise2]).then((message) => {
        console.log(message);
    });

I hope with this post, you will get some understanding of what is Promise and how it works in JavaScript.
Happy coding!!!

The post JavaScript promises and how it works. appeared first on Technolize Your Future.

]]>
https://techtalkbook.com/javascript-promises-and-how-it-works/feed/ 0 1280
Just Start – The Motivation https://techtalkbook.com/just-start/ https://techtalkbook.com/just-start/#respond Sun, 24 Feb 2019 08:34:24 +0000 http://techtalkbook.wordpress.com/?p=54 Pay attention to the things first which are the most important. Distance yourself from negativity. Stop only when DONE not when TIRED. Wake up with determination and go to bed with satisfaction. Do it Now else ‘LATER‘ with become ‘NEVER‘.... Continue Reading →

The post Just Start – The Motivation appeared first on Technolize Your Future.

]]>
  • Pay attention to the things first which are the most important.
  • Distance yourself from negativity.
  • Stop only when DONE not when TIRED.
  • Wake up with determination and go to bed with satisfaction.
  • Do it Now else ‘LATER‘ with becomeNEVER‘.
  • Stop wishing and start doing.
  • Start where you are, Use what you have, Do what you can.
  • Don’t live in your comfort zones thinking a lot can go wrong.
    You don’t have to be perfect to start anything.
  • You will only fail if you stop trying or do not try at all.
  • You do not know what you can achieve until you try.
  • Take the risk and learn from it.
  • Change your life today, don’t gamble on the future. Act now, without delay.
  • The only person stopping you from achieving something is the person you see when you look in the mirror.
  • The only thing stopping you from doing anything is you and your fear.
    Remove fear and then you can do anything.
  • When you feel like something is too much for you to handle, keep in mind that it will soon pass.
  • Be a warrior, not a worrier.
  • You’re afraid you have no talent. You’re afraid your best work is behind you. Don’t be afraid of being rejected or criticized.
  • Do not compare with others and do not have an expectation.
    Just keep doing and be better than you are now.
  • You don’t have to seek perfection when you are ready to create your life’s work.
    You just need to get started.
  • You don’t create your life first and then leave it.
    You create it by leaving it, not agonizing about it.
  • Motivation? its right inside you, not anywhere outside.
  • Imagine the worst situation that will happen if you don’t do anything productive.
    For example, let’s say you’re at a job you hate and dream of running your own business.
    You get home tired from work. But instead of researching more into starting a venture,
    it’s easier to watch TV and waste time.  Think of what will happen in 10 years.
    You’ll probably be stuck at the same old job, wondering what could have been if you had taken action earlier.
  • Sometimes you have to let go of things that are no longer serving you.
    If you’re holding on to something—like a goal—that is no longer in reach, it’s time to walk away.
  • Whenever you face a challenge, remember that’s part of the process and that on the other side of struggle usually lies the strength you need to level up.
  • Don’t be afraid to take one step back today to take two steps forward tomorrow.
  • Rather than focusing on the present and going one step at a time, we focus on too many things in the future and get worried.
    We also get worried by looking at our past and also looking at our peer group.
    We even make our own lives miserable by asking others about us.
    We are a funny race of people.
    Staying focused on fewer things ensures that we are inching towards our goal, consistently.
  • Everyone is running their own RACE, in their own TIME, if it’s not happening now…it’s not the right time.
    Don’t be discouraged if things are not working out right now.
    God is working on it behind the scenes.
    It may not come when you want, but trust that it will be right on time!
  • The post Just Start – The Motivation appeared first on Technolize Your Future.

    ]]>
    https://techtalkbook.com/just-start/feed/ 0 54
    How to secure your bank account and cards from fraud transactions. https://techtalkbook.com/secure-bank-account-and-cards-from-fraud-transactions/ https://techtalkbook.com/secure-bank-account-and-cards-from-fraud-transactions/#comments Sat, 26 Jan 2019 12:53:21 +0000 http://techtalkbook.com/?p=1072 Ever got into a trap of fraudulent transactions from your bank account? Do you have faith and believe in yourself and on the service provider that you will get OTP/verification before a transaction can take place from your bank account or... Continue Reading →

    The post How to secure your bank account and cards from fraud transactions. appeared first on Technolize Your Future.

    ]]>
    Ever got into a trap of fraudulent transactions from your bank account?

    Do you have faith and believe in yourself and on the service provider that you will get OTP/verification before a transaction can take place from your bank account or payment apps (which you keep loaded with lots of money)?

    If yes then you should give it a second thought.

    Because one day you might get an SMS/Email mentioning a transaction successful for XXXXXX amount, even without any OTP/calls/verification, even if you did not initiate that transaction and you keep wondering how it happened and then you have no idea what to do?

    So let’s see different ways with which you might compromise your bank/card details unknowingly and then to see what action you can take at best in case you get into this trap.

    1. Do not show your cards to anyone:
      Don’t show your card to someone you can’t trust.
      Because that person can take a picture or memorize your card details to use it for fraud transaction.
    2. Do not take out your card or use your card details in public places:
      Don’t use your card to load money in your online payment apps in stores/public places or for payments in any stores.
      Better to have a very minimum use of that. (Remember you are under CCTV surveillance).
    3. Scratch/Remove your card number and CVV number:
      As mentioned in above 1st and 2nd points, It’s not possible to avoid using the card every time, so better you scratch your card number’s few digits or at least the CVV number.
      Note: Remember those numbers or write it somewhere in an encoded/patterned format so that you don’t lose that or else the card will be useless to you). You can scratch or color your cvv number like below so that no one can see it.
       
    4. Do not save card detail on online ordering/shopping apps:
      Many Apps are now very famous to be commonly used by almost everyone for online payments/recharges.
      While making payment,  It either gives you an option whether you want to save your card detail for faster future payments or the app will automatically save that information by default.
      And you are so busy in today’s fast-moving world that you do allow the apps to save card details because you want to make future payment process easy and faster without providing that information again and again.

      But there are apps which do not allow you to even delete those card information from their App’s setting.

      https://twitter.com/sagrawal003/status/1062311918310805509https://twitter.com/sagrawal003/status/1088772100956082178

      If your card information is saved in online payment apps and even if the app is 100% secure, you never know when and where that app or your detail will get compromised in future and then boom. It’s you who will lose the hard earned money which you will be more concerned about.

      So while making any payments, better to not give permission to save your card details in your payment apps.

    5. Install only trusted/official apps on the device:
      Nowadays there are many apps are available on app store and we just download it based on rating or whatever shows on the top of the list.You should make sure to install only those apps which are created/uploaded by the company or authorized organizations.
    6. Do not give device data access permission to all apps:
      Many apps on our device ask for gallery, media, contacts, SMS permission but do not give access to all those data blindly.
      check if that app really needs access to the data it is asking permission for.

      From my personal experience, I had installed one app which was related to gallery/photos but that app was asking permission to access contact and SMS before I can use the app. Why on earth that photo app needs access to my phone contacts and SMS. and even if it needs permission, then why it is mandatory by the app without which I can not use the app.

    7. Do not save any private details on online storage:
      If you are using online storages to store your card details, passwords, personal private data for easier access from anywhere then better stop doing that because you never know how and when someone will hack data and use it. (or store in some encoded/pattern format if you have no other choice)

      Just a simple example: You log in to your Gmail account on any public device or anywhere else except your device and then forgot to log out from there. Then whoever else has access to that device can get all your data if you have your personal data stored in google drive.

    8. Do not share bank/card detail to anyone on phone calls:
      It’s very common now to get a call from someone claiming representative of a bank or from a service provider you are using their service and then you are being asked to share card details to reactive account/card or your service.

      No authorized/valid service provider will ever ask you your bank card detail or account details over phone/email/SMS.
      If that happens to you, just drop the call because that is a fake call through which one will get your data and use it.

    9. Do not blindly use any keyboard on your device:
      There are many fancy keyboards available on the app store which we download and use for advance fancy features.

      But be careful from using those keyboards as those may collect all the text that you type in on that keyboard, especially keyboard which are not authentic and authorized one and hacker put those for hacking your data.

      Even “Gboard” keyboard of Google gives you a warning when you enable it saying that it may be able to collect all text including your personal data such as passwords and credit card numbers. See the screenshot below.

    10. Careful from any links from social media or mobile chatting apps:
      Do not open any links from email/chatting groups/SMS which claims to give you offers by asking you to enter bank account/card details.
      There can be cases where those links are fake and hacker wants to get your data on your device once you open the link.

      Hacker can hack your data by running some script on their website link which you opened on your mobile or redirect you to a bank website which you use and ask to enter card details to claim the offers or something.There are many ways to hack your data so you better open only those links which start with https or you think is a valid website link.

    11. Enable Biometric Locking for your Aadhaar detail:
      Now everyone has Aadhaar card and everything about you and your bank detail are linked with your Aadhaar number.
      And it’s now possible to transfer the amount from your bank account to any bank account if someone has access to your fingerprint and details.

      https://www.moneycontrol.com/news/technology/auto/this-week-in-auto-tata-motors-launches-harrier-maruti-unveils-new-wagon-r-3438861.html

      https://economictimes.indiatimes.com/news/politics-and-nation/otp-authentication-better-than-biometric-for-aadhaar-verification-delhi-high-court/articleshow/66465317.cms.

      So if you do not use your fingerprints for any Biometric operations in your day-to-day life, better to lock that from Aadhaar website. https://resident.uidai.gov.in/biometric-lock.

      It provides an option to lock and unlock your Biometric permanently or temporarily for 10-15 minutes.

     

    Of course, there are many many other ways of hacking your data, but above-mentioned points are the minimum security level you should remember and apply it.

    With these few tips, you can do whatever you can to make your data secure but even then you might become a victim of fraudulent transactions if your day is a bad day.

    So if you get into a trap of fraudulent transactions then below are the minimum things you should do at the earliest to report this case to your respective bank account.

    1. Call your bank’s customer care number immediately, report about the incident, ask them to block your card and freeze account temporarily if that is necessary.

      Or login to internet banking, block your card from there. [Call customer care to report case anyway even if you do this]
      (Better to remember where these options are present in your I-banking so that you can use it immediately when needed)

    2. Submit documents to the bank within 3 days of the incident:
      1. FIR copy if the transaction amount is more than 20,000/- (check the amount limit in your respective bank’s website)
      2. Customer Dispute Form with data filled up. (Every bank has ‘Dispute form’ so download that from the internet or ask your bank to give one form)
      3. Incident letter. (A letter to bank mentioning detailed information of the incident like when and how it happened and what all action you took so far from your side)
      4. Can include scan copy of the transaction SMS/statement for reference.
    3. Your bank will then report this to their fraudulent handling department and will give you acknowledgment receipt.
      Acknowledgment receipt can be a copy of your submitted dispute form with bank stamp and signature with acceptance note.
    4. Also, send all the documents submitted and details via email to respective RBI ombudsman of the city where your bank account branch is present (where bank account opened or transferred).
      https://www.rbi.org.in/CommonPerson/english/scripts/againstbankabo.aspx
    5. Once the above processes are completed, all you will need to do is to wait for at least a month or two (max 90 days) before you get status from your bank about the report.

      You, better keep asking the bank, customer support, RBI’s ombudsman about the status every week, can also follow up with them on their social media page.

    6. It depends on the bank and RBI to take appropriate action and decide whether you will be getting your money back or not.

     

    I hope the above post will give you some idea on how you can secure your bank/card information as much as possible from your end.

    Happy Securing your Data !!!

    The post How to secure your bank account and cards from fraud transactions. appeared first on Technolize Your Future.

    ]]>
    https://techtalkbook.com/secure-bank-account-and-cards-from-fraud-transactions/feed/ 2 1072
    Devtools Code Snippets and its benefit https://techtalkbook.com/devtools-snippets-and-its-benefit/ https://techtalkbook.com/devtools-snippets-and-its-benefit/#respond Sun, 20 Jan 2019 14:45:03 +0000 http://techtalkbook.com/?p=1031 Snippet: Snippets are small scripting feature that allows you to execute within the sources panel of Chrome Developer tools. It executes from the context of the currently opened page. Can access and run them from any page. Firefox has scratchpad editor... Continue Reading →

    The post Devtools Code Snippets and its benefit appeared first on Technolize Your Future.

    ]]>
  • Snippet:

    • Snippets are small scripting feature that allows you to execute within the sources panel of Chrome Developer tools.
    • It executes from the context of the currently opened page.
    • Can access and run them from any page.
    • Firefox has scratchpad editor and Chrome has snippets feature for this.
  • How to run snippet: (There are three ways to run your snippet)
    • Right-click on the snippet filename from the left side snippet list and select Run.
    • Click the Run button. 
    • Press Command + Enter (For Mac) or Ctrl + Enter (For Windows, Linux).
  • Why use snippets:
    • If you find yourself using some codes repeatedly on multiple pages then consider saving those scripts as snippets.
    • An alternative to bookmarklet:
      Problem with bookmarklets is that you need to use a generator to convert a js file into a bookmarklet, pain to make changes to a long single line of JavaScript inside of your bookmark manager, create and share those, show it on bookmarks bar on UI, run it and sometimes even open the dev tools to see if it really worked.But Snippets, on the other hand, are a much better way to handle this problem.
    • An alternative to console command:
      When using console command, sometimes we loose our unexecuted codes while using arrow up/down key for code correction because if the arrow is on the top of the code then pressing it again mistakenly displays the previously executed code and we end up losing our current unexecuted long multiline codes.But with Snippets, we can avoid above issue and also save the code as a file inside dev tool which we can use later when required. We can also save it externally to a known place on the disk as a backup to use it later.
    • Run part of the code:
      You can select portion of your code inside Snippets and run that particular portion of the code instead of executing all codes written in there.
    •  Breakpoint for debugging:
      It allows setting breakpoints in the codes for debugging on execution similarly the way you debug all other loaded js codes in your project.
  • So this is some basic cum advance detail about Snippet feature of developer toolbar and its benefit. I hope after reading this, it will help you write better and faster code during development.

    Happy coding!!!

    The post Devtools Code Snippets and its benefit appeared first on Technolize Your Future.

    ]]>
    https://techtalkbook.com/devtools-snippets-and-its-benefit/feed/ 0 1031
    Different ways to delete Array elements in JavaScript https://techtalkbook.com/ways-to-remove-array-elements-in-javascript/ https://techtalkbook.com/ways-to-remove-array-elements-in-javascript/#respond Sat, 19 Jan 2019 14:43:40 +0000 http://techtalkbook.com/?p=999 Global object Array itself does not have any remove or delete method. But there are many other ways to remove array elements in JavaScript. Below are the different ways to remove array elements in JavaScript. From the start of an... Continue Reading →

    The post Different ways to delete Array elements in JavaScript appeared first on Technolize Your Future.

    ]]>
    Global object Array itself does not have any remove or delete method. But there are many other ways to remove array elements in JavaScript.

    Below are the different ways to remove array elements in JavaScript.

    1. From the start of an array using shift() method.
    2. From the end of an array by setting array length set or pop() method.
    3. Removing a range of elements from anywhere using splice() method.
    4. Removing elements by value using splice() and filter() method.
    5. By using Lodash library. (This requires loadash library to be included in your script: https://lodash.com)
    6. Using delete operator.

    Let’s see those different ways one by one:

    1. Removing elements from the start:
      • Using shift() method: [Removes only one element]
        It removes the first element of an array and updates array length and element indexes.
        It also returns the removed element on execution.
        var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
        var shiftedElement = testArray.shift();
        
        // Removes the first element from the array.
        console.log(testArray); // ["B", "C", "D", "E", "F", "G", "H", "I", "J"]
        
        // Sets new length for the Array.
        console.log(testArray.length); // 9
        
        // Returns the removed element.
        console.log(shiftedElement); // A
        
        // Confirms that elements has new indexes in the Array.
        console.log(testArray[3]); // E
    2. Removing elements from the end:
      • Setting array length: [Removes single or multiple elements]
        Set array length property to the desired length (less than actual array length) and rest of the elements will be removed from the end of an array.
        This way, it will remove elements with an index greater than equal to the desired length.
        var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
        testArray.length = 6;
        
        // Removes rest of the elements except first 6 elements.
        console.log(testArray); // ["A", "B", "C", "D", "E", "F"]
        
        // Sets new length for the Array.
        console.log(testArray.length); // 6
        
        // Confirms that elements has new indexes in the Array.
        console.log(testArray[4]); // E
      • Using pop() method: [Removes only one element]
        It removes the last element of an array and updates array length and element indexes.
        It also returns the removed element on execution.
        var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
        var popedElement = testArray.pop();
        
        // Removes the last element "J" from the array.
        console.log(testArray); // ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
        
        // Sets new length for the Array.
        console.log(testArray.length); // 9
        
        // Returns the removed element.
        console.log(popedElement); // J
        
        // Confirms that elements has new indexes in the Array.
        console.log(testArray[2]); // C
    3. Removing a range of elements from anywhere:
      • Using splice() method: [Removes any number of elements from anywhere in an array]
        • It removes any number of elements from anywhere in an array and updates array length and element indexes.
        • It also returns all removed elements as a new array.
        • It requires arguments to be passed (zero-based index).
          Only the 1st argument is mandatory which specifies the position from where to add/remove elements.
          The 2nd argument specifies the number of elements to be removed.
          The 3rd  argument and rest of the arguments after that specifies new elements to be added to the array.
          // Remove elements from the middle.
          var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
          var removedElement = testArray.splice(2, 1);
          
          // Removes 1 element from 2nd index in the array.
          console.log(testArray); // ["A", "B", "D", "E", "F", "G", "H", "I", "J"]
          
          // Sets new length for the Array.
          console.log(testArray.length); // 9
          
          // Returns the removed element.
          console.log(removedElement); // ["C"]
          
          // Confirms that elements has new indexes in the Array.
          console.log(testArray[4]); // F

          // Remove elements from the start.
          var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
          var removedElement = testArray.splice(0, 2);
          
          // Removes the first element from the array.
          console.log(testArray); // ["C", "D", "E", "F", "G", "H", "I", "J"]
          
          // Sets new length for the Array.
          console.log(testArray.length); // 8
          
          // Returns the removed element.
          console.log(removedElement); // ["A", "B"]
          
          // Confirms that elements has new indexes in the Array.
          console.log(testArray[4]); // G

          // Remove elements from the end.
          var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
          var removedElement = testArray.splice(-3);
          
          // Removes 1 element from 2nd index in the array.
          console.log(testArray); // ["A", "B", "C", "D", "E", "F", "G"]
          
          // Sets new length for the Array.
          console.log(testArray.length); // 7
          
          // Returns the removed elements.
          console.log(removedElement); // ["H", "I", "J"]
          
          // Confirms that elements has new indexes in the Array.
          console.log(testArray[4]); // E
    4. Removing elements by value:
      • Using splice() method:
        In this approach, you can loop through the array to check if the element you want to remove matches with the element currently being looped and then remove it.
        var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
        var splicedElement;
        
        for( var i = 0; i &lt; testArray.length-1; i++) { 
           if ( testArray[i] === "D") {
             splicedElement = testArray.splice(i, 1);
           }
        }
        
        // Removes element "D" from the array.
        console.log(testArray); // ["A", "B", "C", "D", "E", "F", "G"]
        
        // Sets new length for the Array.
        console.log(testArray.length); // 9
        
        // Returns the removed element.
        console.log(splicedElement); // ["D"]
        
        // Confirms that elements has new indexes in the Array.
        console.log(testArray[4]); // F
      • Using filter() method:
        This does not affect the original array and will return a completely new array with removed elements.
        so basically, it will filter elements which are matched from the original array.
        var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
        
        var filteredElements = testArray.filter(function(value, index, testArray) {
            return value === "C";
        
        });
        
        // Original array remains same as before.
        console.log(testArray); // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
        
        // Original array length remains the same.
        console.log(testArray.length); // 10
        
        // Returns element "C" in a new array.
        console.log(filteredElements); // ["C"]
        
        // Confrims that element indexes are same in original array.
        console.log(testArray[4]); // E

        var testArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        
        var filteredElements = testArray.filter(function(value, index, testArray) {
            return value &lt; 7;
        
        });
        
        // Original array remains same as before.
        console.log(testArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        
        // Original array length remains the same.
        console.log(testArray.length); // 10
        
        // Returns all elements less than 7 in a new array.
        console.log(filteredElements); // [1, 2, 3, 4, 5, 6]
        
        // Confirms that element indexes are same in original array.
        console.log(testArray[4]); // 5
    5. Using Lodash library: (This requires loadash library to be included in your script: https://lodash.com)
      Libraries are a sometimes better way to solve complex problems.
      Lodash provides such rich set of array manipulation.
      It works somewhat similar to the array filter() method but it also updates the original array by removing elements and returning those elements as a new array.
      var testArray = ["A", 1, "B", 2, "C", 3, "D", 4, "E", 5];
      
      var numberedArray = _.remove(testArray, function (element) {
          // Remove all numbers.
          return typeof element === 'number';
      });
      
      // Remove numbers from the original array.
      console.log(testArray); // ["A", "B", "C", "D", "E"];
      
      // Original array length remains the same.
      console.log(testArray.length); // 5
      
      // Returns numbered elements in a new array.
      console.log(numberedArray); // [1, 2, 3, 4, 5]
      
      // Confirms that element indexes are same in original array.
      console.log(testArray[3]); // D
    6. Using delete operator:
      So far we have seen many ways which delete the elements, update array length and indexes of the elements.
      But delete operator just removes the reference to the element so that it becomes undefined.
      Memory is freed when there are no more references to a value so delete operator frees the memory instead of deleting the element.
      var testArray = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
      
      delete testArray[3];
      
      // Element at 3rd index is set to undefined in original array. It shows as empty here because there is no value for 3rd index.
      console.log(testArray); // ["A", "B", "C", empty, "E", "F", "G", "H", "I", "J"]
      
      // Original array length remains the same.
      console.log(testArray.length); // 10
      
      // Confirms that element at 3rd index is set to undefined.
      console.log(testArray[3]); // undefined

     

    So these are all different ways to remove array elements in JavaScript.
    I hope it will help you write better array manipulation codes as and when required based on the problems to be solved.

    Happy coding!!!

    The post Different ways to delete Array elements in JavaScript appeared first on Technolize Your Future.

    ]]>
    https://techtalkbook.com/ways-to-remove-array-elements-in-javascript/feed/ 0 999
    Difference Between Call() and Apply() in JavaScript https://techtalkbook.com/difference-between-call-and-apply-in-javascript/ https://techtalkbook.com/difference-between-call-and-apply-in-javascript/#respond Mon, 06 Aug 2018 14:52:20 +0000 http://techtalkbook.com/?p=965 A useful mnemonic for Call() and Apply() is: a in apply() stands for array of arguments. c in  call() stands for comma separated arguments. The difference between apply() and call() is just the way arguments are passed: apply() : Invoke a function with arguments passed as an... Continue Reading →

    The post Difference Between Call() and Apply() in JavaScript appeared first on Technolize Your Future.

    ]]>
  • A useful mnemonic for Call() and Apply() is:
    • a in apply() stands for array of arguments.
    • c in  call() stands for comma separated arguments.
  • The difference between apply() and call() is just the way arguments are passed:
    • apply() : Invoke a function with arguments passed as an array.
      function.apply(thisObj, arrayOfArguments);
    • call() : Invoke a function with arguments passed as comma-separated.
      function.call(thisObj, arg1, arg2, ...);
  • Now let’s take a look at the ways to use them: (Below is the code snippet we will use for understanding)
    var person1 = {name: 'person1', age: 20, gender: 'Male'};
    var person2 = {name: 'person2', age: 19, gender: 'Female'};
    
    var greetHi = function() {
        alert('Hi, ' + this.name);
    };
    
    var greetBye = function() {
        alert('Bye, ' + this.name);
    };

    Here, calling just greetHi();or greetBye(); will give errors or unexpected results because both methods rely on their context for this.name, and calling these methods without explicit scope will just run them within the scope of their current window.

    So to run them in the scope of an Object, we need to call these methods like below and that’s how call() and apply() method are used.

    // Using call()
    greetHi.call(person1);
    greetBye.call(person2);
    
    // Using apply()
    greetHi.apply(person1);
    greetBye.apply(person2);

    Both the above way of calling the method using call() and apply() do the exact same thing and they get executed in the context, or scope, of the first argument passed which is an Object.

  • Now we will see how to use these with arguments passed and this is where we will know when to use call() and apply():
    Lets combine greetHi() and greetBye() to a single method as just greet() where we will pass ‘Hi’, ‘Bye’ as an argument.
    and also create another method where it will need multiple parameters to be passed.

    // greetHi() and greetBye() combined to greet().
    var greet = function(greet) {
        alert(greet + ', ' + this.name);
    };
    
    // New method with multiple arguments.
    var setPersonInfo = function(name, age, gender) {
        this.name = name; this.age = age; this.size = size;
    };
    
    // Call greet method using call() with single argument passed.
    greet.call(person1, 'Hi');
    greet.call(person2, 'Bye');
    
    //Now to call 'getPersonInfo' method using call(), we will have to pass all arguments as a comma separated like:
    setPersonInfo.call(person1, 'John', 25, 'Male');

    This is a no big deal but limitation of call() will become apparent when you do not know the number of arguments to pass to a method like a dispatcher which will just dispatch your arguments/message to intended methods as below:

    var dispatch = function(person, method, args) {
        method.apply(person, args);
    };
    dispatch(person1, greet, ['Hi']);
    dispatch(person2, setPersonInfo, ['John', 25, 'Male']);

    So here you can see that we are passing an array of arguments which are different in both of the above call of dispatch() method and then apply() is called on the method with the argument passed whose length varies in each of the methods.

  • That’s the difference between call and apply. Both can be called on functions, which they run in the context of the first argument.

    So If you know number of arguments to pass, you should use call() and If you don’t know, or arguments are already in an array, should use apply().

    I hope it gives you some clarity on call() and apply().

    References:

    • https://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply
    • http://hangar.runway7.net/javascript/difference-call-apply
    • http://lucybain.com/blog/2014/call-vs-apply/

    Happy coding!!

    The post Difference Between Call() and Apply() in JavaScript appeared first on Technolize Your Future.

    ]]>
    https://techtalkbook.com/difference-between-call-and-apply-in-javascript/feed/ 0 965
    Export data from the Chrome browser console https://techtalkbook.com/export-data-from-the-chrome-browser-console/ https://techtalkbook.com/export-data-from-the-chrome-browser-console/#respond Wed, 01 Aug 2018 05:48:54 +0000 http://techtalkbook.com/?p=928 Ever wondered how to save any data or a large object from Chrome browser console while debugging? Let’s talk about it and get the hands on that. It’s pretty easy to do it with a few clicks and a simple... Continue Reading →

    The post Export data from the Chrome browser console appeared first on Technolize Your Future.

    ]]>
    Ever wondered how to save any data or a large object from Chrome browser console while debugging?
    Let’s talk about it and get the hands on that.

    It’s pretty easy to do it with a few clicks and a simple JavaScript code snippet in your browser console.
    Note: In Firefox, right click on object/data in the console, it shows an option to copy and you can just use it. 🙂

    Steps for configuration setup:

    1. Open browser console and go to Sources -> Snippets in the console.
    2. Either right-click on the left side panel to make a new file or click on ‘New snippet‘ option and save the file as any name with a .js extension for example saveToConsole.js.
    3. Paste below JavaScript code into the snippet file saveToConsole.js and save it in the console with Ctrl + s.

      (function(console) {
          console.save = function(data, filename) {
      
              if (!data) {
                  console.error('Console.save: No data');
                  return;
              }
      
              if (!filename) {
                  filename = 'console.json';
              }
      
              if (typeof data === 'object') {
                  data = JSON.stringify(data, undefined, 4);
              }
      
              var blob = new Blob([data], {type: 'text/json'}),
                  e    = document.createEvent('MouseEvents'),
                  a    = document.createElement('a');
      
              a.download = filename;
              a.href = window.URL.createObjectURL(blob);
              a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':');
              e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
              a.dispatchEvent(e);
          }
      })(console);
    4. Right click on the saveToConsole.js file and run the snippet.

    That’s it for the simple configuration setup and now you can just call console.save() to download any data/object from your chrome browser console and save to a file.
    Like if you have an object named Reports which can be printed in the consoleyou can run console.save(Reports) in your console and save it into a file.

    Happy debugging!

    Reference(s):

    • https://coderwall.com/p/prhwzg/add-console-save-to-chrome
    • http://bgrins.github.io/devtools-snippets/#console-save

    The post Export data from the Chrome browser console appeared first on Technolize Your Future.

    ]]>
    https://techtalkbook.com/export-data-from-the-chrome-browser-console/feed/ 0 928