Working in the Console

One of the most useful parts of the DevTools is the console, which lets you enter JavaScript code and evaluate it immediately. This is especially useful for iteratively developing JavaScript code that makes changes to a page.

In the DevTools, click on the Console tab, to the right of the Elements tab (Figure 6.5).

Figure 6.5  Choosing the console tab

Choosing the console tab

The console has a prompt where you can enter lines of code. Click to the right of the Choosing the console tab symbol so that the console is ready for input (Figure 6.6).

Figure 6.6  The console, ready for input

The console, ready for input

Type the following math expression into the console:

137 + 349

Press the Return key. The console will print out the result (Figure 6.7).

Figure 6.7  Evaluating a math expression

Evaluating a math expression

The console’s main job is to tell you, in the simplest terms, the value of the code you enter.

As with many things in life, order matters. If you need certain items to be evaluated as a group, you can wrap parentheses around them. (This is much easier than memorizing the order in which JavaScript would do this without the parentheses.) Enter the following expression in the console.

3 * ( (2 * 4) + (3 + 5) )

Press the Return key, and the console will crunch the numbers in the correct order (Figure 6.8). (By the way, although we have added spaces between the numbers and operators for the sake of readability, you do not need to include them. The console does not care.)

Figure 6.8  Evaluating a more complex math expression

Evaluating a more complex math expression

Now, on to using your variables. You can clear the contents of the console by pressing the Evaluating a more complex math expression icon in the upper left of the console panel or with the keyboard shortcut Command-K (Ctrl-K).

Start typing DETAIL_IMAGE_SELECTOR. As you type the first few letters, you can see that the console already knows about the variables you created and provides a list of autocomplete suggestions (Figure 6.9).

Figure 6.9  The console’s autocomplete menu

The console’s autocomplete menu

Press the Tab key and let the console autocomplete the variable name for you. When you press the Return key, the console reports that the value of DETAIL_IMAGE_SELECTOR is the string "[data-image-role="target"]".

Figure 6.10  The console printing a variable’s value

The console printing a variable’s value

(The console always prints strings with double quotes, even though you actually used single quotes in main.js.)

Strings are one of five primitive value types in JavaScript. (Numbers and Booleans are two of the others.) They are “primitive” because they represent simple values. This is in contrast to more complex values in JavaScript, which you will learn about next.

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

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