Websocket data undefined outside onmessage block

Hello. I’m not able to use the data from the websocket because it is undefined. I have a variable called data and I initialize it with the json from the websocket. It is displayed in the console inside the client.onmessage block but when I try to use it below I get this error: Uncaught TypeError: Cannot read properties of undefined (reading ‘BEST’) . How could I solve not to have the data undefined?

const client = new W3CWebSocket("wss://host.net");

var dataFromServer;

client.onopen = () => {
  var sendData = {
    eventId: "16",

  console.log("WebSocket Client Connected!");

client.onmessage = function (message) {
  dataFromServer = JSON.parse(message.data);
  console.log("got reply: ", dataFromServer);

client.onerror = function () {
  console.log("Connection Error");

console.log(dataFromServer); // undefined

var best = dataFromServer.BEST.slice(0, 3); // Uncaught TypeError: Cannot read properties of undefined (readning 'BEST')

Please post your actual code instead of a picture. Thanks

Sorry, I edited it should work now.

1 Like

Where are you assigning data the value or anything it is just use to console log and access the value without any assignments

You might be meaning to use dataFromServer

I named it wrong, not it should be correct but the issue is still the same.

Json.parse is unnecessary,just console log the message

It is already a object at that point

Yeah, but thats not the problem I can see the data in the console. The problem is the 2nd console.log

The code inside the callback runs when an event is fired. The code outside the callback runs immediately and at that time the variable has not been assigned anything so it’s undefined. Use the data inside the callback directly, or pass it to a function.

Simple click handler example:

<button>Click me</button>
let outsideScope;

  .addEventListener("click", ({ currentTarget }) => {
    // Runs when the event fires
    outsideScope = currentTarget.textContent;
    console.log("outsideScope inside callback", outsideScope);

// Runs before the event fires
console.log("outsideScope outside callback", outsideScope);

// 1. outsideScope outside callback undefined
// 2. outsideScope inside callback Click me
1 Like

How can I use it directly or pass it to a function? Could you show my through my example?

The console.log inside the callback is an example of direct usage. For the function usage, you just call the function and pass it an argument then use that inside the function.

client.onmessage = function (message) {
  const best = message.data.BEST.slice(0, 3);

function logBest(data) {

I tried this but I get this error message in the console: Cannot read properties of undefined (reading ‘slice’)

Log out the data you get back (message) and make sure you know what the data looks like. In all likelihood, it just means you are not accessing the correct properties.

Yeah, there are 3 separate messages in JSON but the first one does not have the BEST value, could this be the problem right? Is there a way chekc if the value not present then do nothing or have a default instead?

Have you done the freeCodeCamp JS curriculum? If not I would highly suggest you do so as you would learn what you need for this.

There are a few ways you can check it, if the property is not on the object it will be undefined and that is a falsy value.

const best = message.data.BEST ? message.data.BEST.slice(0, 3) : 'default value'

[Object.prototype.hasOwnProperty() - JavaScript | MDN](for checking property)

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