Spread operator in JavaScript VS Python.

Aditya Sharma - Jan 13 '23 - - Dev Community

The JavaScript spread operator(...) becoming popular in programming as it is used for expanding iterable objects into function arguments, array literals, or other object literals.

Simply saying, spread operator can be used as an unpacking tools which expands the iterables into individual elements

On the other hand, Python too contains an alternative for Spread operator that allows the iterables unpacking.

Now we will see it in some of the examples shown-

Array Literals

In JS

const name = ['Aditya', 'Shivam', 'Yash'];
 const newname = ['Sahil', ...name, 'Niraj']; //spreading name in newname

 console.log(newname);

//Output:['Sahil', 'Aditya', 'Shivam', 'Yash', 'Niraj']
Enter fullscreen mode Exit fullscreen mode

Similarly,
In Python

name = ['Aditya', 'Shivam', 'Yash']
newname = ['Sahil', *name, 'Niraj']# unpacking name in newname

print(newname)

#Output: ['Sahil', 'Aditya', 'Shivam', 'Yash', 'Niraj']
Enter fullscreen mode Exit fullscreen mode

As we can see, we achieved the same result in Python as we got using the spread operator in JS.

Function Arguments

In JS

function add(a,b){
    return a+b;
}
const nums = [20,30];

console.log(add(...nums));//spreading nums while passing argument to a function

//Output: 50
Enter fullscreen mode Exit fullscreen mode

Similarly,
In Python

def add(a,b):
    return a+b
nums = [20,30]
print(add(*nums)#unpacking nums list while passing it to the add method
Enter fullscreen mode Exit fullscreen mode

Here we used the approach to get the similar output as we got in JS using spread operator.

Object Literals

In JS

const person = {
    name : 'Aditya',
    age : '23',
    occupation : 'Developer',
    height:'170 cm'
}

console.log({...person,location : 'India'})

//Output: {name: 'Aditya', age: '23', occupation: 'Developer', height: '170 cm', location: 'India'}
Enter fullscreen mode Exit fullscreen mode

Similarly, in Python we can use the double asterisk operator (**)

In Python

person = {
    'name' : 'Aditya',
    'age' : '23',
    'occupation' : 'Developer',
    'height' : '170 cm'
}

print({**person, 'location':'India'})

//Output: {'name': 'Aditya', 'age': '23', 'occupation': 'Developer', 'height': '170 cm', 'location': 'India'}
Enter fullscreen mode Exit fullscreen mode

As we can see, we needed **person to unpack the keyword arguments. Whereas, single asterisk operator *nums is used for iterable objects.

For more, follow me on Github, LinkedIn

. . . . . . . . .