Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 686
Bill Avatar asked Oct 26 '16 07:10

Bill


People also ask

What does .log do in JavaScript?

The JavaScript Math. log() function returns the natural logarithm of a number.

Does console log equal print?

Here's a quick lesson for you: In your web browser's devtools, your console. log() does not capture the objects you print when you print them. It captures it when you look at the printout.

How does console log work in JavaScript?

The console. log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.


2 Answers

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.

like image 145
Mulan Avatar answered Oct 28 '22 17:10

Mulan


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`;
like image 42
Bill Avatar answered Oct 28 '22 15:10

Bill