Avoid indentation using backticks in JavaScript

Backticks and line breaks lead to inconvenient indentation:

javascript
let multiline = (
    
    `Hi,
    this text has a weird indentation
    because it's in the middle of backticks.` 
    
);

console.log(multiline);

/*
Hi,
    this text has a weird indentation
    because it's in the middle of backticks.
*/

Alernative 1: dedent function

You could create a prototype function to dedent the multiline string:

javascript
String.prototype.dedent = function() {
    
    return this.split('\n').map(line => line.trim()).join('\n');
    
}

At this point, you could:

javascript
let multiline = (
    
    `Hi,
    this text has a nice indentation
    because we defined a dedent function.` 
    
).dedent();

console.log(multiline);

/*
Hi,
this text has a nice indentation
because we defined a dedent function.
*/

Alernative 2: array instead of backticks

If the previous alternative seems to complicated, you could use an array instead of backticks:

javascript
let multiline = [
    
    `Hi`,
    `this text has a nice indentation`,
    `because it uses an array instead of backticks.`
    
].join('\n');

console.log(multiline);

/*
Hi
this text has a nice indentation
because it uses an array instead of backticks.
*/

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.