This is the second of series of posts that explore new features of ES6 so in this post lets look at const keyword and template literals introduced in ES6.
const keyword
In previous versions of JavaScript there was no way to define a constant value. Developers just used only upper case letters to declare a constant variable like,
var SEC_KEY="1234567";
But it could be changed at a latter part of the code.
var SEC_KEY="1234567";
SEC_KEY="abcdefg";
console.log(SEC_KEY);
As above example demonstrate a different value can be written to a variable after declaration. So ES6 has introduced a new keyword called const. defining a variable with const keyword make that variable read-only. So the below code will give an error when trying to update the variable.
const SEC_KEY="1234567";
SEC_KEY="abcdefg";
Template literals
Template literel is a new feature that came with ES6. We all know we can define a string using string literals with single or double quotes in javaScript. Template literals use back-ticks (``) Before ES6 we had to type "\n" in side a string to make a new line. But with template literals it can be done without typing extra characters as in following code snippet.
var par1='line1 \nline2';
var par2=`line 1
line 2`;
console.log(par1);
console.log(par2);
When concatenate variables with string "+" was used before ES6. With template literals in ES6 variables can be embedded in to a string inside ${} syntax as demonstrated in following example.
var variable1="abc"
var variable2="def"
var par3="variable1 : "+variable1+" | variable2 : "+variable2;
var par4=`variable1 : ${variable1} | variable2 : ${variable2}`;
console.log(par3);
console.log(par4);
No comments:
Post a Comment