How to return the value of a function variable

I'm finishing a carousel and I want to separate the codes. I need to return the value of a function variable and I don't understand. When I put a value in 'return', it returns, but the value of the variable does not. I'll just post more important parts of the code and try to explain

This is the first function, which changes images. The function I'm calling is to return the position of the button within the array. This array is the 'buttons' variable.

const buttons = document.querySelectorAll('.carousel-button');
function moveSlider() {
  buttons.forEach(element => {
    element.addEventListener('click', (event) => {
        var buttonId;
        var carouselId;
        var btnPosition

        var id = event.target.id;
        buttonPosition(id)
        console.log(buttonPosition())
...

The Function I'm calling up there

function buttonPosition(id){
  var position;
  for($i = 0; $i < buttons.length; $i++){
      if(id == buttons[$i].id){
          position = $i;
      }
  }

  return position;
}

Why does the variable value return 'undefined'?

1 answer

  • answered 2020-10-29 22:26 polarfuchs

    You are first calling the method with the parameter "id". But when you you use console.log your calling the method again but without the parameter. You should store the returned value of the function in a variable and then work with the or for example output the variable.

    var yourReturnValue = buttonPosition(id)
    console.log(yourReturnValue)