Before we get started in some of the details about how applications in the real world are written, I wanted to take a moment and introduce you to some modern features of JavaScript which are commonly used in modern applications. Note that the goal of this book is not to provide a comprehensive introduction to JavaScript itself but rather to use JavaScript as a jumping point for learning programming in general. Nonetheless, I wanted to take some time and introduce a few modernizations of JavaScript that have been introduced over the years which you are likely to run into if you read JavaScript code. None of these are radical departures, but they do make JavaScript a little easier to read and write.
JavaScript was originally written with a primary goal of being simple, easy to implement, and easy to learn. The basic ideas behind JavaScript are sufficiently simple that the author of JavaScript originally wrote JavaScript in only 10 days. However, as it has become more and more widespread as a programming language, additional features have been added on.
In this chapter we will look at some of the more commonly used additions to JavaScript that have been added over the years. Additionally, we will also hit on some older features that are important but haven’t yet been discussed in the book.
16.1 Declaring Variables with let and const
The var keyword is what we have been using to declare variables so far in this book. As we have noted, when used outside of a function, var declares a global variable, and, when used inside a function, var declares a local variable that is scoped to the function it is contained in. However, var has some weird behaviors that need to be maintained for backward compatibility with older code, even though it probably isn’t wise to use these behaviors.
First of all, the var keyword can occur anywhere in the function, and it still backward-applies to the usage of the variable previously in the function. If you declare a variable with var more than once, these all get bundled into a single variable declaration. Finally, being function-scoped is somewhat of a surprising feature, as most programming languages delineate scopes at the block level.
The let keyword must occur before using the variable.
Every time you use the let keyword, it declares an entirely new variable.
The let keyword is block-scoped, not function-scoped.
If you try to use let twice in the same scope for the same variable, it will generate an error.
The code in Figure 16-1 illustrates the differences. Following along will help you see the differences in how the two ways of declaring variables behave.
Another keyword for declaring variables is const, which stands for “constant.” This works very similarly to let, except that, once assigned a value, the variable cannot have another value assigned to it. This is helpful in two ways. First, it enables optimizations within JavaScript that can make your code faster if you have code that needs to execute quickly. Second, and even more importantly, it helps you to remember which variables are actually varying and which ones are supposed to be left alone. The const keyword will remind you that this variable is only supposed to be assigned once, and, if you forget, the subsequent assignments to that value will yield errors.
In most modern JavaScript applications, let and const are preferred to var. We have used var primarily because it is more forgiving for beginners and reflects a lot of existing documentation on JavaScript. However, if you go further, you will probably see let and const quite a bit.
16.2 Destructuring Assignments
What this says is that we should expect that myary is structured in such a way that it looks like the left-hand side and that we should assign the variables accordingly. Any additional members of the array are ignored, and if there aren’t enough members of the array, the variable will be filled with undefined.
Destructuring is very helpful when you want to extract several pieces of an object or an array without having complicated code. You simply mirror the left-hand side so that the variable you want to assign is in the same location that you are expecting on the right-hand side. You can embed arrays within objects within arrays and so forth.
As mentioned, this book is not intended as a complete JavaScript book, but I did want to let you know about some pieces of syntax that are both helpful and you are likely to see out in the wild.
16.3 Accessing Properties with Strings
Now, we already know how to access individual properties of this object using theperson.name or theperson.age. However, we can also ask the object for a property that is named by a string. If we want the name property, I can ask for it by doing theperson["name"]. By putting this on the left-hand side of an assignment statement, I can set a field in this way as well, whether or not it existed beforehand.
This allows for a huge amount of flexibility in both the creation and usage of object fields. In fact, property names can actually be arbitrary strings and don’t even have to be accessible in the “normal” syntax. For instance, I could set a field like theperson["some,;/field–+"]. If we tried to access that field using the normal method, we would get a syntax error. But it is a perfectly valid operation as a string.
There are many cases where it is useful to have an object serve as a random grab-bag of key-value pairs. Using objects in this way allows you to do this. In computer programming, objects used in this way are referred to variously as dictionaries, hashtables, maps, or associative arrays.
16.4 Function Syntax
The meaning is (almost) the same, but it gets rid of the annoyingly long function keyword.
Regular functions get another special variable we haven’t talked about, known as arguments. This is essentially an array of all arguments passed to the function, which allows functions to be called with more arguments than are shown in the parameter list. Arrow functions do not have this special variable.
Arrow functions do not overwrite the this variable (see Chapter 15). If you want to inherit the current this variable being used, arrow functions will help out. If you want to make an object method, you should use the traditional syntax.
Regular functions can be called with the new keyword to build objects (again, see Chapter 15). Because arrow functions do not work with their own this variable, you cannot use arrow functions in this way.
So aside from a few edge cases, arrow functions are basically identical to the syntax we’ve used so far. However, while it might seem trivial, the fact that arrow functions don’t clobber the this variable comes in handy quite a bit. If you are writing a method inside an object and need a dynamically created function, you can choose a regular function or an arrow function based on whether or not you want this to be overwritten.
16.4.1 Review
Variables can be declared with the let and const keywords for block scoping and slightly cleaner behavior.
Variables declared with the const keyword should not be reassigned after declaration.
Assigning variables based on complex object and array layouts can be greatly simplified through destructuring assignments.
The arrow syntax for functions is more compact and convenient to write.
The arrow syntax for functions does not overwrite the this special variable.
16.4.2 Apply What You Have Learned
- 1.
Go through your old programs and rewrite them using let instead of var.
- 2.
Look through a program and find a variable which was never reassigned, and use the const keyword for declaring the variable.
- 3.
Rewrite a program that uses functions to use the arrow syntax.
- 4.
Rewrite the function in Figure 11-5 so that it uses destructuring syntax to put the child’s age in a separate variable.