InterviewSolution
| 1. |
What are template Strings in ES6? |
|
Answer» Spread operators(…) were introduced in JAVASCRIPT in ES6 version. Just like plus(+) and MINUS(-) are operators, spread(…) is also an OPERATOR in JavaScript. Basically Spread operator spreads on demand. When you pass arguments to a function using Spread operators they are called Rest parameters. Consider the below example for arrFunc. We can pass any number of arguments to a function and use the …arr to get it. Now inside the function the arr gets converted into and array. This functionality is quite similar to arguments object. Now see the restFunc, here we are using rest parameter to get the remaining of the arguments. We can get argument a, b, c and then the rest is converted into array. The Spread operator can be use separately from function parameter and have some very useful use in array manipulation. They can now also be used with Objects. Consider that we want to copy an array to other array. Now as you can see in the problem that when we assign variable y to x, we are referencing it and any changes to y will reflect in x. In the FIRST solution, we use the new JavaScript method Object.assign() to copy all contents of “a” to an empty array and then assigning it to “b”. But the better and simple solution is with Spread operator where we spread the array “c”, and take its content in an array. Another use it that if we pass an array to build in functions, which expects normal arguments. Consider the below examples. We can also use Spread operator in Objects. So, by it we can do both clone and merge as SHOWN in below example. Notice, that in mergedObj foo is “baz” as Object cannot have duplicate keys. |
|