skip to Main Content

Here, I have created an array that will print the output, but the second output did not give a valid result, like I work as a Web Dev in Ind. I want, but it prints I work as a Sam in 27. So, what do I need to change about this program? 

const arr = [
  (name, age) => {
    console.log(`My name is ${name} and I am ${age} years old.`);
  },
  (job, city) => {
    console.log(`I work as a ${job} in ${city}.`);
  }
];

for (let i = 0; i < arr.length; i++) {
  arr[i]("Sam", 27, "Web Dev", "Ind");
}

2

Answers


  1. You are passing all 4 parameters into each function, which only takes 2 parameters.

    In your code:

    for (let i = 0; i < arr.length; i++) {
      arr[i]("Sam", 27, "Web Dev", "Ind");
    }
    

    Basically what is being run are these two function calls:

    arr[0]("Sam", 27, "Web Dev", "Ind")
    arr[1]("Sam", 27, "Web Dev", "Ind")
    

    Where what you want to run is this:

    arr[0]("Sam", 27)
    arr[1]("Web Dev", "Ind")
    

    So you will have to go about passing your parameters, or executing your functions in a different way.

    Login or Signup to reply.
  2. To get something like the effect you want, you can use destructuring:

    const arr = [
      ({name, age}) => {
        console.log(`My name is ${name} and I am ${age} years old.`);
      },
      ({job, city}) => {
        console.log(`I work as a ${job} in ${city}.`);
      }
    ];
    
    for (let i = 0; i < arr.length; i++) {
      arr[i]({ name: "Sam", age: 27, job: "Web Dev", city: "Ind"});
    }

    Destructuring allows each function to decide which properties to pluck out of the passed object. You could add another function:

    const arr = [
      ({name, age}) => {
        console.log(`My name is ${name} and I am ${age} years old.`);
      },
      ({job, city}) => {
        console.log(`I work as a ${job} in ${city}.`);
      },
      ({city, age}) => {
        console.log(`At ${age} years old, I find ${city} to be a lot of fun.`);
      }
    ];
    
    for (let i = 0; i < arr.length; i++) {
      arr[i]({ name: "Sam", age: 27, job: "Web Dev", city: "Ind"});
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search