Search code examples
javascriptjquerydomjavascript-objects

JavaScript object as parameter


I tried to make a function that writes some divs in an HTML document. Everything is working fine but I want to try to change the function declaration from this:

function writeDiv(divDOMelement, numberOfExcercises, numberOfTasksInEx);

To something like this

function writeDiv(divDOMelement, {numberOfExcercises:N, numberOfTasksInEx:[v]}) 

Just to be clear, the first declaration works perfectly, but when I tried implementing the second one, and changing the function call I received an error.

Here is the full code:

let open = false;
let currentlyOpen;

function writeDiv(divDOMelement, {numberOfExcercises:N, numberOfTasksInEx:[v]}) {
  for (let i = 0; i < numberOfExcercises.N; i++) {
    // ... didnt include the code that prints the divs on the site just to make it easier to read.
    for (let j = 0; j < numberOfTasksInEx.v[i]; j++) {
    // ... same as the first loop.
    }
  }
}


$(document).ready(function () {
  writeDiv("#mainDiv", {numberOfExcercises:3, numberOfTasksInEx:[5,2,3]});
});

Just to clarify, this numberOfTasksInEx should be an array, the first element of the array tells me that the first exercise will have that many tasks, the second tells me that the second exercise will have that many tasks, and so on.

The error I am getting:

jQuery.Deferred exception: numberOfExcercises is not defined 
Uncaught ReferenceError: numberOfExcercises is not defined

Solution

  • Your declaration syntax is incorrect. All you need is:

    function writeDiv(divDOMelement, {numberOfExcercises, numberOfTasksInEx})
    

    Then inside your function you'll have numberOfExercises as the overall count, and numberOfTasksInEx as the array of per-exercise tasks.

    The declaration syntax extracts those properties from the single object passed in as the second parameter to the function in a process called "decomposition". The : in your version does something, but not what your code expects: it allows the property name from the source object (the actual parameter) to be renamed. That's not really necessary here, but for example numberOfExercises:N would mean that in your function you would refer to simply N, not numberOfExercises.N.