Python has a succinct way of assigning a function with a parameter to multiple variables, done as a one-liner. I would like to know whether JavaScript has the same, or similar way of doing that.
I have found several examples describing multiple variable assignments for JavaScript, using multiple assignments and Destructuring. The issue with these methods is that they can, or do require equality of variable to value:
let a = b = c = some_value, or let [a, b] = [x, y]. This is where I have a problem with a particular part of code.
Python
#!/usr/bin/env python3
def numbers(arr):
if len(arr) <= 1:
return arr
left_half, right_half = divide(arr) # The code in question; Multi-variable assignment
return left_half, right_half
def divide(arr):
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
return left, right
l = [12, 45, 9, 2, 5]
print(numbers(l)) # ...([12, 45],[9, 2, 5])
JavaScript
function numbers(arr) {
if (arr.length <= 1) {
return arr;
}
let leftHalf, rightHalf = divide(arr); // The not-so-equivalent code
return leftHalf, rightHalf;
}
function divide(arr) {
let mid = Math.floor(arr.length / 2);
let left = arr.slice(0, mid);
let right = arr.slice(mid);
return left, right;
}
const l = [12, 45, 9, 2, 5];
console.log(numbers(l)); // ...[9, 2, 5]
How can the same or similar pattern as Python be achieved in the JavaScript code?
return [left, right];andlet [leftHalf, rightHalf] = divide(arr);. See Destructuring assignmentleftandleftHalfcompletely. Is that what you are trying to do?let [leftHalf, rightHalf] = divide(arr);gives me the result I outlined.