About ES6 syntax 4 (Template literals, Object initializer)
This article introduced ES6 syntax (Template literals, Object initializer)
This post is to summarize ES6 syntax, which I recently revisited in preparation for a coding test.
ES6 stands for ECMAScript, a standardized version of JavaScript released in 2015.
About Template literals
To use them, use backticks (
) instead of double quotes (β β) or single quotes (β β). You can also use placeholders to contain expressions. They are represented by a $ and curly braces ( ${expression} ). Inside a placeholder, the expression and the text between them are passed to the function together, and the default function simply concatenates those parts into a single string.
If you want to use the backtick character inside a template literal, you can do so by putting a backslash () in front of the backtick.
Example Template literals
`\`` === "`"; // --> true
About object literals (Object initializers)
Methods no longer need to be prefixed with a colon ( : ) or function. If you have overlapping function names, you can only write them once. To dynamically create a property of an object, you used to have to declare it outside of an object literal, but starting with ES6, you can use it as a property right inside the object.
Example of an object literal (Object initializer)
const myFunction = function () {
console.log("my function");
};
const myText = "text";
const myObject = {
// Create myObject in innerFunction
innerFunction() {
console.log("Declare a function directly inside an object.");
},
// Call outside function
myFunction,
// Call outside string and Update key, value
[myText + 1]: "Chamber",
};
myObject.innerFunction(); // result: Declare a function directly inside an object. myObject.innerFunction(); // result: Declare a function directly inside an object.
myObject.myFunction(); // result: my function
console.log(myObject.text1); // result: Chamber