Insert items in a blank array

Can someone please tell me, what am I doing wrong here?

I want to insert new items in the array.

var fruits = [];

function enterRecords (fruit) {
	"use strict";
		if (fruits === ''){
			 return fruits.push(fruit);
		}else{
			return 'records already updated';
		}
};

console.log(enterRecords('Kiwi'));

You are checking whether fruits is an empty string, but fruits is an array. It will never be an empty string.

		if (fruits === ''){
			 return fruits.push(fruit);

If the fruits array is an empty string, then push fruit onto it?

You can push onto an empty array, so why are you using the if?

Thank you. I can see the problem but what’s the solution?

It depends on what you are trying to do, but in this case you do not want to compare an array is a string.

I want to check if this array is empty, and if it is, insert the new item in the array.

Ok. Then your if statement needs to change to whether the array is empty.

Are you sure that you only want to push onto the array if the array is empty? In that case you would only ever add at most one thing to the array.

Yes, that’s correct. I am just trying to understand how array works in real code.

var fruits = [];

function enterRecords (fruit) {
	"use strict";
		if (fruits.length === 0){
            fruits.push(fruit);
			return fruits;
		}else{
			return 'records already updated || you entering empty string';
		}
}

console.log(enterRecords("test"));

check the length of the array, if length is 0 it means the array is empty.

You wouldn’t usually prevent more that one total element from being in an array - that defeats the purpose of an array.

But, one typical way to check if an array is empty is to check if it has length of 0.

1 Like

It is great that you can solve the problem, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

Yes! that’s works like a charm. Thank you.

1 Like

Understood. Thank you so much.

Sorry, I was not aware of this, will take care! Thanks for letting me know : )