javascript - Why does console.log behave like this? - Stack Overflow

On the node.js interpreter:-console.log("A newline character is written like "\ n ".&

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.

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.

Share Improve this question asked Mar 22, 2015 at 7:20 azero0azero0 2,3104 gold badges22 silver badges33 bronze badges 1
  • May be it is because when a string is parsed by the piler. It behaves differently in the both cases. @azero0 . But it gives the same output in pure-Javascript. Nice check, may be the piler does not parse the string datatypes as same as pared to the console.log()'s string. Good Question – Asif Mehmood Commented Mar 22, 2015 at 8:00
Add a ment  | 

1 Answer 1

Reset to default 6

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"

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745560585a4633084.html

相关推荐

  • javascript - Why does console.log behave like this? - Stack Overflow

    On the node.js interpreter:-console.log("A newline character is written like "\ n ".&

    19小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信