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:
- Never use var again. Forget about it.
- 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.
- 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."
or Kotlin:
"${name} is ${age} year${when (age == 1 ){ true -> "" false -> "s"}} old."
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.`
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:
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>`
Again you can copy / paste this into your web browser dev console (F12 in most browsers) and you'll see the following:
More to come in the next article...
Top comments (0)