Javascript Syntactic Sugar
Syntactic sugar describes an alternative syntax designed to make ones code more concise. This is often synonymous with more efficient code, however may vary on a case to case bases.
- Adding one to a variable. Instead of writing out “chocolates = chocolates +1”, Javascript offers the simple option of placing “++” after, or before the variable. If the “++” is added before the variable the return will be the new value. If the “++” is added after the variable, the variable will increase, however the immediately returned value will be unchanged.
2. Ternary Operation: used in place of an if/else statement. In the below example “loveChocolate” is the statement, after the question mark you have two outcomes. The first is “chocolate chip cookies”, which will be returned if the condition is true. The second is “key lime pie”, which will be returned if the condition is false.
3. Removing Redundancies: if key value-pair is the same, one can declare pair as shown below.
4. Object Destructuring: used by selecting an element from a collection, and assigning the chosen elements to variable. This allows for the value to be easily called on in the future.
5. Object Spread: operator allows you to pass elements of an array into a function as an argument. Instead of passing in (“sugar”, “butter”, “salt”)as three separate arguments, one can simply enter the array name as shown below. Note: if the array has more arguments than the function requests, the additional arguments will be ignored (ex. (“sugar”, “butter”, “salt”, “chocolate”) will render the same result). Similarly if the array has less arguments than the function requests, the undefined arguments will show as “undefined”.
6. Rest Parameter: allows you to collect the remaining parameters, that you are passing into your function, into an array. The below “randolphsDesserts” function takes in three arguments. The first argument (“Eclairs”) passed through will be assigned to “a” the second(“Apricot Tarts”) to “b”, and the remainder will be assigned to the “desserts” array.
7. Object.assign: allows us to combine properties from multiple Objects into a single Object. If multiple objects have the same key, the last object called will override the first. The example below shows three objects being combined into one.
8. Iterating: There are several ways to iterate in javascript, however the “sugar” iterations include forEach, Find, Filter. Allowing for more concise code.
Citation: