Why doesn't ${variable_name} work with socket.io?

Tell us what’s happening:
I wrote this code:

socket.on("connect", () => {
  console.log('The following user connected (client-side msg): ',socket.id);
  displayMessage('You connected with id: ${socket.id}')
});

function displayMessage(message) {
  const div = document.createElement("div")
  div.textContent = message
  document.getElementById("message-container").append(div)
}

In theory, ${socket.id} should be shown as a variable, but the computer shows it as string. Furthermore, when I look at the preview I see this on connection to the server:
image

Instead of ${socket.id} I want to display the actual socket.id

What should I do?

P.S: my html.index file looks like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Secure Real-Time Multiplayer Game</title>
    <meta
      name="description"
      content="An example for the fCC InfoSec Secure Real-Time Multiplayer Game project"
    />
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="../public/style.css" type="text/css" />
    <link href="https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap" rel="stylesheet">
    <script src="/socket.io/socket.io.js"></script>
  </head>
  <body>
    <header>
      <h1>Secure Real Time Multiplayer Game</h1>
    </header>
    <hr style="margin: 25px" />
    <div class="container">
      <div id="message-container"></div>
      <canvas 
        ref="game"
        id="game-window" 
        width="640" 
        height="480"
      >
      </canvas>
    </div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
    </script>
  </body>
  <script src="../public/game.mjs" type="module"></script>
</html>

Your code so far
https://replit.com/@jaimeggb/secure-real-time-multiplayer-game#public/game.mjs

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36

Challenge: Secure Real Time Multiplayer Game

Link to the challenge:

The first thing I see is that you are using single quotes, which means this is a string literal.

Template strings are surrounded by backticks. `

Your suggestion worked, thank you. What is the difference between a template string and a string literal?

A string literal is a plain old regular string.

"Hello World"

A template string allows you to evaluate JavaScript within a string and insert the resulting value.

const name = "jaimeggb";

`Hello ${name.toUpperCase()}.` // Hello JAIMEGGB.
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.