-2

Basically, I want to organize my code better by creating function definitions wherever I can. When I try to create a new function outside the current scope and return that, it will say x and y are not defined.

I know it's definitely something to do with scoping. Is there anything I can do to organize my code like in the 2nd code paragraph below? Or do I have to declare my functions in the right scope.

# Works
function RandomFunction() {
    x = 1;
    y = 1;
    marker.addEventListener('click', function(x, y) {
        return function() {
            console.log(x+y);
        }
    }
}

# Not working
function RandomFunction() {
    x = 1;
    y = 1;
    marker.addEventListener('click', function(x, y) {
        return add;
    }
}

function add() {
    console.log(x+y);
}
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
Valachio
  • 1,025
  • 2
  • 18
  • 40
  • 1
    Have a look at [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – JanS Jan 04 '18 at 20:46
  • Your click handler returns a function? How does that returned function get executed? I'd be very surprised if your working example actually did work. – xdumaine Jan 04 '18 at 20:50
  • The `addEventListener` callback does not take numerical arguments (x, y). – trincot Jan 04 '18 at 20:52
  • Sorry the code may not work. I just wrote up some quick code to demonstrate my coding issue. @xdumaine – Valachio Jan 04 '18 at 20:56

2 Answers2

1

The function add needs to have each number passed in as parameters(firstNum, secondNum).

The function RandomFunction can declare x and y as variables above the event listener scope. Then when the click event is activated, x and y from the RandomFunction scope will be passed to the add function where the add function can reference those values as firstNum and secondNum.

Also, there is no need to return the function "add" within the click event's callback function.

function RandomFunction() {
    var x = 1;
    var y = 1;

    marker.addEventListener('click', function() {
        add(x, y);
    });
}

function add(firstNum, secondNum) {
    console.log(firstNum + secondNum);
}

RandomFunction();
Akyuna Akish
  • 147
  • 1
  • 7
1

I am not sure what you want to accomplish, but if you want to return a function that "sees" your x,y and can operate on them here it is :

function RandomFunction() {
  var x = 1;
  var y = 1;
  marker.addEventListener('click', function() {  
    // (add(x, y))(); this will give you 2 in console
    return add(x, y); // this will return a function that when you execute it will give 2 as result
  })

}

function add(x, y) {
  return function() {
    console.log(x + y);
  }
}
RandomFunction();

I am not sure what you want to do, but this will return a function that has access to your x,y when marker is clicked.

ThanosSar
  • 532
  • 6
  • 20