I have the following function from another SO answer that fetches a local IP address. I output the local IP twice, once in the function, and I also try to output the value where the function is called:
function getLocalIP () {
  window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection
  var pc = new RTCPeerConnection({iceServers: []})
  var noop = function () {}
  var localIP
  pc.createDataChannel('')
  pc.createOffer(pc.setLocalDescription.bind(pc), noop)
  pc.onicecandidate = function (ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate) return
    localIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1]
    console.log(localIP)
  }
  return localIP
}
console.log(getLocalIP())
This outputs:
undefined
192.168.0.1
I mostly understand why this is happening. JavaScript is asynchronous so getLocalIP is returning the value when it is still undefined.
How can I work with this to get the behaviour I expect from a synchronous background? I come from a Python background where I would expect the code above to return the defined variable.
