javascript console.log new feature with 'raw'? [duplicate]
Asked Answered
P

2

8

I have encounter this example and was completely lost...

const test = (hey) => console.log(hey);

console.log(test `wtf`); 

First all this is valid, in the console.log, it appear to be

["wtf", raw: Array[1]]

It's like the function is been executed and with extra raw? can someone please explain?

Pustulate answered 26/10, 2016 at 7:34 Comment(4)
console.log(test "w**f"); ?Iodine
developer.mozilla.org/tr/docs/Web/JavaScript/Reference/… I suppose it is string templaterZarah
Tagged template strings: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Tenney
@anant You've censored the "t"…?Tenney
H
6

It's just a Tagged Template Literal. It looks fancy, but there's nothing too special about it. Note, they're part of ES6/ES2015 so you will need to tranpsile them if you plan on supporting older browsers.

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 / ES6 specification.

Habsburg answered 26/10, 2016 at 7:45 Comment(0)
P
3

credit to @karmuran and @deceze

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals

Raw strings

The special raw property, available on the first function argument of tagged template literals, allows you to access the raw strings as they were entered.

function tag(strings, ...values) {
  console.log(strings.raw[0]); 
  // "string text line 1 \n string text line 2"
}

tag`string text line 1 \n string text line 2`;
Pustulate answered 26/10, 2016 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.