In your case it works because you are running it on a single node. If you ran on multiple nodes, "localhost" would resolve to the IP of each node separately and they would not know about each other’s existence since the job script, once launched by SLURM, executes the same job script for each of the allocated nodes. Once SLURM launched the job from the queue, SLURM_JOB_NODELIST contains IPs of nodes that were allocated to the job; piping its content to head -n 1 simply gives the IP of the first allocated node in the list and sets it as master.
Port number can be set random and will be okay unless you are unlucky and some other process or SLURM user uses that random port number.