© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
J. BartlettProgramming for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-8751-4_16

16. Modernizing JavaScript

Jonathan Bartlett1  
(1)
Tulsa, OK, USA
 

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.

Because of these drawbacks, more recent iterations of JavaScript introduced the let keyword for declaring variables. Using let is very similar to var, with some important distinctions:
  • 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.

The last lines of Figure 16-1 will give an error because the constant value is reassigned.

A 14 line code initializes variable x and z as 3, refers to the function scoped x, global z, just reaffirms the existence of x and creates a new y for this block.

Figure 16-1

Differences Between let and var

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

One thing that saves a lot of typing is what is known as a destructuring assignment. Let’s say you have an array myary that has the value [23, 43, 5]. Now, let’s say that you want to separate these values into the variables x, y, and z. Usually, you would do that like the following:
let x = myary[0];
let y = myary[1];
let z = myary[2];
However, destructuring allows us to tell JavaScript in a succinct way how to do the assignment. Here is the same assignment using destructuring:
let [x, y, z] = myary;

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.

This also works with objects as well. Let’s say that we have an object that looks like this:
var myobj = {
   field1: "val1",
   field2: "val2",
   field3: "val3"
};
Let’s say that we wanted to extract field1 and field2 into their own variable. This can be done as follows:
let { field1, field2 } = myobj;
If we wanted to rename field2 to be myotherfield, then we can write it like this:
let { field1, field2: myotherfield } = myobj;

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

One important feature of JavaScript that has been in there from the beginning is the ability to access properties using the string value for the name of the property. This allows usage of JavaScript objects as extremely flexible stores of data. To see what I mean, let’s look at an example object.
var theperson = {
   name: "Jim",
   age: 20,
   hair: "brown"
};

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.

Because this is a string, I can use a variable as well.
var myfield = "name";
alert("The person's name is " + theperson[myfield]);
This means that a user can even say what field they would like to access.
var myfield = prompt("What field would you like to read?");
alert("The value of that field is " + theperson[myfield]);

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

So far we have declared functions by typing something like the following:
var myfuncname = function(param1, param2) {
   // Function body here
}
This syntax was chosen to emphasize the distinction between creating a function and assigning a name to that function. I think doing it this way helps make it easier to understand how creating and passing functions as parameters works (like we did in Chapter 14). However, there is a combined syntax that does both at once that is much more commonly used. The same snippet above, using this other syntax, looks like this:
function myfuncname(param1, param2) {
   // Function body here
}
However, modern JavaScript adds yet another way to create functions, which is known variously as lambda functions or arrow functions.1 Creating the same function using lambda/arrow functions looks like this:
var myfuncname = (param1, param2) => {
   // Function body here
}

The meaning is (almost) the same, but it gets rid of the annoyingly long function keyword.

There are indeed some slight differences to regular functions, but usually they are unimportant. The main differences are as follows:
  • 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

In this chapter, we learned about additional syntax available in JavaScript. We learned the following:
  • 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. 1.

    Go through your old programs and rewrite them using let instead of var.

     
  2. 2.

    Look through a program and find a variable which was never reassigned, and use the const keyword for declaring the variable.

     
  3. 3.

    Rewrite a program that uses functions to use the arrow syntax.

     
  4. 4.

    Rewrite the function in Figure 11-5 so that it uses destructuring syntax to put the child’s age in a separate variable.

     
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.151.126