0

I have gone through this Question and Answer While loop inside while loop JavaScript

function getMaxLessThanK(n, k) {

  let i = 1;

  while (i < n) {
    let j = i + 1;
    while (j < n + 1) {
      console.log(i, j)
      j++
    }
    i++
  }
}

when n = 5, what am I getting is

1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
undefined

How to avoid this the last line undefined. what is the reason for it?

Can anyone help on this please?

Edit:

This is what the actual thing I am doing below.

enter image description here

5
  • is it from this code block or someplace else your using this function which is printing this Commented May 22, 2022 at 5:45
  • Do you also log the result of the function call? Like console.log(getMaxLessThanK(5))? Your function returns undefined. Commented May 22, 2022 at 5:45
  • No, I my self wrote this code while trying to solve one of the HackerRank Question Commented May 22, 2022 at 5:46
  • @Ram yes, exactly, n =5, k=4, console.log(getMaxLessThanK(n) Commented May 22, 2022 at 5:47
  • 1
    So this is because you are logging the returned value of the function which is undefined. This is the answer you are looking for. undefined is not an unexpected value. Commented May 22, 2022 at 5:51

1 Answer 1

2

If you're running it in a console and get an undefined like this:

enter image description here

This undefined indicates that your statement runs without returning a value. It's not a result of your console.log.

If you make the function return something:

function getMaxLessThanK(n, k) {

  let i = 1;

  while (i < n) {
    let j = i + 1;
    while (j < n + 1) {
      console.log(i, j)
      j++
    }
    i++
  }
    return 'return value';
}

Then you'll get

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You. I got the concept with your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.