0

I wanted to have a console log of each socket message being sent down to the server, so I quickly wrapped socket.io's socket.emit function

    var self = this;
    this.socket = io.connect();

    this.socket._emit = this.socket.emit;
    this.socket.emit = function(){
        console.log(...arguments[0]);
        self.socket._emit(...arguments);
    };

It works fine except for some bizarre console log printing. This happens on Chrome and Firefox. What is going on?

enter image description here


I did fix this by using arguments[0] instead of ...arguments[0] but I'm still curious..

3
  • 1
    I suspect you have a string encoded as UTF-16 Commented May 6, 2017 at 21:57
  • Can you further explain what that means in this context? Commented May 6, 2017 at 22:06
  • My guess was incorrect. I didn't know about the spread syntax. Full answer coming. Commented May 6, 2017 at 22:23

1 Answer 1

3

The spread syntax when used as the argument to a function call breaks the single string value into separate arguments for each character. The example below should make it clear.

var str = "abc";
console.log(str);         // abc
console.log(...str);      // a b c
console.log("a","b","c"); // a b c

var ary = [...str];
console.log(ary);         // (3) ["a", "b", "c"]

showArgs(...str);
function showArgs(x, y, z){
  console.log(x); // a
  console.log(y); // b
  console.log(z); // c
}

Why were you using console.log(...arguments[0])? What did you hope/expect to happen by using the ... there?

Sign up to request clarification or add additional context in comments.

1 Comment

I used ... to pass to the original function's implementation, and used it to print the arguments without thinking about it. It's still surprising because hovering over the ... object shows the string as a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.