You can use the object assign function or apply
() function as an Alternative to spread operator JavaScript.
Alternative to spread operator JavaScript
In a simple example code, the spread operator and the Object assign function both will take the right objects.
<!DOCTYPE html>
<html>
<body>
<script>
const moreFood = {
'pizza': '🍕',
'steak': '🥩',
};
const food = { 'chocolate': '🍫', 'icecream': '🍦', 'pizza': 'pizza' };
var res = Object.assign(food, moreFood);
console.log(res)
</script>
</body>
</html>
Output:
There isn’t a simple one-to-one mapping between using the spread operator and using apply
. But we can still create a pretty decent emulation. Let’s take a look at how.
function spreadify (fn, fnThis) {
return function (/* accepts unlimited arguments */) {
// Holds the processed arguments for use by `fn`
var spreadArgs = [ ];
// Caching length
var length = arguments.length;
var currentArg;
for (var i = 0; i < length; i++) {
currentArg = arguments[i];
if (Array.isArray(currentArg)) {
spreadArgs = spreadArgs.concat(currentArg);
} else {
spreadArgs.push(currentArg);
}
}
fn.apply(fnThis, spreadArgs);
};
}
var someArgs = ["a", "b", "c"];
var moreArgs = [1, 2, 3];
console.log(someArgs, moreArgs);
Outputs: [“a”, “b”, “c”] [1, 2, 3]
Or concatenate two arrays using concat()
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const concatenatedArray = arr1.concat(arr2);
console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6]
Do comment if you have any doubts or suggestions on this JS operator code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version