1

I am new to javascript and I try to make a simple game with level. But my code doesn't running like I want. I see many questions on the forum like my problem but I don't understand thanks to them why my function doesn't return anyhting. Can you explain me why, and not only give me the solution. Thanks !

function level()
{
    var SquareNbrLevel;
    var levelBtn = document.querySelectorAll(".level-btn"); //Select all levels button

    for(var i = 0; i < levelBtn.length; i++)
    {
        levelBtn[i].addEventListener("click", function()
        {
            if(this.textContent === "Easy")
            {

                SquareNbrLevel = 3;
                console.log("easy " + SquareNbrLevel);
                return SquareNbrLevel;

            }
            else
            {
                SquareNbrLevel = 6;
                console.log("hard " + SquareNbrLevel);
                return SquareNbrLevel;
            }

        });
    }

}


var nbr  = level();
console.log("Level" + nbr);
1
  • why are you trying to return a value from a click handler? leve() gets called before your click events fire Commented Jun 14, 2020 at 10:31

4 Answers 4

2

You function attaches click listeners to HTML elements and returns nothing.

Here's a simplified version and you probably see it:

function level()
{
    var SquareNbrLevel;
    var levelBtn = document.querySelectorAll(".level-btn"); //Select all levels button

    for(var i = 0; i < levelBtn.length; i++)
    {
        levelBtn[i].addEventListener("click", clickListenerFunction);
    }

}

I've replaced the listener (callback) with a name and now we see that the level function itself does not return anything.

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

2 Comments

Sorry but I don't understand what are you trying to tell me
You wonder why your level function returns nothing and this shows it: the level function has no return statements. The click handler functions do have some, but they are different functions. What result did you expect from calling the level function?
1

Event handlers should run after the DOM elements are ready. It doesn't make sense to have them process when level() is called to get the level.

Your level function wasn't returning anything. Hence undefined. And you were calling the level function before a level was set, which also doesn't make sense.

Your attempts to return a value were returning inside the click handler function, which does not affect the level() function itself.

Simple example that uses a global variable to store the level.

var SquareNbrLevel;

function level() {
  return SquareNbrLevel;
}

var levelBtn = document.querySelectorAll(".level-btn"); //Select all levels button
for (var i = 0; i < levelBtn.length; i++) {
  levelBtn[i].addEventListener("click", function() {
    if (this.textContent === "Easy") {
      SquareNbrLevel = 3;
      console.log("easy " + SquareNbrLevel);
    } else {
      SquareNbrLevel = 6;
      console.log("hard " + SquareNbrLevel);
    }

  });
}


document.getElementById('level').addEventListener("click", () => {
  var nbr = level();
  console.log("Level" + nbr);
});
<button class="level-btn">Easy</button>
<button class="level-btn">hard</button>

<button id="level">level</button>

Comments

0

You can use promises.

function level()
{
promise = new Promise((resolve, reject) => {
  var SquareNbrLevel;
    var levelBtn = document.querySelectorAll(".level-btn"); //Select all levels button

    for(var i = 0; i < levelBtn.length; i++)
    {
        levelBtn[i].addEventListener("click", function()
        {
            if(this.textContent === "Easy")
            {

                SquareNbrLevel = 3;
                console.log("easy " + SquareNbrLevel);
               resolve( SquareNbrLevel);

            }
            else
            {
                SquareNbrLevel = 6;
                console.log("hard " + SquareNbrLevel);
                resolve( SquareNbrLevel);
            }

        });
    }

});
   return promise 
}


level().then(nbr=>{
console.log("Level" + nbr);
});

Comments

0

The thing is you're not returning anything from level function. If you return something like this, you'll see the value. By default, a function returns undefined in Javascript.

What you perceive as being returned in if..else block is happening in method that handles click event for these levelButtons. They occur only when any of these is clicked plus the returned values from this function is not utilised anywhere to see.

function level()
{
    var SquareNbrLevel;
    var levelBtn = document.querySelectorAll(".level-btn"); //Select all levels button

    for(var i = 0; i < levelBtn.length; i++)
    {
        levelBtn[i].addEventListener("click", function()
        {
            if(this.textContent === "Easy")
            {

                SquareNbrLevel = 3;
                console.log("easy " + SquareNbrLevel);
                handleClick(SquareNbrLevel);

            }
            else
            {
                SquareNbrLevel = 6;
                console.log("hard " + SquareNbrLevel);
                handleClick(SquareNbrLevel);
            }

        });
    }
  return " something cool"

}
   
   var currentSquareNbrLevel = ""
function handleClick(SquareNbrLevel){
 currentSquareNbrLevel = SquareNbrLevel;
  alert(SquareNbrLevel)
}
var nbr  = level();
console.log("Level" + nbr);

4 Comments

I understand but when I click on easy button, the function doesn't return the SquareNbrLevel. I want that my function return SquareNbrLevel variable
@RonyCohen that's because the click handler only executes when click on it. You're not catching the returned value.
So why after I click on a button level I don't see anything on my console webpage if i capture the return function in variable ?
You should be able to see the console.log part if you do it correctly. And you can call another function from there to get the latest SquareNbrLevel something as I did in the updated code

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.