Can you explain how this JS code works?

Can you explain how this JS code works?
0

#1

I know what this code does, but I’m not sure how it works. See comments for where my confusion lies.

var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(showPosition); 
        // what does passing a parameter here do?
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";}
    }
    
function showPosition(position) {
// that variable I asked about in a previous line is now used 
// in a function here but I'm not sure why, and what does
// passing a parameter here do? I know it's used below but 
// unsure why
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}

#2

watchPosition(showPosition) passes the variable showPosition (which is the function declared below) to navigator.geolocation.watchPosition (which is a function provided by JS).

function showPosition(position){ ... } this is the callback function that you pass as an argument to watchPosition. watchPosition can then run this function (because it got passed as an argument). showPosition takes in one argument (position).


#3

navigator.geolocation is an object made by Geolocation API. It contains several variable include position.coords.latitude and position.coords.longitude. It’s value in Null unless Geolocation API can find your coordinate