Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

JavaScript Crash Course: A Hands-On, Project-Based Introduction to Programming
JavaScript Crash Course: A Hands-On, Project-Based Introduction to Programming
JavaScript Crash Course: A Hands-On, Project-Based Introduction to Programming
Ebook739 pages6 hours

JavaScript Crash Course: A Hands-On, Project-Based Introduction to Programming

Rating: 0 out of 5 stars

()

Read preview

About this ebook

A fast-paced, thorough programming introduction that will have you writing your own software and web applications in no time.

Like Python Crash Course, this hands-on guide is a must-have for anyone who wants to learn how to code from the ground up—this time using the popular JavaScript programming language.


Learn JavaScript—Fast! 

JavaScript Crash Course is a fun-filled, fast-paced introduction to programming with JavaScript. Dive right in and you’ll be writing code, solving problems, and building working web applications and games in no time. You’ll start by learning fundamental programming concepts, such as variables, arrays, objects, functions, conditionals, loops, classes, and more. Aided by engaging examples and hands-on exercises, you’ll build on this foundation and combine JavaScript with HTML and CSS to create interactive web applications that you can run right away.

Then you’ll put your new skills into play with three substantial projects: a Pong-style game with a virtual opponent, an app that generates electronic music, and a platform for visualizing data fetched from an API.

Along the way, you’ll learn how to:

• Update web pages in real time by manipulating the Document Object Model
• Trigger functions in response to events like key presses and mouse clicks
• Generate graphics and animations with JavaScript and HTML’s Canvas element
• Visualize data with the D3.js library and scalable vector graphics (SVG)
• Make electronic music with Tone.js and the Web Audio API

If you’ve been thinking about digging into programming, JavaScript Crash Course will get you writing real programs fast. Why wait any longer? Jump on your magic carpet and ride!
LanguageEnglish
PublisherNo Starch Press
Release dateMar 5, 2024
ISBN9781718502277
JavaScript Crash Course: A Hands-On, Project-Based Introduction to Programming

Read more from Nick Morgan

Related to JavaScript Crash Course

Related ebooks

Programming For You

View More

Reviews for JavaScript Crash Course

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    JavaScript Crash Course - Nick Morgan

    INTRODUCTION

    I vividly remember the first time I wrote JavaScript. I’d been messing around with web design and copy-pasted some code from another website to add some weird effects whenever the mouse hovered over certain parts of the page. I had no idea what the code was doing, but through trial and error I managed to get something working.

    JavaScript is a very forgiving language—sometimes to a fault—and that made it a very gentle introduction to programming for me and countless others. So many people have chosen JavaScript as a first programming language because of how easy it is to get started: it’s right there waiting for you in your web browser!

    Who Is This Book For?

    The aim of this book is to get you writing real JavaScript code as quickly as possible, teaching all the essentials without getting bogged down in the intricacies of the language. I don’t expect you to have any prior programming experience. If you’re comfortable using a computer for everyday tasks like browsing the internet and editing documents, you have everything you need to get started.

    JavaScript Crash Course is written for individuals of all ages who want to learn JavaScript independently through hands-on examples and projects. Maybe you want to transition into a career in computer programming, or you want to pursue coding as a hobby. Perhaps you’ve worked in other programming languages, and you need to get up to speed in JavaScript. If you’re a teacher and are looking for an easy way to introduce your students to programming, JavaScript Crash Course is a great option for you, too.

    Why JavaScript?

    There are hundreds of programming languages to choose from, but there are a few things that make JavaScript special. Most important is its relationship with web browsers, such as Google Chrome, Safari, Microsoft Edge, and Firefox. Almost every web browser can run JavaScript, which means the code you write in JavaScript can be run on any computer with a web browser. There’s no need to install any additional special software. Almost all smartphone web browsers can run JavaScript, too, so you may have a JavaScript-enabled browser in your pocket or bag right now.

    Because of its relationship to web browsers, JavaScript is an extremely important part of web development. If a website includes dynamic, interactive features, it was probably created with JavaScript. For example, YouTube uses JavaScript to show you previews of videos when you hover over their thumbnails, Threads uses JavaScript to load more posts as you scroll down the page, and Amazon uses JavaScript to power its Look Inside feature.

    Beyond its use in web browsers, JavaScript is also heavily used on the backend of websites, or the part of the website code that runs on a server, delivering content to users (as opposed to the frontend code that runs directly on the user’s device). This is possible via a technology called Node.js. Many top websites have a Node.js backend, letting you use the same language for the frontend and backend of your website, and even share code between the two.

    Finally, JavaScript has become a very popular scripting language for various applications, from Photoshop (where you can automate image processing) to Gmail (where you can add automations that organize your email). With some JavaScript knowledge, you can bend these applications to your will!

    While the language is useful in all these areas, this book will focus solely on browser-based JavaScript. There are a few reasons for this. First, as I’ve already mentioned, one of the great advantages of running JavaScript in a browser is that you don’t have to install anything special to get started. I didn’t want to begin the book with a tedious chapter on installing Node.js on your computer—a chapter that could become outdated as soon as it was written. Second, while virtually all websites use JavaScript for the frontend, JavaScript is just one among many possible languages for writing backend code. The browser is by far the most universally applicable context for learning JavaScript.

    I still highly recommend checking out Node.js and other uses for JavaScript after you finish this book and have some experience with the language. You should see the book as a jumping-off point: the beginning, rather than the end, of your JavaScript education. For more on next steps once you’ve worked through the book, see the afterword.

    What Can You Expect to Learn?

    This book will teach you browser-based JavaScript. Beyond learning the JavaScript language itself, you’ll also learn skills that will help you in any programming language, such as how to think about problems and how to structure programs. You’ll build a foundation of programming knowledge that will stick with you throughout your professional and personal coding endeavors.

    Part I of this book lays out the basics of the language. I’ve been very intentional about the ordering of language concepts and features, making sure that every new concept builds on previous ones and never introducing anything that doesn’t have a solid foundation. Here’s what you’ll find in this part of the book:

    Chapter 1: Getting Started Shows you how to write your first lines of JavaScript in both a web browser and a text editor.

    Chapter 2: The Basics Introduces basic ingredients of JavaScript programs, like expressions, statements, and variables, and explains how to use simple data types to represent numbers, text, and true/false values.

    Chapter 3: Compound Data Types Discusses arrays and objects, which let you combine multiple pieces of data into more meaningful collections.

    Chapter 4: Conditionals and Loops Teaches you to add logic to your programs with control structures that can make decisions and repeat segments of code.

    Chapter 5: Functions Shows you how to create reusable pieces of code with functions.

    Chapter 6: Classes Helps you add more structure to your code with classes and object-oriented programming principles.

    Part II of the book discusses how to use JavaScript to work with web browsers. This section explores important techniques for creating interactive web applications:

    Chapter 7: HTML, the DOM, and CSS Explains how to write web pages in HyperText Markup Language (HTML) and modify their content with JavaScript using the Document Object Model (DOM). You’ll also learn how to apply basic styling to web pages using Cascading Style Sheets (CSS).

    Chapter 8: Event-Based Programming Shows how to trigger JavaScript code in response to user behaviors such as mouse clicks and key presses.

    Chapter 9: The Canvas Element Teaches you to draw graphics and animations in the browser with JavaScript using the Canvas API.

    Finally, Part III of the book lets you put the skills you gained in Parts I and II to use through a series of projects. There are no dependencies between the projects, so you can tackle them in any order, or only work on the projects you find most interesting. I would recommend completing all of them if possible, as they all introduce some valuable general-purpose programming concepts. Each project spans two chapters:

    Project 1: Creating a Game Guides you through making your own version of the classic Atari game Pong. This project will put to use your skills with the Canvas API and tie together all the basics you learned about data structures, conditionals, and functions. After you’ve developed the game in Chapter 10, Chapter 11 shows you how to restructure its code using classes and object-oriented design principles.

    Project 2: Making Music Explores how to make music using JavaScript. Chapter 12 explains how to use the Web Audio API and a library called Tone.js to generate sounds. Then Chapter 13 puts together what you’ve learned to create a song. Once you’ve completed this project, you’ll not only be able to create your own music, but you’ll also have gained some experience working with complex third-party libraries.

    Project 3: Visualizing Data Introduces you to the world of data visualization using the popular D3 library. Chapter 14 teaches the basics of D3 and Scalable Vector Graphics (SVG), an alternative to the Canvas API for drawing in the browser. Then, in Chapter 15, you’ll build an application to dynamically visualize data loaded from across the internet. This project illustrates how to request data through a third-party API, an important programming skill.

    Online Resources

    This book features a number of hands-on exercises so you can practice what you’ve learned. I encourage you to try them all out yourself, but if you get stuck or you just want to check your answers, solutions are available online at https://codepen.io/collection/ZMjYLO. There you’ll also find complete, downloadable code files for the book’s projects.

    For updates and other information about the book, see the No Starch Press website at https://nostarch.com/javascript-crash-course.

    PART I

    THE LANGUAGE

    This first part of the book introduces the fundamentals of the JavaScript language. You’ll learn about the basic building blocks of any JavaScript program, including many core concepts that are relevant to any programming language.

    First we’ll look at two ways to write and execute JavaScript code: in the console of a browser or in a text editor (Chapter 1). Then, you’ll learn how to represent individual pieces of data with variables and constants, and how to manipulate that data through statements and expressions (Chapter 2). Next, you’ll see how to group individual values into more meaningful structures using JavaScript’s compound data types, arrays and objects (Chapter 3).

    The later chapters of this first part show you how to add structure to your code. First, you’ll incorporate logic into your programs with conditionals and loops, which together allow you to make decisions and control the flow of code execution (Chapter 4). Then, you’ll learn techniques for reusing and organizing code with functions (Chapter 5) and classes (Chapter 6).

    1

    GETTING STARTED

    In this chapter, you’ll get started writing your first JavaScript code. First, you’ll learn how to enter code directly into a web browser, without having to install any specialized software. This approach is ideal for quickly testing out simple sequences of code. Next, you’ll see how to write JavaScript in a separate text editor program, which is more appropriate as your code becomes more complex. We’ll use both of these techniques for writing and executing JavaScript code throughout the book, so this chapter will prepare you for everything that’s to come.

    Using the JavaScript Console

    The quickest way to run JavaScript code is through the JavaScript console. This is an interface in most web browsers that lets you enter individual lines of code and immediately see the results. We’ll use the console in Google Chrome, the most popular browser. If you don’t have Chrome installed, you can download and install it from https://www.google.com/chrome.

    Once you have Chrome installed, follow these steps to access the JavaScript console:

    1. Open Chrome and enter about:blank in the address bar. This will take you to a blank web page.

    2. In Windows or Linux, press CTRL-SHIFT-J, or press OPTION-COMMAND-J if you’re using macOS.

    3. You should now see the JavaScript console, including the > prompt symbol where you can enter code. Click inside the console to put your cursor next to the prompt.

    The console should look something like Figure 1-1. It may appear alongside the blank web page, rather than beneath it, depending on your browser settings.

    Figure 1-1: Google Chrome’s JavaScript console

    When you’re learning a new programming language, it’s customary to start by writing some code to display the message Hello, world! Let’s try it out! Type the following into the console:

    alert(Hello, world!);

    In this book, when I ask you to enter code into the JavaScript console, I’ll show the code in bold. If the code produces any output in the console, I’ll show it directly below your input, not in bold.

    When you’re ready to run the code you’ve typed in, press ENTER. You should see a dialog appear in the browser containing the message Hello, world! as shown in Figure 1-2.

    Figure 1-2: Hello, world!

    You’ve just used JavaScript’s alert function, which makes text pop up in a dialog. A function is a piece of code for performing a certain task—in this case, displaying a dialog. Functions can take arguments, which help specify how the task should be performed. The alert function takes one argument: a piece of text to display. Here, we’ve provided Hello, world! as the argument. You’ll learn much more about functions in Chapter 5.

    Click OK to dismiss the dialog and get back to the console. Then congratulate yourself on running your first JavaScript code.

    Using a Text Editor

    The JavaScript console is good for testing out a few lines of code, but it isn’t so suitable for the larger projects we’ll be working on later in the book. For those, it’s more practical to use a text editor, a dedicated program for writing and editing code files. In this section, we’ll create a similar Hello, world! program in a text editor.

    For this book, I recommend using the Visual Studio Code text editor from Microsoft (VS Code for short). It’s freely available for Windows, macOS, and Linux. Go to https://code.visualstudio.com and follow the instructions there to download and install the editor.

    Once you’ve installed VS Code, create a new directory on your computer called javascript_work where you can save the code files you work on for this book. Then follow these steps to get ready to write your code:

    1. Open VS Code.

    2. Create a new file by selecting FileNew File.

    3. You should be prompted to name the new file. Enter hello.html.

    4. Next, you should be prompted to choose the new file’s location. Select the javascript_work directory you just created and click Create File.

    5. You should now be on a screen where you can edit your new file.

    The.html extension in the filename indicates that this is an HTML file. HTML is a markup language used to describe the content of web pages. One way to run JavaScript code is to include it in an HTML file and then open the HTML file in a web browser. That’s what we’ll be doing here. Enter the contents of Listing 1-1 into your new file, exactly as written.

    alert(Hello from hello.html!);

    Listing 1-1: Writing JavaScript inside the file hello.html

    As you type, you may notice that VS Code tries to predict what you’re entering. This can be confusing at first, but once you get used to it, you’ll likely find it helpful. Sometimes these predictions will be inserted automatically, while for others you’ll have to press TAB to insert them.

    The first and last lines of Listing 1-1 are HTML code, the bare minimum required to embed JavaScript into an HTML file. We’ll explore HTML in detail in Chapter 7. For now, all you need to know is that it involves tags that identify different components of a web page. Most important for our purposes are the opening tag at the beginning of the third line. When you load this file in a browser, everything between these tags (the second line in Listing 1-1) will be interpreted as JavaScript.

    The JavaScript portion of the file is:

    alert(Hello from hello.html!);

    Here we’re using the alert function, just as we did earlier in the console. This time we provide a different message, Hello from hello.html!, to display in the dialog.

    When you’re finished entering the code, save the file. Now you’re ready to open the file in Chrome and see the JavaScript code in action. Follow these steps:

    1. Open a new tab in Chrome.

    2. Press CTRL-O in Windows or Linux, or COMMAND-O in macOS, to bring up the Open File dialog.

    3. Locate your hello.html file, select it, and click Open.

    You should now see a dialog pop up containing the Hello from hello.html! message, as shown in Figure 1-3.

    Figure 1-3: Hello from hello.html!

    The browser recognized the code in the HTML file between the tags as JavaScript and executed that code, causing the dialog to appear. If you don’t see the dialog pop up, double-check the code in your hello.html file to make sure it matches Listing 1-1 exactly.

    Summary

    In this chapter, you learned two different ways to write and execute JavaScript code. First, you entered code into the JavaScript console in the Chrome web browser. You’ll use this technique in the coming chapters to test out short snippets of code as you learn the basics of the language. Next, you embedded JavaScript in an HTML file using a text editor, then opened that file in Chrome to run the code. You’ll use this technique in later chapters to develop more sophisticated projects.

    2

    THE BASICS

    In this chapter, I’ll introduce some of the basic ingredients that make up any JavaScript program. You’ll learn about the fundamental units of JavaScript code that allow you to represent values and give instructions to the computer. You’ll also learn how to assign a name to a value so you can refer to it later in your code.

    This chapter also shows how JavaScript categorizes values into different data types based on the kind of information a value can represent. We’ll focus on primitive data types that represent individual values, such as a single number or a single piece of text. You’ll practice working with different primitive data types in the JavaScript console and explore some of the operations you can apply to them.

    Expressions and Statements

    The most basic building block in JavaScript is the expression, a fragment of code that represents a single value. The act of determining the value of an expression is known as evaluation. For example, 100 + 200 is an expression that evaluates to the number 300.

    Another important JavaScript building block is the statement, which is a complete thought, like a sentence in English, instructing the computer to do something. Every JavaScript program consists of a series of statements. In Chapter 1, for example, we used the statement alert(Hello, world!); to instruct the computer to display a dialog with the text Hello, world! in it. Whereas a sentence ends with a period, JavaScript statements end with a semicolon.

    You can turn an expression into a statement simply by adding a semicolon to the end of it. For example, 100 + 200; is a statement instructing the computer to add two numbers together. Open up the JavaScript console and enter this statement. When you do this, it will evaluate the expression in the statement and print the result:

    100 + 200;

     

    300

    The main expression in this statement, 100 + 200, is known as a compound expression, since it actually contains two smaller expressions, 100 and 200. These are examples of the simplest form of JavaScript expression, the literal, which is a direct representation of a fixed value in code. Specifically, 100 and 200 are number literals, since they directly correspond to the numeric values they represent, 100 and 200. By contrast, the compound expression 100 + 200 isn’t a literal, since it doesn’t directly correspond to its value of 300. The + in this compound expression doesn’t represent a value at all. Rather, it’s an operator, a symbol used to combine or manipulate expressions.

    It’s important to distinguish between values, which are the underlying pieces of data in a program, and expressions, which are the notations in code that tell JavaScript what the values should be. Both 300 and 100 + 200 have a value of 300, but they’re two different expressions—one literal, one compound—that provide different ways of representing that value.

    JavaScript expressions and statements complement each other. Expressions have values, but an expression by itself doesn’t actually do anything. Conversely, statements do work by telling the computer to perform tasks, but statements themselves don’t have values; they’re just instructions. The power of programming comes from writing statements that use and manipulate the values of expressions to achieve the desired outcomes.

    Numbers and Operators

    JavaScript uses the number data type to store numeric values. You already started working with numbers in the previous section, where you also met the + operator, which adds two numbers together. JavaScript has operators for other common mathematical calculations, too, including subtraction (-), multiplication (*), and division (/). Try them out in the JavaScript console:

    100 + 200;

     

    300

    10000 - 999;

     

    9001

    999 * 111;

     

    110889

    997002 / 999;

     

    998

    In cases like this, where the expression involves an operator (such as + or *), we often say the operator returns a value (rather than saying an expression is being evaluated). For instance, the * operator takes in the numbers 999 and 111 and returns their product, 110889.

    Order of Operations

    You can combine multiple numbers and operators in a single expression, in which case you need to think about the order in which the operations will be performed. Consider this example:

    5 + 10 / 10 - 5;

     

    1

    When you have multiple operators like this, JavaScript uses the standard mathematical PEMDAS (parentheses, exponents, multiplication, division, addition, subtraction) rule to determine the order of calculations. The division operation in this expression takes place first, followed by the addition and subtraction, yielding a value of 1.

    To force the addition and subtraction to happen first, use parentheses:

    (5 + 10) / (10 – 5);

     

    3

    This time, the expression produces a different value, since the parentheses changed the order of operations.

    Floating Point

    So far we’ve limited ourselves to whole numbers, but JavaScript’s number data type also accommodates fractional numbers, called floating-point numbers in programming terms. Here’s an expression that produces a floating-point number:

    10 / 4;

     

    2.5

    Floating-point numbers have limited precision, so the decimal component can’t go on forever. Instead, they’re truncated, as in the following example:

    10 / 3;

     

    3.3333333333333335

    You may notice some weird quirks of floating-point math, where the answer isn’t quite what you’d expect. For example, 0.1 + 0.2 doesn’t work out to exactly 0.3. Instead, we get several extra decimal places:

    0.1 + 0.2;

     

    0.30000000000000004

    This is due to the underlying mathematics of how computers represent numbers (search the web for floating-point arithmetic to learn more). In general, these quirks shouldn’t affect you, but they could in certain circumstances. For example, if you’re writing an application that works with monetary values, it could be a problem if $0.10 and $0.20 didn’t sum to exactly $0.30. In this case, the usual solution is to convert your monetary values to cents (or the equivalent smallest denomination) before doing any math on them. For example, the number 0.10, representing an amount of dollars, would become 10, representing an amount of cents.

    TRY IT YOURSELF

    2-1. Use the JavaScript console to calculate the number of seconds in a day.

    Bindings

    In JavaScript, you can associate a name with a value so you can easily reference that value later in your code. This association is called a binding. Bindings are powerful tools because they provide a place to store the values your expressions generate. Without them, your programs would have no way of remembering the work they’ve already done.

    One type of binding is a variable, which allows you to update the value associated with a particular name as needed. They’re called variables because their values can change, or vary. Another type of binding is a constant, where you can’t update the value associated with the name once it’s been assigned. The value remains fixed, or constant.

    Think of a variable or constant as a box with a label (the name) that holds a single item (the value). You put a value in the box, then look it up by name when you need it again. A variable allows you to put a new value in the box, while a constant will always contain the same value.

    The name of a binding is also called its identifier, and creating an identifier is known as declaration: the binding’s name is being declared. In JavaScript, a declaration is a special kind of statement that generates a new identifier. Let’s look at how to declare and work with variables and constants.

    Variables

    JavaScript has two keywords for declaring variables: var and let. A keyword is a word built into the JavaScript language that’s reserved for a particular purpose. Originally, the var keyword was the only option available, but let was later added to fix some of the shortcomings of var. Today, let is the preferred keyword for declaring variables, so that’s what we’ll use in this book, but don’t be surprised if you encounter var while looking at older code.

    Here’s an example of using let to declare a variable:

    let age;

     

    undefined

    This let declaration creates a new variable called age. A let declaration doesn’t have a value, so the JavaScript console prints out the special value undefined.

    Now that we’ve created a variable, let’s write an expression to give it a value:

    age = 35;

     

    35

    Giving a variable a value is called assignment, and you use the assignment operator (=) to do it. On the right side of the operator, you enter an expression (in this case, the number literal 35), and on the left, you enter the name of the variable that should be assigned the value of that expression (in this case, age).

    An assignment using the = operator is a compound expression, just like expressions using + and other mathematical operators. The value of an assignment expression is the new value of the variable. In this case, we’ve set age to 35, so the console prints 35.

    Assigning a value to a variable for the first time is called initialization. Programmers usually combine the declaration and initialization of a variable into a single line of code. For example, here we create a new variable called cats and assign it the value 2, all in the same statement:

    let cats = 2;

     

    undefined

    Even though we’re assigning the variable a value here, the prevailing rule is that the let declaration itself has no value, so the JavaScript console prints undefined.

    To confirm the assignment worked, enter just the variable name into the console, followed by a semicolon:

    cats;

     

    2

    Here, cats is an expression that evaluates to the current value of the cats variable, so the console prints that value.

    Because cats is a variable, we’re free to change its value using new assignment expressions. Here, for example, we update its value to 3:

    cats = 3;

     

    3

    The nice thing about variables is that you can change their values whenever you need—for example, when you get another cat.

    Constants

    To declare a constant in JavaScript, we use the const keyword:

    const PI = 3.141592653589793;

     

    undefined

    This creates a new constant called PI and assigns it the value 3.141592653589793, which is the approximate value of the number π.

    Now we can use that constant to determine the circumference of a circle based on its diameter:

    let diameter = 3;

     

    undefined

    let circumference = diameter * PI;

     

    undefined

    circumference;

     

    9.42477796076938

    Here we create a variable called diameter and assign it the value 3. Then we create another variable, circumference, and assign it a value of diameter * PI. Notice that we’re using a compound expression consisting of a variable (diameter), a constant (PI), and a math operation (*) to set the value of a variable. A lot of programming boils down to creating constants and variables, and then manipulating them to create other constants and variables.

    NOTE

    Going forward, to keep the book’s code listings from getting too cluttered, I’ll stop showing the undefined that the console prints after a variable or constant is declared.

    Unlike with variables, you can’t change the value of a constant once it’s been created. For example, if you try to update the value of PI, JavaScript gives an error:

    PI = 5.378;

     

    Uncaught TypeError: Assignment to constant variable.

      at :1:4

    Errors are how JavaScript tells you there’s something wrong with your code. The important part of this error message is Assignment to constant variable. This indicates that we mistakenly tried to assign a new value to a constant.

    Also unlike with variables, where you can separate the declaration from the initialization, you have to give a constant its value in its declaration. As a result, this won’t work:

    const TAU;

     

    Uncaught SyntaxError: Missing initializer in const declaration

    This error message tells us that the constant declaration is missing its initializer, meaning the constant should have been given a value.

    Naming Conventions

    You should give variables and constants descriptive names, so when you or somebody else is reading your code, it’s clear what your variables and constants represent. For example, if you’re writing code to control a car, you might want a variable that stores the speed of the car in miles per hour. The name speedInMilesPerHour is a bit too long, but given that MPH is a commonly understood abbreviation for miles per hour, a good variable name would be speedInMPH. A shorter name like speed might be okay, but only if it’s obvious to everyone reading your code that speed is always in miles per hour. (Imagine if someone from Germany were reading your code and thought you were talking about kilometers per hour.) A bad name for this variable would be s, which tells the reader nothing.

    JavaScript is case sensitive, which means it distinguishes between the variables age, Age, and AGE. Also, identifiers can’t contain spaces. To work around that, a common convention for variable names is to use camelCase, where the first word in the name starts with a lowercase letter and each subsequent word starts with a capital letter, as in speedInMilesPerHour. (It’s called camelCase because the capital letter in the middle looks like the hump of a camel.)

    An alternative naming convention for variables is snake_case, where everything is lowercase and each word is separated by an underscore. (I guess this looks a bit like a snake if you squint.) In snake_case, we would write speed_in_miles_per_hour or speed_in_MPH.

    Using snake_case can make variable names slightly clearer than camelCase, but it also makes them longer and harder to type quickly. JavaScript programmers tend to prefer camelCase, so that’s what I’ll use in this book.

    Constants follow a separate naming convention from variables. There are two types of constants: true constants, which have values that will never change whenever you run the program (such as pi or the number of hours in a day), and values you’ve made constants because you don’t want to accidentally change them in your code (such as the current user’s name). For true constants, it’s customary to use all-caps snake_case, like HOURS_IN_A_DAY. For constants you’ve created to avoid accidentally changing a value, use the same convention as for variables. In that case, the only difference is that the binding has been created using const rather than let.

    CHOOSING BETWEEN LET AND CONST

    It’s not always obvious whether to use let or const when you’re creating a binding. If you’ll need to update the binding’s value, use let to make it a variable. In other cases, it’s up to you. Some programmers prefer to use let most of the time and reserve const only for true constants. Others use const wherever possible and switch to let only if they realize they need to update the value of a binding. The advantage of defaulting to let is that you don’t need to stop and consider whether every binding could validly be changed. The advantage of defaulting to const is that you gain some safety from accidentally changing a value that shouldn’t have been changed. Ultimately, the choice between the two approaches is a matter of style and personal preference.

    Incrementing and Decrementing

    When you’re writing software, you’ll often have to increment (increase) or decrement (decrease) the value of a variable by 1 or some other number. For example, you might use a variable to count the occurrences of a word in a document. Every time you see that word, you would increase the value of the variable by 1. Likewise, you might use a variable to keep track of how much money a player has in a game, increasing or decreasing it whenever the player earns or spends some.

    One way to increment a variable is to initialize it, then change its value to itself plus 1:

    let money = 100; money = money + 1;

     

    101

    Here we declare a new variable called money and initialize it with the value 100. We then assign a new value to money by adding 1 to its existing value. It may seem paradoxical to see an expression like money = money + 1;, but this is actually quite a normal programming pattern. When JavaScript encounters an assignment expression like this, it first calculates the value of the expression on the right of the assignment operator, which in this case is money + 1. Because money is currently 100, money + 1 has a value of 101. JavaScript then updates the value of the variable on the left side of the assignment operator, which in this case is the same variable, money.

    The key here is that JavaScript waits

    Enjoying the preview?
    Page 1 of 1