Differnce between function script and nno function script

hello every one
hope you all doing well.

can anyone please explain the difference between these two scripts, as both scripts are giving the same result.

why add the function when we are doing fine without it. Any reasons.

with function

const cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}


cars.sort(function(a, b){return a.year - b.year});

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;

Without function

Advance thanks.

With this trivial example it doesn’t make any difference. But really you’re likely to have much more complex needs (and likely a lot more data). At that point you want to break the problem down into small parts. Breaking things into functions is the way to do that. This looks like the start of that process – going forward maybe you have a function that gets an array of cars from somewhere, then one that takes the result of that and reads an parses it. Maybe filters the cars. Then one that takes the result of that and renders to HTML

many thanks for the explanation

The two are not the same. In the code, you update the DOM twice, in the image you only do it once.

Without the function, you would have to repeat the DOM code twice, before and after the sort. I’d say it is a fine example of when you need a function. That is when you need to repeat/reuse the functionality the code provides.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.