Javascript. Cómo funcionan las comillas invertidas (``)

Descubre los principales usos de las comillas invertidas en Javascript

Photo by Nhu Nguyen on Unsplash
`some text`

Concatenar e interpolar strings

const name = 'Gerardo';
const surname = 'Fernández';
const telephone = '123 123 123';
// "Old syntax"const userInfo = 'User info: ' + name + ' ' + surname + ' ' + telephone;// "New syntax"const userInfo = `User info: ${name} ${surname} ${telephone}`;
const user = getUserFromApi(); 
// "Old syntax"const userInfo = 'User info: ' + user.getName() + ' ' + user.getEmail();// "New syntax"const userInfo = `User info: ${user.getName()} ${user.getEmail()}`;

No es necesario escapar los caracteres “ y ‘ mediante \

const foo = 'Can\'t connect to the server';const bar = `Can't connect to the server`;
const foo = "Error: \"Introduce a valid email\"";const bar = `Error: "Introduce a valid email"`;

Strings en varias líneas

const html = "<article>
<h1>Article title</h1>
</article>";
SyntaxError: "" string literal contains an unescaped line break
const html = "<article> \
<h1>Article title</h1> \
</article>";
const html = '<article>' +
'<h1>Article title</h1>' +
'</article>';
const html = `<article>
<h1>Article title</h1>
</article>`;
const string = `First line
Second line`
First
Second

Tagged templates

// Apollo queryconst query = gql`
query {
...
}

// Styled components
const Container = styled.div`
width: 1000px;
background: red;
`;
<div style="width: 1000px; background:red">
...
</div>
function foo() {
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments[2]);
}
const varOne = 'bar';
const varTwo = 'zeta';
foo`This is bar: ${varOne} and zeta: ${varTwo}`;
["This is bar: ", " and zeta: ", ""] (array)
bar (string)
zeta (string)
function foo(literals, ...expressions) {
console.log(literals);
console.log(expressions[0]);
console.log(expressions[1]);
}
const name = 'Gerardo';
const email = 'info@mail.com';
console.log(i18n`Hi ${name}, your email is ${email}`);// Hola Gerardo, tu email es info@mail.com

Conclusiones

¿Quieres recibir más artículos como este?

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store