Search code examples
javascriptarraysfunctionreturn

How to return true each time something is added to an array in Javascript


I created a function that will add an item to an empty array up to a const max value. However, I can't figure out how to return true each time an item is successfully added to the array (and false each time an item couldn't be added). Here is what I've got:

let adoptedDogs = [];
const maxDogs = 2;

function getDog( name ){
console.log( 'dog's name:', name );

if( adoptedDogs.length < maxDogs ){
  adoptedDogs.push( name );
}
}

getDog( 'Spot' );
getDog( 'Daisy' );
getDog( 'Chester' );

Solution

  • let adoptedDogs = [];
    const maxDogs = 2;
    
    function getDog(name){
    
    if( adoptedDogs.length < maxDogs ){
      adoptedDogs.push( name );
      return true;
    }
    return false;
    }
    
    console.log(getDog('Spot'));
    console.log(getDog('Daisy'));
    console.log(getDog('Chester'));