Friday, 31 January 2020

Javascript : 'this' keyword inside function and arrow function



This keyword inside normal function and arrow function refers to the global object but if  function is inside of object then within normal function this refers current object and if it's arrow function then 'this' refers to the global object.

var val=500//global variable

var obj={

    val:909,//local variable

    func1:function(){
        console.log(this.val); //909
       // console.log(this); //here this refres obj
    },
    func2:()=>{
        console.log(this.val);//500
        //console.log(this);// here this refers Global(Window object)
     }
}
console.log(obj.func1());
console.log(obj.func2());

Monday, 20 January 2020

Javascript : Destructuring


With the help of destructuring we can unpack values from Arrays and objects into variables directly.
It's vary common to initialize a variable form object property or array like:

let test1=arr[0], test2=arr[1] or 
let name=customer.name,etc.
Below examples will be helpful to understand Destructing in Javascript.

//array destructuring 

let arr = [90300930200];
[jk= arr;
console.log(j + " " + k);

// ... (rest operator)

[lm...p= arr;
console.log(l + " " + m);
console.log(typeof p + " " + p);

//************ object destructring ************:
//Example 1:
let { ab } = { a: 10b: 30c: 90 };
console.log(a + " " + b);

//Exaple 2: object function destrucring
let obj = {
    write: function () {
        console.log("hello");
    }
}
let { write } = obj
write();

//Destructuring with function argument
// Normally we work with object like below
let obj2 = {
    firstname: "nirnajan"
}

function WriteToConsole(val) {
    console.log(val);
}
WriteToConsole(obj2.firstname);//rsult:niranjan


//Destructuring : instead of passing object we can extract param directly
function WriteToConsole2({ firstname }) {
    console.log(firstname);
}
WriteToConsole2(obj2);


//Some complex (nested object)destructuring examples
let customer = {

    firstName: "abc",
    lastName: "bcd",
    Order: [{
        orderDate: '12/12/2020',
        orderId: 1
    }],

}

// To destructing from array within object
let { firstNameOrder: [{ orderId }] } = customer;
console.log(firstName + "****" + orderId);


//another example:
var user = {
    id: 42,
    displayName: 'jdoe',
    fullName: {
        firstName: 'John',
        lastName: 'Doe'
    }
};
let { displayNamefullName: { firstNamename } } = user;

//here firstName:name means renaming 'firstName to name' 
// i.e displayName=user.dispalyName
// name=fullName.firstName
console.log(displayNamename);

Wednesday, 15 January 2020

JavaScript : Hoisting


In Java script, variables and functions are hoisted, what it means, we will try to understand it by examples:

if we are using variables without declaration like:


console.log(a); //ex 1 ; error : a is not defined

We will get error " ReferenceError : a is not defined.." so we will modify code to resolve error like :


var name;        // ex 2
console.log(name);

Now, we will get output "undefined" i.e. you have declared a variable but not defined it. In sort,    java script engine tells you,  there is a variable named 'name' and it's value is undefined. ['undefined' is a data type in java script.] what if we will write code like:

console.log(k);
var k="hello";

what would be the output of above code, will it throw error? or k = 'undefined' or k='hello',          based on ex1 we may say, code will throw error. but it's not correct, because of Hoisting.

Java script moves all the variable's and function's declaration on the top of scope before execution.
so above code will be like that:

var k;
console.log(k);
k="hello";
as a result of hoisting, program will print 'undefined' as we saw in ex2;

Hoisting is also applicable for function definitions. for example :
we can use function before it's definition like :

func1();
function func1(){
    console.log("from func1");
}

but it's not application in-case of function expression ( because their we are declaring a variable of type Function) below code will throw an error

func2(); //Error: func2 is not a function
var func2=function(){
    console.log("from func2");
};

to run above code we need function expression declaration before it's use
var func3=function(){
    console.log("from func3");
};
func3(); 

NOTE :
console.log(b); // veriable declare with 'let' are not hoisted.
let b=10;

Thursday, 9 January 2020

JavaScript Gocha Part -1


// Arithmetic Operations 

console.log(14 + "" );// "14"
console.log("43"+2);//"432"
console.log("43"+"2"//"432"
console.log("43"+true)//"43true"
console.log(1+true);//2
//******* Gocha with Minus' ********** */
console.log("43"-2);//41  /
console.log("43"-"2");//41
console.log("43"-true);//42
console.log(1-true);//0
//*********************** */
var arr=["a","b"+["c","d"];
console.log(arr); //result: a,bc,d
arr=[3,4]-[1,2]
console.log(arr);//NaN
//*********************** */
/**When you use the || operator, 
 * if the first value casts to true you will get that value returned. 
 * Otherwise, you will always get the second one. In the case of && you will always get 
 * the second value if they are both coerced to true. 
 * If the first one casts to false then you will get it’s value returned. */

const a = 100
const b = "test"
const c = null
console.log(a || b// 100 // '||'  laways returns first value,if it's true 
console.log(a && b// "test" // && always returns second value
console.log(a && c// null
console.log(b && c// null
console.log(Boolean(null),Boolean(undefined) ,Boolean(100) ,Boolean("hello"));
// result: false,false,true,true

console.log("********************************************");

//what will be output of below code
console.log("case 1:")
console.log(1+'2');//Ans : 12 as js converts int to string and contacatenates both

//Question 2:
console.log("case 2:")
console.log(3>2>1); //Ans : false

//Question 3: 
console.log("case 3:");
console.log(3<2<1);
//Expected 'false' but will get 'true' as ('false'<1) ->(0<1) so true.

console.log("case 4:")
console.log('null==0 '+(null==0));// expected true but this expression will give false.

console.log("case 5: ")
console.log(""==0);//true
console.log(""==false);//true
//=========================/
console.log("Case 6:")
console.log(Number(true)); //1
console.log(Number(false)); //0
console.log(Number(undefined));// NaN
console.log(Number(null));//0
console.log(Number(""));
console.log(Boolean(undefined));// false
console.log(Boolean(null));//false

//=========================/


function Abc(name){
    console.log("Hello " +name);
}

Abc();
//Result: 'Hello undefined ' as name's value is undefined. 

Abc("Nds"4,"garbage vale"); 
//Result : "Hello Nds" as function call will ignore other values.

//======Gocha with '||' operator==========

var name1;
function Greet(k){
k=k || 'default value for name param';
console.log(k);
}
// console.log(name1);
// Greet(name1);//undf 0
var tttsdnj=null;
Greet(tttsdnj); // null null
// name1="";
// Greet("empty "+ name1); //empty
// name1='ttt';
// Greet(name1);//name='abc' result:abc;
// name1=0;
// Greet(name1);// 0
console.log(Boolean('str to bool'));


//object 
var Person={};
Person.FirstName="niranjan";
Person.LastName="Sharma";
console.log(Person);
console.log(Person.FirstName);
console.log(Person.LastName);
console.log(Person["FirstName"]);
console.log(Person["LastName"]);
console.log(Person.__proto__.toString());

//Function Gocha
function abc(){
    var name="xyx";
    if(true){
        var name="zzz"// this name will hide above declared name
        console.log(name);         
    }
    console.log(name); // zzz; as new name varible hides old name.
}
abc();


//

Use of ' this ' keyword in Javascript







Below code shows use of 'this' keyword and it's value at different places in Javascript program.

Javascript Promise - a simple explanation



Promise in JavaScript is similar to promise in real life.
In our day to day life we promise something, for example your boss asks you to deliver a particular task within given timeline. we say, yes I will deliver it within given timeline. It's a promise.
Now there two situations with your promise, either you will deliver task within timeline or not.
Same concept is applicable with JavaScript Promises, either promise will be resolved or it will be rejected. ( i.e. either you will be able deliver task on time or you will not be able to deliver on time).
for these two situations, your boss will plan accordingly.
Technically your boss has two functions (plan in real life), one he will execute when you will deliver task on time and other if you will not deliver task on time.
lets see how to create and use Promise in JavaScript.

Promise is a object, which has a executor (function) which takes two callback functions (resolved, rejected)

var deliveryPromise=new Promise(function( resolved, rejected){
              // your are coding and trying to deliver on time;
              // if you are success then you have to call resolved() function.
             // if not then you have to call rejected() function.

});
you are giving this promise to you boss as I wrote previously your boss has two function( In real life these functions (or plan) in his mind)


deliveryPromise.then(function(){

                   // this function will be executed when resolved() called in above code.
                  // Your boss's next plan if you are able to deliver on time
}).catch(function(){
 
                 // this function will be executed when rejected() called in above code.
                // Your boss's backup plan if you are not able to deliver on time
}).finally( function(){
              // this function will be always executed, in both cases (resolved ,rejected)
});

Promise has 3 states : Pending ,Resolved, Rejected.

Definition from MDN :The Promise object represents the eventual completion( or failure ) of an Asynchronous operation, and its resulting value. "

Example :
Suppose your mom is promising you, to buy a new mobile for you, if she will get bonus more than 10000 this month. (if she will get bonus more than 10000 then promise will get resolved otherwise rejected).





Javascript : Difference between undefined and null

Difference between Null and Undefined
1. By default when you declare a variable and not assign any value to it, it would be undefined.
2. Null is basically a object which you can set to a variable, same like other languages, you can assign null to variable to
set it's value to nothing.
3. typeOf(undefined) is undefined while typeOf(null) is object.
4. when you will perform any arithmetic operation on 'undefined' you will get following result :
      var a;
            a+'string' = 'undefinedstring' (result)
            a+5=NaN
            a+true=NaN
            a+null=NaN
while if you will perform arithmentic operation with Null then you will get following result
     var a=null;
            a+'string'='nullstring'
            a+5=5
            a+true=true

JQuery : Quick Review

JQuery Selectors :selectors allows us to find a html elements so, we can manipulate it's attributes programmatically.  Id Sele...