JavaScript: Immutability, arrow function and object spread operator

Submitted by Peter Majmesku on Tue, 01/02/2018 - 23:22

In JavaScript, function arguments are references to the actual data.

Here, we used Object.assign to change the color rating. Object.assign is the copy machine; it takes a blank object, copies the color to that object, and overwrites the rating on the copy. Now we can have a newly rated color object without having to change the original.

This gives 

let color_lawn = {
    
title"lawn",
    
color"#00FF00",
    
rating0
}

var 
rateColor = function(colorrating) {
    return 
Object.assign({}, color, {rating:rating})
}

console.log(rateColor(color_lawn5).rating)      // 5
console.log(color_lawn.rating// 0 

ES6 arrow function along with the ES7 object spread operator

This example can be shortened with the new JS standards. See below.

let color_lawn = {
    
title"lawn",
    
color"#00FF00",
    
rating0
}

// ES6 arrow function: =>
const rateColor = (colorrating) =>
    ({
        
// ES7 spread operator: ...
        
...color,
        
rating
    
})

console.log(rateColor(color_lawn5).rating)      // 5
console.log(color_lawn.rating)                          // 0 

This function copies the original object to a new object and then sets a new color rate in that copy. It is immutable.

Short explanation about the new techniques

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

Pure functions

A pure function is a function that returns a value that is computed based on its arguments. Pure functions take at least one argument and always return a value or another function. They do not cause side effects, set global variables, or change anything about application state. They treat their arguments as immutable data and are testable.

List of references

Tags

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.