FAQ: Code Challenges: Intermediate JavaScript - convertToBaby()

My code returns the expected array but I cannot move ahead. I get a message saying that my code does not return the expected result but I cannot understand why. Anyone can help?

Code:
let prefix = ‘baby’;
let newArray = ;

function convertToBaby(animals) {
for(let animal of animals) {
newArray.push(prefix + ’ ’ + animal);
}
return newArray;
}

it returns:
[ ‘baby panda’,
‘baby turtle’,
‘baby giraffe’,
‘baby hippo’,
‘baby sloth’,
‘baby human’ ]

Expected output:
// Should return [‘baby panda’, ‘baby turtle’, ‘baby giraffe’, ‘baby hippo’, ‘baby sloth’, ‘baby human’];

As stetim94 mentioned in an earlier post, try calling your function more than once

console.log(convertToBaby(animals))   // Works first time
console.log(convertToBaby(animals))  // Don't get same result as first time

You have declared newArray in the global scope. Every time the function is called, it pushes the entries to the same array. You don’t want the results from different function calls to be collected in the same array.

With that in mind, where do you think let newArray = [] should be placed?

My solutions:
variant 1:

const convertToBaby = (array) => {
  let alteredArr = [];
  for(i=0; i < array.length; i++) { 
    alteredArr.push(`baby ${array[i]}`);
  }
  return alteredArr; 
};

variant 2(with forbidden to use .map() method):

const convertToBaby = (array) => {
  let alteredArr = array.map(ele => {
    return ele = 'baby ' + ele;   
  });
  return alteredArr;
};

The task was not to use the .push() method. Since the .map() method itself returns a new array.
Actually, I spent most of my time writing code with the .map() method. Although it is written in the description of the exercise that it is very convenient to use it >_<

p.s. Stuck for at least an hour with this exercise :slight_smile: In the beginning, not much worked out, but in the end I got a polished code, which I am very happy with

1 Like

Great, got pretty much the same solutions as you! I also did a version with .map (commented out since it wasn’t allowed for the purpose of the exercise):

// Write your code here: const convertToBaby = arr => { const newArr = []; for (let i = 0; i < arr.length; i++) { newArr.push("baby " + arr[i]) } return newArr; } /* const convertToBaby = arr => { const newArr = arr.map(element => { return "baby " + element; }) return newArr; } */ // When you're ready to test your code, uncomment the below and run: const animals = ['panda', 'turtle', 'giraffe', 'hippo', 'sloth', 'human']; console.log(convertToBaby(animals))

I don’t understand, why does .push add the string 'baby before each array element? I thought that .push added at the end of an array and that .unshift added at the beginning. I tried to use .unshift and I noticed that the array gets printed by in reverse order starting with ‘baby human’ rather than ‘baby panda’.
Help please? :sweat_smile:

The push method adds the element to the end of the array, whereas the unshift method adds the element to the beginning of the array. For Example,

let arr = ["a", "b", "c"]

arr.push("X");

console.log(arr);
// [ 'a', 'b', 'c', 'X' ]
// Element added to end of array

arr.unshift("Y");

console.log(arr);
// [ 'Y', 'a', 'b', 'c', 'X' ]
// Element added to beginning of array

If you loop over an array, do some stuff to each element and then add to another array via the unshift method, then you are going to end up with a reverse ordering.

let arr = ["a", "b", "c"];
let result = [];

for (letter of arr) {
    result.unshift(letter);
    console.log(result);
}

// [ 'a' ]
// [ 'b', 'a' ]
// [ 'c', 'b', 'a' ]

As for why you are seeing "baby panda" instead of "panda baby", that doesn’t have anything to do with your choice of push or unshift method. Rather, it has to do with how you are creating the new string.

animal = "panda"
word = "baby"

stringOne = word + " " + animal
console.log(stringOne)
// "baby panda"

stringTwo = animal + " " + word
console.log(stringTwo)
// "panda baby"
1 Like

Oh My God thank you so much for taking the time to explain this to me in detail :smiley:

I feel silly for having spent so much time trying to figure out why I was getting “baby panda” rather than “panda baby” and I kept looking at the reason in the wrong place :frowning_face:

About the unshift producing a reversed array, does it happen every time we do something inside the loop to that array?

Thank you again!

Suppose we are iterating over the elements of an array and adding them to another array.

If we are adding the elements via the push method, then in each iteration of the loop, the element we are iterating over will be added to the end of the array. So, the original order will be preserved. For example,

let arr = ["a", "b", "c"]
let numArr = [1, 2, 3, 4]

for (let element of numArr) {
    arr.push(element)
}

console.log(arr)
// [ 'a', 'b', 'c', 1, 2, 3, 4 ]

If we are adding the elements via the unshift method, then in each iteration of the loop, the element we are iterating over will be added to the beginning of the array. So, the original order will be reversed. For example,

let arr = ["a", "b", "c"]
let numArr = [1, 2, 3, 4]

for (let element of numArr) {
    arr.unshift(element)
}

console.log(arr)
// [ 4, 3, 2, 1, 'a', 'b', 'c' ]

Perhaps a visual may help you step through the loops and see what is happening.

  • Go to https://pythontutor.com/javascript.html

  • Copy & Paste the first code in this post (the one with push) into the editor and click the “Visualize Execution” button.

  • Keep clicking the “Next” button till you reach the end of your code. In particular, pay attention to how the elements are being pushed to the arr array.

  • Now do the same with the second code in this post (the one with unshift). In particular pay attention to how the elements are being added to the arr array and why this causes the reverse order.

Hi,I 've been trying to understand why in previous exercise greetAliens() the code does not result in an undefined, but it does here when using the same method:

Code resulting in right answers but undefined at the end:

const convertToBaby = (arr) => {
for (let i = 0; i < arr.length; i++)
console.log(Baby ${arr[i]})


Code for greetAliens() resulting with right answers with NO undefined after it logs

const greetAliens = (arr) => {
for (let i = 0; i < arr.length; i++) {
console.log(
Oh powerful ${arr[i]}, we humans offer our unconditional surrender!
);
}
};

// When you’re ready to test your code, uncomment the below and run:

const aliens = [“Blorgous”, “Glamyx”, “Wegord”, “SpaceKing”];

greetAliens(aliens);

When you post code directly into the forums, the code loses formatting and some characters can go missing (such as the backticks in your console statements). To preserve code formatting in forum posts, you can use the </> button (See [How to] Format code in posts for more details).

You haven’t posted how the function call to the convertToBaby function is being made. Both the convertToBaby and greetAliens functions will return undefined. As mentioned in the documentation (Functions - JavaScript | MDN (mozilla.org)),

By default, if a function’s execution doesn’t end at a return statement, or if the return keyword doesn’t have an expression after it, then the return value is undefined.

Since neither of the above functions has an explicit return statement, so the return values of both functions will be undefined.

As for why you are seeing undefined being logged for one function and not the other, it is most likely due to how you are calling the functions.

// VERSION A
// Will execute functions with the return value not being logged
convertToBaby(someArray) 
greetAliens(someArray)

// VERSION B
// Will execute functions AND then the return value will be logged
console.log(convertToBaby(someArray))  // undefined will be logged at end 
console.log(greetAliens(someArray)) // undefined will be logged at end

In both Versions A and B, the return values of the functions are the same i.e. undefined.
The only difference is that in version A, we aren’t using a console.log statement or assigning the return value to a variable, so we are ignoring the return value.
In version B, we are nesting our function call in a console.log statement, so the undefined gets logged to the console.

Thank you for showing me how to properly post! I was a little intimidated to post and or ask questions.

Yes, I see how by using console.log() as oppose to calling on the function determines undefined.

on convertToBaby() the code that produced undefined was:

for (let i = 0; i < arr.length; i++)
console.log(`Baby ${arr[i]}`)
}

const animals = ["panda", "turtle", "giraffe", "hippo", "sloth", "human"];

console.log(convertToBaby(animals))```

![Screenshot 2024-02-13 at 10-12-20 Practice JavaScript Syntax Arrays Loops Objects Iterators Codecademy|619x500](upload://6HPMBCjNJ301XBc4gltTdJr12Yb.png)

when I changed `console.log()` and just called on function it did the trick, again thank you for your help!
1 Like