blight231
blight231

Reputation: 33

Getting UNDEFINED at the end of a simple for loop function BEGINNER JAVASCRIPT

const reverseArray = (words) => {
  for (let i = words.length - 1; i >= 0; i--) {
    console.log(`${words[i]}`);
  }
};

const sentence = ['sense.', 'make', 'all', 'will', 'This'];

console.log(reverseArray(sentence))

// Should print ['This', 'will', 'all', 'make', 'sense.'];

const nums = [1, 2, 3, 4, 5];

console.log(reverseArray(nums));

// Should print 5,4,3,2,1

But it keeps giving me Undefined at the end ? I know this is a rookie question , sorry.

Upvotes: 2

Views: 1750

Answers (4)

laurisstepanovs
laurisstepanovs

Reputation: 536

It prints undefined in the end because you are trying to console.log function but it returns nothing there is no need for the console.log you can just call this function.

reverseArray(sentence)
reverseArray(nums)

But better way to reverse an array is to use build-in function reverse() So you can change your function like this.

const reverseArray = (words) => {
  words.reverse().forEach(item => {
    console.log(item);
  });
};

Upvotes: 3

Zunair
Zunair

Reputation: 1195

Your reverseArray function doesn't return an array or anything hence undefined.

And it doesn't reverse your array and does not store it anywhere.

You need to reverse the array into a variable then return it at the end of the function.

Or just use built-in string.reverse() method to reverse the array!

Upvotes: 1

imvain2
imvain2

Reputation: 15847

The problem is without a return, the function is returning nothing, which means undefined. So your console.log(reverseArray(sentence)) call is the same as console.log(undefined).

In this answer, the function just returns the reversed array.

const reverseArray = (words) => {
  reversed = []
  for (let i = words.length - 1; i >= 0; i--) {
     reversed.push(words[i])
  }
  return reversed
};

const sentence = ['sense.', 'make', 'all', 'will', 'This'];

console.log(reverseArray(sentence))

// Should print ['This', 'will', 'all', 'make', 'sense.'];

const nums = [1, 2, 3, 4, 5];

console.log(reverseArray(nums));

Upvotes: 1

Shivam
Shivam

Reputation: 1

Every function in JavaScript returns undefined unless you return something else.

Try:

const reverseArray = (words) => {
  for (let i = words.length - 1; i >= 0; i--) {
     console.log(`${words[i]}`);
  }
  return "" //Here magic occurs
};

const sentence = ['sense.', 'make', 'all', 'will', 'This'];

console.log(reverseArray(sentence))

// Should print ['This', 'will', 'all', 'make', 'sense.'];

const nums = [1, 2, 3, 4, 5];

console.log(reverseArray(nums));

Upvotes: -1

Related Questions