DEV Community

Cover image for JS: Why we should also use formatted strings
Lorenzo
Lorenzo

Posted on • Updated on

JS: Why we should also use formatted strings

Hello World! Today we will study why formatted strings (template literals) are so useful for programmers and how to use them.


The first important thing to notice that a lot of different programming languages allow us to use formatted strings.
We should always use formatted string because they provide us a better looking and modern code. We get rid of this multitude of + signs with a more elegant dollar sign (with curly brackets {}).

For example in this article about how to implement a random background color change in javascript I could have used:

  1. Normal string
function random_bg_color() {
    let x = Math.floor(Math.random() * 256);
    let y = Math.floor(Math.random() * 256);
    let z = Math.floor(Math.random() * 256);
    let bgColor =  "rgb(" + x + "," + y + "," + z + ")";
}
Enter fullscreen mode Exit fullscreen mode
  1. Formatted string
function random_bg_color() {
    let x = Math.floor(Math.random() * 256);
    let y = Math.floor(Math.random() * 256);
    let z = Math.floor(Math.random() * 256);
    let bgColor =  `rgb( ${x}, ${y}, ${z} )`;
}
Enter fullscreen mode Exit fullscreen mode

Check how horrific, awful, shaking and macabre this line is let bgColor = "rgb(" + x + "," + y + "," + z + ")"; compared to the elegance of a formatted string. Now imagine the same in a real-life project with hundreds of lines of codes and dozens of variables. You can't multiple adjectives, but it will be a hundred times horrific, awful...
A formatted string is very easy to obtain, you place a back-tick a the start and one at the end of the expression (like a quotation mark) and then write a normal sentence. Variables are differentiated with a dollar sign. We don't have to worry about spacing or capitalizing problems after a point.


Another cool feature of template literals is that they allow you to write multiline code:

let multiline = `Remember the like
and follow ${me} for more content`;
Enter fullscreen mode Exit fullscreen mode

Just to remember you, $ is obtained by pressing shift+4. Curly brackets with shift+alt+Γ© for { and shift+alt+* for }.
Back-ticks vary by keyboard and country -here a full list.
Principally we have:
Mac - ALT + 9
Windows: ALT+96
Linux: ALT+’ (ALTGR + apostrophe)
On a laptop with windows, for example on an Italian keyboard, we can't do ALT+96 so we have to install a Linux keyboard or to open Charmap. To open it: Windows logo command + r, then you write Charmap, this will open:
image
I usually leave it open while coding and return copying the backtick every time y need it.


The last thing to notice is that template strings in javascript are (or at least I think) the best in the big programming language market. We don't have to write the f like in python or to do complicate things and it's really nice looking. I also need to say that they allow you to immediately differentiate variables from strings.


Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue

Check this article about how to write CSS like a pro!


Subscribe to my Newsletter!

A loooong, and fun, weekly recap for you
Free PDF version of my articles
Highly customizable inbox
That's --> free <-- and you help me!

Top comments (4)

Collapse
 
valeriavg profile image
Valeria • Edited

We shouldn't always use template literals. For example, in cases where newlines matter it's better to concatenate strings differently:

const yamlConfig=`var1: 1
var2: 2
var3: "something else"`
// Versus:
const yamlConfig=
     'var1: 1\r\n'+
     'var2: 2\r\n'+
     'var3: "something else"'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ
x+':'+y
`${x}:${y}`
Enter fullscreen mode Exit fullscreen mode

I disagree - depends entirely upon the situation. Sometimes normal string concatenations are shorter and easier to read

Collapse
 
pfacklam profile image
Paul Facklam

I think it depends on the situation when and when not to use it. If you want to know more about the power of template literals: dev.to/clicksolutions/the-power-of...

Collapse
 
lorenzoblog profile image
Lorenzo

The link is no longer valid, do you want to send it again?