Using the Spread Operator to Evaluate Arrays In-Place Tests

My tests using the Spread Operator rather than the apply function.

In the 1st function show_max_array i use the apply operator to convert the array into comma seperated values.

In the show_max_array_spread function you can see how i replaced the apply with the spread operator and it works in the same way. (i changed the max array value to 58 show the function is still running).

You can test these functions below. 

Demo

JS


// this is a common function just to write the content into the result div
function write_result(result) {
  var result_html = document.getElementById("result");
  result_html.innerHTML = result;
}

function show_max_array() {
  "use strict";
  const an_array = [1,5,8,34,56];
  var the_max = Math.max.apply(null, an_array);
  return the_max;
}

function show_max_array_spread() {
  "use strict";
  const an_array = [1,5,8,34,58];
  var the_max = Math.max(...an_array); // this version skips the apply step and uses the ... spread operator instead to convert the array to values. this only works inline.
  return the_max;
}

// im not sure why this would be useful, but you can copy an array this way as well. it converts the array into comma seperated values.
function copy_array_spread() {
  const an_array = [1,5,8,34,58];
  let another_array = [...an_array];
  return another_array;
}

HTML

<div id='result' class='mb-3 alert alert-primary'>..</div>
<button onclick='write_result(show_max_array());' class='btn btn-primary mb-1'>Run Function - show_max_array</button>
<button onclick='write_result(show_max_array_spread());' class='btn btn-primary mb-1'>Run Function - show_max_array_spread</button>  <button onclick='write_result(copy_array_spread());' class='btn btn-primary mb-1'>Run Function - show_max_array_spread</button>

Working Result

..

External Link for Using the Spread Operator to Evaluate Arrays In-Place Tests

Other Items in javascript
Page Views

This page has been viewed 58 times.

Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹