#Did you know is a new series of Enmascript where we write short and concise explanations about topics we consider might be relevant or underestimated, if you are looking for more complete in-depth articles check out our other series.
One of the most popular features used in javascript after Ecmascript 2015 is without question the spread operator. In this short "Did you know" article, we will explore a couple of exceptional use cases that we consider to be very useful but that are not so well known.
Optional/Conditional Spreading
Add object properties and values based on a condition:
In this way, we can add the woof property conditionally without having to use any if/else logic or similar approaches... if the condition returns true, it will add the property, otherwise, the object will remain untouched.
result of console.log(obj)
{key:'value',woof:true};
Important note: optional spreading like this only works inside an object, if we try to do this outside of it we would get a SyntaxError, if you want to understand a little more of why this happens you may want to check out this conversation we had in reddit
Copy objects and exclude selected properties
Let's say we like the parts of certain CPU and we would like to keep most of them except for the ssd, because of course, we would like to have more space:
// Original CPUconstCPU={ram:'32gb',ssd:'64gb',micro:'i7'};// new CPU copy without the 64GB ssdconst{ ssd,...newCPU }=CPU;
Now, if you console log newCPU you will see that it does not longer contain the ssd property, this happened because we excluded that property from the rest that were included in newCPU by leveraging the rest operator.
result of console.log(newCPU)
{ram:'16gb',micro:'i7'};
Do you have any more relevant use cases for the spread operator you would like to comment about? go a head and do that on reddit or twitter in our social links.
Big O notation allows us to evaluate the performance of algorithms so that we can determine their efficiency and make decisions based on this determinations, let's try to understand how this notation works and how we can apply it in our lives as software developers.Read more
Linked Lists are a fundamental data structure in the world of software development, in this article we will explore its implementation and its applications in today's worldRead more