This question already has answers here:
Backticks (`…`) calling a function in JavaScript
(3 answers)
Closed 6 years ago.
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?
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.
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`;
Related
This question already has answers here:
Template String As Object Property Name
(3 answers)
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 3 years ago.
How do I use template literal as key inside object literal?
The following code:
{
`${id}_name`: "John Doe",
`${id}_age`: 27,
}
Produces a syntax error:
Uncaught SyntaxError: Unexpected token :
Is there something I'm missing, or is this not supported? If not, is support for this feature planned?
And of course I come up with a solution straight away:
{
[`${id}_name`]: "John Doe",
[`${id}_age`]: 27,
}
Wrap the template literal in square brackets. This will evaluate the expression in between the square brackets and use it as the key.
Without square brackets, only identifiers (e.g. my_key_name), single or double quote strings (e.g. "My Key Name") and numbers (e.g. 42) can be used.
Your answer is correct, but i will try to answer the why of it.
If we refer to the Ecmascript object definition, it is said
Properties are identified using key values. A property key value is either an ECMAScript String value or a Symbol value. All String and Symbol values, including the empty String, are valid as property keys. A property name is a property key that is a String value.
In this case, a ECMAScript string is defined as
A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), and U+000A (LINE FEED).
Which mean a string has to be unicode caracter enclosed in single or double quotes. And Object keys must be ECMAScript string or Symbol, which i assume are index.
A template literal is a ECMAScript string but an ECMAScript string is not a template literal.
P.S. Take this with a grain of salt, i'm not an ECMAScript expert but that's what i could find.
This question already has answers here:
How to add spaces between every character in a string?
(4 answers)
Closed 3 years ago.
How can i convert a text like Test to T e s t I know It can probably be done with regex but i don't understand how
I've, Quite new to javascript, in python (Which i quite understand) It can be done with a for loop something like
print(" ".join(a for a in "Test"))
But join works differently in javascript and only works for arrays (lists) if i'm right
I've also tried using replace but it does nothing
console.log("Test".replace(""," "))
console.log("Test".replace(""," "))
"Test".split("").join(" ")
// or
[..."Test"].join(" ")
Thats it. You can't do that with .join directly as that only accepts a string.
JS doesn't support generator expressions, and join is an array method that takes the joiner not a string method that takes an iterable. The closest equivalent to your Python code would be
console.log(Array.from("Test").join(" "))
Using Array.from (converting the iterable string to an array) over .split("") has the advantage that it doesn't break unicode characters that consist of multiple code points apart.
This question already has answers here:
What do the brackets around the arguments mean when reading documentation for a method? [duplicate]
(3 answers)
Closed 4 years ago.
I am using criso validator.js, of user Input,
but it Eslint is showing error in syntax on this lines
if (!Validator.isAlphanumeric([(data.password,'en-US')])) {
console.log(" Not an alphanumeric");
}
how to properly check user's entered password is Alphanumeric,
I know we can do it using regex but I wanted to do it by using their provided syntax as isAlphanumeric(str [, locale]).
here is their documentation screenshot of code.
The square brackets in the isAlphanumeric(str [, locale]) notation are not related to JavaScript Array literals. Instead, they denote that when calling isAlphanumeric, the first argument str (in your case, data.password) is required, and the second argument locale is optional.
In your case, you do want to pass in a locale. Here is how that would look:
if (!Validator.isAlphanumeric(data.password, 'en-US')) {
console.log("Not an alphanumeric");
}
In technical documentation, square brackets ([]) generally denote that an argument is optional. Tecnhnically this is just a convention (and probably comes from Unix CLI Usage Messages), but in my experience is so widely used that always interpreting square brackets as denoting an optional argument is usually a safe assumption to make.
This question already has answers here:
JavaScript braces on new line or not? [closed]
(9 answers)
Closed 5 years ago.
I was used in this type of convention of indentation and curly brackets placement in college.
function code()
{
if(code)
{
code
}
}
but online tutorials in javascript tells me to do this style instead
function code(){
if(code){
code
}
}
this first one is also my preferred style because it is more clear and understandable. My question is why do I have to follow the second example? is there any advantages??
The official answer is that you can use either, but the practical answer is that it is safer to use the version where the opening curly brace is on the same line as the code block it defines.
In JavaScript, {} is the syntax for an object literal and JavaScript also has automatic semi-colon insertion. This automatic semi-colon insertion can cause functions written with the opening curly-brace on a different line than the function it defines the body of, to execute differently than you would expect. See this for details:
Why do results vary based on curly brace placement?
Mostly preference. I personally prefer the second way, but the only difference is when javascript's automatic semicolon insertion kicks in. There is no difference when dealing with function declarations or if statements.
This question already has answers here:
How can I use backslashes (\) in a string?
(4 answers)
Closed 6 years ago.
Is there anyway to do this in JavaScript:
$ cat test.json
{"body":"\u0000"}
$ python3 -c 'import json; print(json.load(open("test.json", "r")))'
{'body': '\x00'}
Notice, the data above only one \ (does not need to be escaped). So you have the following situation in JavaScript:
JSON.parse('{"body":"\\u0000"}') // works
JSON.parse('{"body":"\u0000"}') // does not work
With potentially any UTF-8 data comming from a binary source (websocket), can this data be processed directly like in the first python example above?
String characters from \u0000 through \u001F are considered as control characters, and according to RFC-7159 are not allowed characters to use in JSON and must be escaped, as stated in section 7.
What you are trying to do is to put unescaped control characters into a JSON, which clearly not acceptable, you have to escape it first, non of the languages accept it, even Python.
The correct answer would be place a UTF-8 encoded value into a string containing a JSON format.
This is a correct JSON, and will be parsed by any JSON parser in any language, even in JavaScript:
{"body":"\u0000"}
This is incorrect JSON (consider the [NUL] as a NUL control character, as it cannot be represented in text):
{"body":"[NUL]"}
That's why JSON.parse('{"body":"\\u0000"}') works and JSON.parse('{"body":"\u0000"}') doesn't.
Hope, it clarifies what's wrong with your test.