One of the key features of const
in JavaScript
is that the const
variable cannot be redeclared.
However, in this code that is grabbed from this link:
signalServer.on('discover', (request) => {
const clientID = request.socket.id // clients are uniquely identified by socket.id
allIDs.add(clientID) // keep track of all connected peers
request.discover(Array.from(allIDs)) // respond with id and list of other peers
})
Every time a new client connects to the server via a socket, a new const clientID = request.socket.id
is created.
So the clientID
variable is created more that one time even though it is a const
.
How is that possible?
A variable name can only exist once in a scope. (Redeclaring one with var
doesn't cause an error, doing so with let
and const
does).
Each call to a function creates a new scope.
There's still only one instance of that variable in that scope.