balaphp
balaphp

Reputation: 1326

node.js variable undefined error after using typeof

This is my code

   if((typeof session) !== undefined && (typeof session.username) !== undefined){
        data = session.username+" online";  
        io.sockets.emit('update_common_message',data);

        socketsOfClients[session.username].push(socket.id);
    }

I am getting error

    TypeError: Cannot read property 'username' of undefined

I dont know what is the wrong with my code...

Upvotes: 0

Views: 268

Answers (3)

vmx
vmx

Reputation: 8427

I think, this would suffice, looks cleaner too.

if (session && session.username) {
  data = session.username + " online";
  io.sockets.emit('update_common_message', data);

  socketsOfClients[session.username].push(socket.id);
}

Upvotes: 1

Max Truxa
Max Truxa

Reputation: 3478

Your problem is that typeof returns a string:

if((typeof session) !== 'undefined' && (typeof session.username) !== 'undefined'){
    // ...
}

Upvotes: 1

robertklep
robertklep

Reputation: 203494

typeof returns a string, so you need to test against a string too:

if ((typeof session) !== 'undefined' ...)

Upvotes: 2

Related Questions