Home > Enterprise >  Not getting result when I call a custom function
Not getting result when I call a custom function

Time:08-21

I would like help figuring out why I'm not getting results when I'm calling a function, for example:

    animals = new Array(4);
    animals[0] = "Cow";
    animals[1] = "Cat";
    animals[2] = "Dog";
    animals[3] = "Ant";
    
  function fauna(animals){
        
        return animals[0];
    }
   
    fauna();

Thanks in advance.

CodePudding user response:

Pay attention that the argument to fauna has the same name as the global variable animals, when something like this happens, Javascript gives priority to the local scoped variable, in the last line you call fauna without sending any parameter, with this when fauna tries to use animals, is can not find it, because the animals fauna is trying to reach is not the same you declared before.

To solve this, there are two approachs,

first: passing animals(global) to fauna so its animals(local) would refer to the same value, like this:

    animals = new Array(4);
    animals[0] = "Cow";
    animals[1] = "Cat";
    animals[2] = "Dog";
    animals[3] = "Ant";
    
  function fauna(animals){
        
        return animals[0];
    }
   
    fauna(animals);

Second, make fauna to get the global animals, not the local's one, in order to do so, remove fauna parameter, like this:

    animals = new Array(4);
    animals[0] = "Cow";
    animals[1] = "Cat";
    animals[2] = "Dog";
    animals[3] = "Ant";
    
  function fauna(){
        
        return animals[0];
    }
   
    fauna();

CodePudding user response:

To combine the previous answers and provide a working code snippet, check this out. You forgot to include the let or const keywords before declaring the animals array.

Further, you're not passing any argument into the faunua function. You want to pass in the animals variable, which is in the same scope as where you are calling the function

You also did not write anything to the console. This can be achieved by using console.log

const animals = new Array(4);
animals[0] = "Cow";
animals[1] = "Cat";
animals[2] = "Dog";
animals[3] = "Ant";

function fauna(animals){
    return animals[0];
}

console.log(fauna(animals))

CodePudding user response:

const animals = new Array(4);
animals[0] = "Cow";
animals[1] = "Cat";
animals[2] = "Dog";
animals[3] = "Ant";

function fauna(animals){
    return animals[0];
}

fauna(animals);

Try this. You were not passing animals array to function call.

  • Related