Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does console.log behave like this?

On the node.js interpreter:-

console.log("A newline character is written like \"\\ n \".");
//output is:-
// A newline character is written like "\ n ".

But when you simply enter this in the node.js interpreter:-

"A newline character is written like \"\\ n \"."
// it prints out:-
//'A newline character is written like "\\ n ".'

Does anybody now why this happened? Just curious to know more about node.js Thanks in advance for your answer.

like image 240
azero0 Avatar asked Mar 22 '15 07:03

azero0


People also ask

What is console log this?

The console. log() is a function that writes a message to log on the debugging console, such as Webkit or Firebug. In a browser you will not see anything on the screen. It logs a message to a debugging console.

How does a console log work?

The console. log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.

Is console log synchronous or asynchronous?

It means that when you invoke `console. log` in a browser it "logs" a reference to an object instead of serialising it. This log is still synchronous, but when you expand it in the console its properties are dereferenced and may be different from when the original log was made.

Why does console log disappear immediately?

This is happening because your form is submitting to itself and the page loads in a fraction of seconds for you to notice the difference. There is 2 way you can solve this in your case. One: Add onsubmit="return false;" attribute in your form element.


1 Answers

When logging a string, it gets fully parsed and every character gets escaped, and that's ok, it is the expected behavior.

Nonethless, displaying a string (not logging), the interpreter tries to show it in the simplest possible form. This will also avoid any misunderstanding for the user who's looking at it. So, basically:

  • Displaying "\"hi\"" will show '"hi"', because you can write a double quote inside a single quote delimited string without escaping it, and it's much easier to read.

  • Displaying '\'hi\'' will show "'hi'", for the same reason.

  • Displaying "\"hi\", 'hey'", with both single and double quotes, will force the interpreter to show you the original string (in the same form you created it), because there's no way to display it wothout escaping either the single or the double quotes, so it can only be shown as "\"hi\", 'hey'".

Try it by yourself:

var a = "\"hi\", 'hey'";
> "\"hi\", 'hey'"

var b = "\"hi\"";
> '"hi"'

console.log(a + ", " + b);
> "hi", 'hey', "hi"
like image 200
Marco Bonelli Avatar answered Oct 07 '22 07:10

Marco Bonelli