Home > Software engineering >  Are there built-in parameters in Javascript?
Are there built-in parameters in Javascript?

Time:10-18

Where do arguments like element, index and array come from, for e.g. the filter method like below:

const arr = [ "Laurence", "Mike", "Larry", "Kim", "Joanne", "Laurence", "Mike", "Laurence", "Mike", "Laurence", "Mike" ];
const arr2 = arr.filter((value, index, array) => {
    console.log(value, index, array.indexOf(value));
    return array.indexOf(value) === index;
});
console.log(arr2);

In some built-in methods we use them, I know what they do, but I don’t understand if they are like built-in parameters.

For example, when one defines a function one would add parameters like value, index and array.

But when one calls the function one doesn’t add any arguments.

Are these kind of parameters like built-in parameters or why we don’t have to specify what they are?

CodePudding user response:

I wrote a custom filter function to show you that these parameters aren't built-in, they are just passed to your callback by the Array.prototype.filter function when the internal loop is executed.

const result = filter([1, 2, 3, 4, 5], item => item % 2 === 0)

console.log(result)

function filter(array, callback) {
  const newArray = []
  for (let i = 0; i < array.length; i  = 1) {
    // pass value index and array
    if (callback(array[i], i, array)) {
      newArray.push(array[i])
    }
  }
  return newArray
}

forEach example:

forEach([1, 2, 3, 4, 5], (value, index) => console.log(value, index))


function forEach(array, callback) {
  for (let i = 0; i < array.length; i  = 1) {
    callback(array[i], i, array)
  }
}

CodePudding user response:

The answer is very simple, No there aren't

CodePudding user response:

In JavaScript, functions are objects like any other -- you can pass functions to functions. This is how the Array.prototype.filter function (the filter method you'd call on an array like arr.filter(...)) works -- it takes a function as a parameter. It filters by calling the function you pass to filter, for every element, with the element [of the array] as value, the index of the element [in the array] as index, and the array itself as array. If your function returns true, the element is contained in the array returned by filter, otherwise the element isn't contained in the returned array.

So yes, the filter function is what calls the function you pass to filter, binding parameters to values -- something that makes parameters arguments.

In JavaScript, if you do not pass an argument to a function that expects an argument, the argument is undefined -- you can say that the parameter isn't bound:

function f(a) {
     return a;
}
console.assert(f() === undefined); /// Yields true

JavaScript will not warn you that an argument is missing.

That is all there is to it, really.

  • Related