JS Tutorial

Function Reference

Method Reference

  • JS String
  • JS Array
  • JavaScript Arrow Function

    Arrow functions were introduced with ES6 for shorter function syntax

    It can be used as Constructor. it also best for non-method function

    Syntax

    (param1, param2,.., paramN) => { statements } 
    

    Example

    var test = () => {
      return "test JS";
    }
    test();
    //output
    //test JS
    

    Arrow Function With Single Parameters

    var test = (name) => 'Name is '+name;
    test('Ashish');
    //output
    //Name is Ashish
    
    //OR
    var test = name => 'Name is '+name;
    test('Ashish');
    //output
    //Name is Ashish
    

    Arrow Function With Multiple Parameters

    var sum = (n1,n2) =>{
     return n1+n2;
    } 
    sum(2,3);
    //output
    //5
    

    Arrow Function With default Parameters and Hoisting

    //default parameter with regular funstion
    function testReg(name='Ashish'){
    console.log(name);
    }
    testReg();
    //Ashish
    
    //default parameter with arrow funstion
    const testArrow = (name='Avanish')=>console.log(name);
    testArrow();
    //Avanish
    
    //hoisting
    testReg();
    function testReg(name='Ashish'){
    console.log(name);
    }
    //Ashish
    
    testArrow();
    const testArrow = (name='Avanish')=>console.log(name);
    //Uncaught ReferenceError: Cannot access 'testArrow' before initialization
    

    Arrow function with return type object

    const objectTest = ()=>({name:'Ashish'});
    const person=objectTest();
    console.log(person);
    //output
    //{name: "Ashish"}
    

    Arrow Function "this" object example

    Example

    //ES5
    var person = {
    name:'Ashish',
    age:30,
    testHello : function(){ 
    	console.log(this.name);
    }
    }; 
    person.testHello();
    //Ashish
    
    //ES5
    var person = {
    name:'Ashish',
    age:30,
    testHello : function(){ 
    var self=this;
    	setTimeout(function() {
    		console.log(self.name);
    	},10);
    }
    }; 
    person.testHello();
    //Ashish
    
    //ES6
    var person = {
    name:'Ashish',
    age:30,
    testHello : function(){ 
    	setTimeout(() => {
    		console.log(this.name);
    	},10);
    }
    }; 
    person.testHello();
    //Ashish
    
    
    //ES6
    var person = {
    name:'Ashish',
    age:30,
    testHello : ()=>{
    	console.log(this.name)
     }
    }; 
    person.testHello();
    //undefined