D
D
Denis Bukreev2016-12-23 20:05:42
JavaScript
Denis Bukreev, 2016-12-23 20:05:42

Can conditions be met in multiline text output?

The question arose.
In ES6, text can be displayed on multiple lines using ` таких `quotes.
Variables in them are written through the construction: ${переменная}.
Is it possible to write some other code inside these quotes, such as conditions or loops?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
riot26, 2016-12-23
@denisbookreev

You can use the ternary operator and functions that return strings:

var a = 'Alice';
var b = 'Bob';
var is_alice = true;
console.log(`Hello, ${is_alice ? a : b}`);
//Hello, Alice

var fruits = ['apple', 'lemon', 'cherry'];
console.log(`Fruits list: ${fruits}`);
//Fruits list: apple,lemon,cherry

console.log(`Fruits list: ${fruits.join(' and ')}`);
//Fruits list: apple and lemon and cherry

P
profesor08, 2016-12-23
@profesor08

Nonsense. If you need to concatenate:

var text = "";
for(let i = 0; i < 5; i++)
{
  text += `bla-bla text i = ${i}`;
}

If you need to do html inserts, then you need a template engine or framework, where it is available.
A mess of html and js code is a bad practice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question