Wed Sep 30 2015
Paul Shan
function func (argument) { let arr = [ 'a', 'b', 'c', 'd','e','f','g' ]; let [x, y, ...rest] = arr; console.log('rest is: ' + rest); // c,d,e,f,g }
function func (a, b=2, c=3) { console.log("a is "+a+"\n"); //a is 100 console.log("b is "+b+"\n"); //b is 200 console.log("c is "+c+"\n"); //c is 3 } func(100,200);
function func (param1,{firstName,lastName}) { console.log("param1 is "+param1+"\n"); // param1 is 100 console.log("name is "+firstName+ " "+lastName+"\n"); //name is Paul Shan } func(100,{firstName:"Paul", lastName:"Shan"});
//Eg:1 let p =10; console.log("p X p = "+(p=>p*p)(p)); //p X p = 100 //Eg:2 let squares = [1, 2, 3].map(x=>x*x); console.log(squares); // [1,4,9] //Eg:3 setTimeout(()=>{ console.log("Example by Void Canvas"); //Example by Void Canvas },100);
//Example 1 : with normal function var obj={ successFunc:function () { console.log("Success"); }, testFunc:function () { setTimeout(function () { if(this.successFunc) this.successFunc(); else console.log("Failure"); },100); } } obj.testFunc(); //Failure will be printed //Example 2 : with arrow function var obj={ successFunc:function () { console.log("Success"); }, testFunc:function () { setTimeout(() => { if(this.successFunc) this.successFunc(); else console.log("Failure"); },100); } } obj.testFunc(); //Success will be printedIn Example 1, the “this” was not referring to the obj object; rather it was pointing to the current execution context; which is the normal behavior of ES5. But in ES6 if you use “this” keyword inside the arrow function, it will point to the parent object only; which is a normal behavior in Java, C# etc. This will actually omit the need of that=this; kind of code.
function printf (str, ...others) { var finalString = str; if(others){ others.forEach(function (val) { finalString=finalString.replace("%s",val); }); } console.log(finalString); } printf("first name is %s and last name is %s","Paul","Shan"); //first name is Paul and last name is Shan
function func (a, b, c) { console.log("a is "+a+"\n"); //a is 100 console.log("b is "+b+"\n"); //b is 200 console.log("c is "+c+"\n"); //c is 300 } var arr = [100,200,300]; func(...arr);
class Human { constructor(name, age) { this.name = name; this.age = age; } who() { return this.name + " is " + this.age + "years old."; } } let breddy = new Human("Breddy",24); console.log(breddy.who()); //Breddy is 24years old. console.log(breddy instanceof Human); //true
class Human { constructor(name, age) { this.name = name; this.age = age; } who() { return this.name + " is " + this.age + "years old."; } } class Student extends Human { constructor(name, age, school) { super(name, age); this.school = school; } who() { return super.who() + ' He goes to ' + this.school + " school."; } } let breddy = new Student("Breddy",24,"Havard"); console.log(breddy.who()); //Breddy is 24years old. He goes to Havard school. console.log(breddy instanceof Student); //trueAs you can see, stuffs are very easy to write and also to understand. The best thing is you can directly call the “super”. No need to call the super by it’s name.
class MyError extends Error { // do your stuff } throw new MyError('An error occured!');
class MyClass { get prop() { return 'getter'; } set prop(value) { console.log('setter: '+ value); } } let inst = new MyClass(); inst.prop = 123; //setter: 123 console.log(inst.prop) //getter
class MyClass {e constructor(prop) { this.prop = prop; } static staticMethod() { return 'I am static'; } prototypeMethod() { return 'I am NOT Static'; } } let inst = new Myclass(123); console.log(inst.prototypeMethod()); //I am NOT Static console.log(MyClass.staticMethod()); //I am static console.log(MyClass.prototypeMethod()); //Error: prototypeMethod is not a function console.log(MyClass.prototype.prototypeMethod()); //I am NOT StaticThe non static members can also be called using the class’s prototype.
//defining modules //------ math.js ------ export function add(a,b) { return a+b; } export function subtract(a,b) { return a-b; } //------ main.js ------ import { add, subtract } from 'math'; console.log(add(11,2)); // 13 console.log(subtract(4, 3)); // 1 //------ main2.js -------- import * as math from 'math'; console.log(math.add(11,2)); // 13 console.log(math.subtract(4, 3)); // 1You can export the methods and properties from a file, which will be considered as modules. In some other file you can selectively (or all) import them. In main.js I specifically imported only two functions of math.js; whereas main2.js imported all the functions with a namespace. The same thing can be done in CommonJS style too. Below is the example.
function add(a, b) { return a+b; } function subtract(a, b) { return a-b; } module.exports = { add: add, subtract: subtract }; //------ main.js ------ var add = require('math').add; var subtract = require('math').subtract; console.log(add(11,2)); // 13 console.log(subtract(4, 3)); // 1 //---- main2.js ----- var math = require('math'); console.log(math.add(11,2)); // 13 console.log(math.subtract(4, 3)); // 1
//------ Human.js ------ export default class { constructor(name){ this.name=name; } } //------ main2.js ------ import Human from 'Human'; let me = new Human("Paul");
let firstName = "Paul"; let lastName = "Shan"; console.log(`full name is ${firstName} ${lastName}`); //full name is Paul Shan
let firstName = "Paul"; let lastName = "Shan"; console.log(`full name is ${firstName} ${lastName}. Age is ${10+10+6}`); //full name is Paul Shan. Age is 26
//In ES5 var str = "Hi all \ I am Paul \ showing you JS examples"; console.log(str); //Hi all I am Paul showing you JS examples var str2 = "Hi all "+ "I am Paul "+ "showing you JS examples"; console.log(str); //Hi all I am Paul showing you JS examples //In ES6 let str3 = `Hi all I am Paul showing you JS examples`; console.log(str3); //Hi all //I am Paul //showing you JS examples
//Eg 1: pass a single string function getLength(str){ return str[0].length; } console.log(`length of VoidCanvas is ${getLength `VoidCanvas`}`) //Eg 2: passing multiple value let firstName = "Paul"; let lastName = "Shan"; function fullName(stringKey, value1, value2){ return value1 + " " + value2; } console.log(`full name is ${fullName `${firstName} ${lastName}`}`); //full name is Paul Shan
//iterate on an array and print all values let templateStr = nameList => displayName` Names are as follows: ${nameList.map(name => displayName` ${name.first} ${name.last}` )} `; console.log(templateStr([ {first:"Paul", last:"Shan"}, {first:"Lois", last:"Lane"} ])); function displayName(literalSections, ...values){ let output = ""; output += recursiveArrayJoin(literalSections); output += recursiveArrayJoin(values); return output; } function recursiveArrayJoin(arr){ let output = ""; arr.forEach(element => { if(element.trim){ if(element.trim()) output+=element+ " " } else{ if(element && element.length) output += recursiveArrayJoin(element); } }); return output; }
var myArr=["Void", "Canvas"]; var myStr = "voidcanvas.com"; var myObj={ "firstName":"Paul", "lastName":"Shan" }; for(var i in myArr){ console.log(i); // 0 1 } for(var v of myArr){ console.log(v); // Void Canvas } for(var i in myStr){ console.log(i); //0 1 2 3 4 5 6 7 8 9 10 11 12 13 } for(var v of myStr){ console.log(v); //voidcanvas.com } for(var i in myObj){ console.log(i); //firstName lastName } //ERROR: not a function. for(var v of myObj){ // Because for of is not applicable in objects console.log(v); }
//problem setTimeout(function(){ console.log("interruption!"); },100); while(true){ console.log("hello!"); }Even if the while loop is not infinite and iterates 10000 times, than also the setTimeout() won’t be able to execute the function to print “interruption”. But generators can be paused or interrupted while looping. Interruptions are allowed in these because generators uses yield inside it. Below is an example code of generator.
function* iteratorGenerator(arr){ for(var i=0;iTo know more about ES6 generators you can refer David Walsh’s blog post. Symbol
Something like Enum has been introduced to JavaScript now. This is called Symbol. This is a new type of primitive value. Let's see how Symbol actually works.Overview
var sym = Symbol(); var foo = Symbol("foo"); typeof sym; // "symbol" var symObj = new Symbol(); // TypeError var symObj = Object(sym); typeof symObj; // "object" Symbol("foo") === Symbol("foo"); // falseUsage
//previously var red = "red"; var green = "green"; var blue = "blue"; function handleColor(color) { switch(color) { case "red": //do your stuff case "green": //do your stuff case "blue": //do your stuff } } //with Symbol const red = Symbol(); const green = Symbol(); const blue = Symbol(); function handleColor(color) { switch(color) { case red: //do your stuff case green: //do your stuff case blue: //do your stuff } }Important methods
The two important methods are Symbol.key() and Symbol.keyFor()let foo1 = Symbol.for("foo"); // create a new symbol let foo2 = Symbol.for("foo"); // retrieve the already created symbol foo1 === foo2 // true Symbol("bar") === Symbol("bar"); // false var globalSym = Symbol.for("foo"); // create a new global symbol Symbol.keyFor(globalSym); // "foo"Few more on ES6 Objects
Let’s check some other new methods and libraries in ES6 with small examples.Map
let map = new Map(); let obj = {a:1}; let func = function(){ var a=1; } map.set(obj, 123); map.set(func, "This is fun"); console.log(map.size); // 2 console.log(map.get(obj)); // 123 console.log(obj); // {"a":1} console.log(map.get(func)); // This is fun console.log(map.has(obj)); // true map.delete(obj); console.log(map.has(obj)); // falseMap is nothing but a key value pair; just like the JavaScript objects. But there are few differences. They are as below:
- The property key of an object can only be string. Whereas the key of a Map can be string, Object, Function or anything.
- If you iterate on a Map, it will iterate exactly in the same order the values were pushed, whereas in case of objects this is not followed.
- Using map.size you can easily get the size of it. But in case of Objects you need to find the size manually.
Set
let set1 = new Set(); set1.add('hello'); set1.add('hello'); console.log(set1.has('hello')); // true console.log(set1.has('world')); // false let set2 = new Set([3,2,1,3,2,3]); console.log(set2.size); //3 console.log(set2.values()); // {3,2,1} - it returns unique values in insertion order console.log(set2.entries()); // {[3,3],[2,2],[1,1]} - it returns all the values insertedSet is an Object to store unique primitive as well as object references. However it doesn’t throw error if you want to add a duplicate value, but silently make the set unique.Object.assign()
Now it’s easy to extend or combine two objects with Object.assign(). Below is an example.var one = {a:1}; var two = {b:2}; Object.assign(one,two); console.log(one); // {"a":1,"b":2} console.log(two); // {"b":2}More on ES6 String
The methods below belongs to the String.prototype. I mentioned the headings as String.method() for better understanding. Examples describes the usage.String.repeat(int)
'abc'.repeat(3); // abcabcabc 'abc'.repeat(3.6); // abcabcabc 'abc'.repeat("2"); // abcabc 'abc'.repeat(-1); //range errorString.startsWith(string)
'abc'.startsWith('ab'); // true '123'.startsWith(1); // true 'abc'.startsWith('b'); // falseString.endsWith(string)
'abc'.endsWith('bc'); // true '123'.endsWith(3); // true 'abc'.endsWith('b'); // falseString.contains(string)
'abc'.contains('bc'); // true '123'.contains(3); // true 'abc'.contains('x'); // falseMore on ES6 Array
The methods below belongs to the Array.prototype. I mentioned the headings as Array.method() for better understanding. Examples describes the usage.Array.find(arrow=>function)
It finds the first element and stops there.var a=[13,7,8,22].find(x => x % 2 === 0) console.log(a); //8Array.findIndex(arrow=>function)
It finds the index of the first occurrencevar a=[13,7,8,22].findIndex(x => x % 2 === 0) console.log(a); //2
SHARE THIS ARTICLE
Thu Mar 10 2016
OAuth authentications are pretty popular now a days and another thing which is popular is JavaScript. This article shows how to plugin google’s oAuth api for authentication in your own node application.Sat Mar 01 2014
This is a continuation of my CSS3 loader snippet collection series. I've provided spinning css3 animation loader in the part 1 of this series and here in part 2, I'm providing various square type loading