//*************** Before ES6 *********************//varcustomer={name:"Jane Doe",handleMessage:function(message,handler){handler(message);},greet:function(){varthat=this;this.handleMessage("Hello, ",function(message){console.log(message+that.name);});}};customer.greet();// "Hello, Jane Doe"// Another option is to use .bind()varcustomer={name:"Jane Doe",handleMessage:function(message,handler){handler(message);},greet:function(){this.handleMessage("Hello, ",function(message){console.log(message+this.name);}.bind(this));}};customer.greet();// "Hello, Jane Doe"
Now, there is a simple way using the arrow function.
1
2
3
4
5
6
7
8
9
10
11
12
//*************** In ES6(using =>) ***************//varcustomer={name:"Jane Doe",handleMessage:(message,handler)=>handler(message),greet:function(){this.handleMessage("Hello, ",(message)=>console.log(message+this.name));}};customer.greet();// "Hello, Jane Doe"
2. Template Strings
1
2
3
4
5
6
7
8
9
10
11
//*************** Before ES6 *********************//varsalutation="Hello";vargreeting=salutation+", World";console.log(greeting);// "Hello, World"//*************** In ES6(using ${}) ***************//varsalutation="Hello";vargreeting=`${salutation},World`;console.log(greeting);// "Hello, World"
You can also do computation inside ${} such as the example below:
Another cool thing is multi-line string. Using backticks you can easily create a multi-line string.
1
2
3
4
5
6
7
8
9
10
11
12
varweatherNote='The weather\n\t'+'today is\n\t'+'sunny';console.log(weatherNote);//*************** In ES6(using ``) ***************//varweatherNote=`Theweathertodayissunny`;console.log(weatherNote);
3. let - allows block scoping to be created.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//*************** Before ES6 *********************//varx=100;if(x){varx=2;}console.log(x);// 2//*************** In ES6(using let) ***************//varx=100;if(x){letx=2;}console.log(x);// 100
4. const - assign constant variables that should not be re-assign
1
2
3
4
5
6
7
8
9
//*************** Before ES6 *********************//varAPI_BASE_URL="www.asdf.com";API_BASE_URL="qwer";// still able to re-assign API_BASE_URL to another valueconsole.log(API_BASE_URL);// "qwer"//************** In ES6(using const) *************//constAPI_BASE_URL="www.asdf.com";API_BASE_URL="qwer";console.log(API_BASE_URL);// Will trigger an error saying attempting to override 'API_BASE_URL' which is a constant.
//*************** Before ES6 ****************************************//varmultiplication=function(x,y){returnx*y;}console.log(multiplication());// NaNconsole.log(multiplication(1,2));// 2//*************** In ES6(default function parameters) ***************//varmultiplication=function(x=0,y=0){returnx*y;};console.log(multiplication());// 0console.log(multiplication(1,2));// 2
7. Repeat
1
2
3
4
//*************** In ES6(.repeat()) ***************//varcat="meow".repeat(5);console.log(cat);// "meowmeowmeow"
Below are some references that you can take a look to learn more about ES6.