DEV Community 👩‍💻👨‍💻

Cover image for Modern JavaScript: Preparation for React Dev (part 1)
raddevus
raddevus

Posted on

Modern JavaScript: Preparation for React Dev (part 1)

These are my quick notes while reading the fantastic book from O'Reilly publishing, Learning React, 2nd ed. by Alex Banks & Eve Porcello

Stop Using var, Use const & let

I don't want to list every single reason that you should switch to let (scoping) and const (no more worries about code in another module altering your values).
Instead, I just want to say:

  1. Never use var again. Forget about it.
  2. Use const everywhere you can -- maybe initially make every variable you create const. Then, when you go to change the value (somewhere else in code), go back and change it to let.
  3. Use let where you can't use const -- because you need to change the value the item contains.

That's it.

Template Strings

We can all stop using the addition operator (+) in JavaScript to create strings. Now we have Template String ability.

String interpolation syntax is far prettier in other languages like C#:

$"{name} is {age} year{(age == 1 ? "" : "s")} old."
Enter fullscreen mode Exit fullscreen mode

or Kotlin:

"${name} is ${age} year${when (age == 1 ){ true -> "" false -> "s"}} old."
Enter fullscreen mode Exit fullscreen mode

JavaScript Uses Back-tick Char

I like those better than the way JavaScript uses the back-tick char.

const name="ted";
let age = 10;
`${name} is ${age} year${(age == 1 ? "" : "s")} old.`
Enter fullscreen mode Exit fullscreen mode

You can copy that code, open up your dev console in your browser (while you're reading this article) and paste it in and hit <ENTER> and it will display the following:

Alt Text

You can alter the value of age = 1 and run it again and you'll see that the "year" part of the string will be singular.

Line Breaks Can Be Included

It's quite amazing that you can build up a huge template string that represents HTML now, and line breaks can be included.

const firstId ="mainOne";
const imageLink="/fake/notreal/fake.jpg"
const outputElement = `
<div id="${firstId}">
   <img src="${imageLink}"
</div>`
Enter fullscreen mode Exit fullscreen mode

Again you can copy / paste this into your web browser dev console (F12 in most browsers) and you'll see the following:

Alt Text

More to come in the next article...

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.