I have these two blocks of code.
socket.on('chatMessage', function(message) {
message.type = 'message';
message.created = Date.now();
message.username : socket.request.user.username;
});
socket.on('disconnect', function() {
io.emit('chatMessage', {
type: 'status',
text: socket.request.user.username + ' left the conversation.',
created: Date.now(),
username: socket.request.user.username,
});
});
If i change :
or =
to other, Webstorm gives me error.Expression statement is not assignment or call.
Could someone explain why this happens? Thanks in advance.
Your first block of code is defining a function block. Your second block of code is defining an object definition. There is different syntax allowed for each and you have to use the appropriate syntax to match the context.
Your first block of code is just executing a series of statements in a function block. The {
at the end of this line:
socket.on('chatMessage', function(message) {
defines the beginning of a function block. Thus, Javascript is looking for statements that are legal in that context. Each line of code there needs to be a legal Javascript statement. And,
message.username : socket.request.user.username;
is not a legal statement in that context. If you were trying to assign a value to message.username
, then the valid syntax for that would be:
message.username = socket.request.user.username;
In your second block, you are in the middle of an object definition. The {
at the end of this line:
io.emit('chatMessage', {
starts an object definition. As such, the legal syntax for defining a property on that object looks like this:
username: socket.request.user.username,
So, there are two keys here:
Recognizing when a {
signifies the start of a function block vs. the start of an object definition. Your first code block starts a function body, the second starts an object definition.
Knowing the difference between syntax allowed in a function block and syntax allowed in an object definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With