Spread Operator & JSX
Learn how to use the spread operator and JSX in Python.
We'll cover the following...
Spread operator
In JavaScript, we may see a parameter notation that looks like this:
var myObject = { foo: 'bar', bar: 123, baz: false };var newObject = { ...myObject, bar: 42};//newObject { foo: 'bar', bar: 42, baz: false }
The ...
notation is the JavaScript spread operator, which performs a function similar to what a dictionary update()
method would be used for. It expands a list of parameters and merges or replaces values based on the keys of the parameters that follow. So, to get similar behavior in Python, we could do this:
myObject = { foo: 'bar', bar: 123, baz: false }newObject = {}## newObject { }newObject.update(myObject)## newObject { foo: 'bar', bar: 123, baz: false }newObject.update({bar: 42})## newObject { foo: 'bar', bar: 42, baz: false }
Because we are frequently working with immutable objects in React, we first start with an empty dictionary and use update()
to populate it with the original values to get a new copy before updating the target value. Note that if the dictionary value is a complex object, we may need to use a deepcopy()
function to make sure we are getting new values and not just copying object pointers. After that, we can use the update()
method again to apply new values.
We may also see the ...
notation in a JavaScript function definition, in which case it is a Rest parameter. In Python, that is the same as using *args
to refer to an arbitrary number of arguments.
JSX
It is ...