Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

JavaScript for Kids: A Playful Introduction to Programming
JavaScript for Kids: A Playful Introduction to Programming
JavaScript for Kids: A Playful Introduction to Programming
Ebook677 pages3 hours

JavaScript for Kids: A Playful Introduction to Programming

Rating: 4.5 out of 5 stars

4.5/5

()

Read preview

About this ebook

JavaScript is the programming language of the Internet, the secret sauce that makes the Web awesome, your favorite sites interactive, and online games fun!

JavaScript for Kids is a lighthearted introduction that teaches programming essentials through patient, step-by-step examples paired with funny illustrations. You’ll begin with the basics, like working with strings, arrays, and loops, and then move on to more advanced topics, like building interactivity with jQuery and drawing graphics with Canvas.

Along the way, you’ll write games such as Find the Buried Treasure, Hangman, and Snake. You’ll also learn how to:
–Create functions to organize and reuse your code
–Write and modify HTML to create dynamic web pages
–Use the DOM and jQuery to make your web pages react to user input
–Use the Canvas element to draw and animate graphics
–Program real user-controlled games with collision detection and score keeping

With visual examples like bouncing balls, animated bees, and racing cars, you can really see what you’re programming. Each chapter builds on the last, and programming challenges at the end of each chapter will stretch your brain and inspire your own amazing programs. Make something cool with JavaScript today!

Ages 10+ (and their parents!)
LanguageEnglish
PublisherNo Starch Press
Release dateDec 14, 2014
ISBN9781593276591
JavaScript for Kids: A Playful Introduction to Programming

Read more from Nick Morgan

Related to JavaScript for Kids

Related ebooks

Programming For You

View More

Reviews for JavaScript for Kids

Rating: 4.333333333333333 out of 5 stars
4.5/5

6 ratings2 reviews

What did you think?

Tap to rate

Review must be at least 10 words

  • Rating: 5 out of 5 stars
    5/5

    Nov 13, 2024

    Thank You This Is Very Good, Maybe This Can Help You
    Download Full Ebook Very Detail Here :
    https://amzn.to/3XOf46C
    - You Can See Full Book/ebook Offline Any Time
    - You Can Read All Important Knowledge Here
    - You Can Become A Master In Your Business
  • Rating: 4 out of 5 stars
    4/5

    Sep 21, 2016

    Easy to use for kids to learn about JavaScript.

Book preview

JavaScript for Kids - Nick Morgan

Introduction

Welcome to JavaScript for Kids! In this book, you’ll learn to program with JavaScript, the language of the Web. But more than that, you’ll become a programmer—someone who not only uses computers but also controls them. Once you learn to program, you can bend computers to your will and make them do whatever you want!

JavaScript is a great programming language to learn because it’s used everywhere. Web browsers like Chrome, Firefox, and Internet Explorer all use JavaScript. With the power of JavaScript, web programmers can transform web pages from simple documents into full-blown interactive applications and games.

But you’re not limited to building web pages. JavaScript can run on web servers to create whole websites and can even be used to control robots and other hardware!

Who Should Read This Book?

This book is for anyone who wants to learn JavaScript or to start programming for the first time. The book is designed to be kid friendly, but it can serve as a first programming book for beginners of all ages.

With this book, you’ll build up your knowledge of JavaScript gradually, starting with JavaScript’s simple data types, before moving onto complex types, control structures, and functions. After that you’ll learn how to write code that reacts when the user moves the mouse or presses a key on the keyboard. Finally, you’ll learn about the canvas element, which lets you use JavaScript to draw and animate anything you can imagine!

Along the way, you’ll create a few games to stretch your programming skills and put what you’ve learned to good use.

How to Read This Book

First off, read it in order! That might sound like a silly thing to say, but lots of people want to jump straight into the fun stuff, like making games. But each chapter is meant to build on what was covered in earlier chapters, so if you begin at the beginning, you’ll have an easier time when you get to the games.

Programming languages are like spoken languages: you have to learn the grammar and the vocabulary, and this takes time. The only way to improve is by writing (and reading) a lot of code. As you write more and more JavaScript, you’ll find certain parts of the language become second nature, and eventually you’ll become a fluent writer of JavaScript.

As you read, I encourage you to type out and test the code examples throughout the book. If you don’t fully understand what’s going on, try making small changes to see what effect they have. If the changes don’t have the effect you expected, see if you can find out why.

Above all, work through the Try It Out and Programming Challenges sections. Typing out the code that appears in the book is a good first step, but you’ll understand programming at a deeper level when you start writing your own code. If you find a challenge interesting, then keep at it! Come up with your own challenges to build even more onto the programs you’ve written.

You’ll find sample solutions to the programming challenges (as well as the code files for the games and other examples) at http://nostarch.com/javascriptforkids/. Try looking at the solutions after you’ve solved a challenge, so you can compare your approach to mine. Or, if you’re stuck, you can check the solution for hints. But remember that these are just sample solutions. There are many, many different ways to accomplish the same goal in JavaScript, so don’t worry if you end up with a completely different solution from mine!

If you come across a word and you don’t know what it means, check the glossary at the back of the book. The glossary contains definitions for many of the programming terms you’ll encounter in this book.

What’s in this Book?

Chapter 1 gives you a quick introduction to JavaScript and gets you started writing JavaScript in Google Chrome.

Chapter 2 introduces variables and the basic data types used by JavaScript: numbers, strings, and Booleans.

Chapter 3 is all about arrays, which are used to hold lists of other pieces of data.

Chapter 4 is about objects, which contain pairs of keys and values.

Chapter 5 is an introduction to HTML, the language used to create web pages.

Chapter 6 shows you how to gain more control over your code using if statements, for loops, and other control structures.

Chapter 7 puts together everything you’ve learned so far to create a simple Hangman word-guessing game.

Chapter 8 shows you how to write your own functions so you can group together and reuse blocks of code.

Chapter 9 introduces jQuery, a tool that makes it easy to control web pages using JavaScript.

Chapter 10 shows you how to use timeouts, intervals, and event handlers to make your code more interactive.

Chapter 11 uses functions, jQuery, and event handlers to create a game called Chapter 11

Chapter 12 teaches a style of programming called object-oriented programming.

Chapter 13 introduces the canvas element, which allows you to draw graphics on a web page with JavaScript.

Chapter 14 builds on the animation techniques you learned in Chapter 10 so you can create animations with canvas, and Chapter 15 shows you how to control those canvas animations with the keyboard.

In Chapter 16 and Chapter 17, you’ll program a complete Snake game, using everything you learned in the previous 15 chapters!

The Afterword gives you some ideas for how to learn even more about programming.

The Glossary contains definitions for many of the new words you’ll encounter.

Have Fun!

One last thing to remember: Have fun! Programming can be a playful and creative activity, just like drawing or playing a game (in fact, you’ll be drawing and playing games with JavaScript a lot in this book). Once you get the hang of how to write code, the only limit is your imagination. Welcome to the amazing world of computer programming—I hope you have a blast!

Part I. Fundamentals

Chapter 1. What Is JavaScript?

Computers are incredibly powerful machines, capable of performing amazing feats like playing competitive chess, serving thousands of web pages, or making millions of complex calculations in less than a few seconds. But deep down, computers are actually pretty dumb. Computers can only do exactly what we humans tell them to do. We tell computers how to behave using computer programs, which are just sets of instructions for the computers to follow. Without programs, computers can’t do anything at all!

Meet JavaScript

Even worse, computers can’t understand English or any other spoken language. Computer programs are written in a programming language like JavaScript. You might not have heard of JavaScript before, but you’ve certainly used it. The JavaScript programming language is used to write programs that run in web pages. JavaScript can control how a web page looks or make the page respond when a viewer clicks a button or moves the mouse.

Sites like Gmail, Facebook, and Twitter use JavaScript to make it easier to send email, post comments, or browse websites. For example, when you’re on Twitter reading tweets from @nostarch and you see more tweets at the bottom of the page as you scroll down, that’s JavaScript in action.

You only have to visit a couple of websites to see why JavaScript is so exciting.

JavaScript lets you play music and create amazing visual effects. For example, you can fly through an interactive music video created by HelloEnjoy for Ellie Goulding’s song Lights (http://lights.helloenjoy.com/), as shown in Figure 1-1.

JavaScript lets you build tools for others to make their own art. Patatap (http://www.patatap.com/) is a kind of virtual drum machine that creates all kinds of cool noises—and cool animations to go along with them—as shown in Figure 1-2.

image with no captionYou control the flashing cursor in HelloEnjoy’s “Lights” music video.

Figure 1-1. You control the flashing cursor in HelloEnjoy’s Lights music video.

When you visit Patatap, try pressing a bunch of keys to make different noises!

Figure 1-2. When you visit Patatap, try pressing a bunch of keys to make different noises!

JavaScript lets you play fun games. CubeSlam (https://www.cubeslam.com/) is a 3D re-creation of the classic game Pong, which looks a little like air hockey. You can play against one of your friends or a computer-generated bear, as shown in Figure 1-3.

The CubeSlam game is programmed entirely in JavaScript!

Figure 1-3. The CubeSlam game is programmed entirely in JavaScript!

Why Learn JavaScript?

JavaScript isn’t the only programming language out there—in fact, there are literally hundreds of programming languages. But there are many reasons to learn JavaScript. For one, it’s a lot easier (and more fun) to learn than many other programming languages. But perhaps best of all, in order to write and run JavaScript programs, all you need is a web browser like Internet Explorer, Mozilla Firefox, or Google Chrome. Every web browser comes with a JavaScript interpreter that understands how to read JavaScript programs.

Once you’ve written a JavaScript program, you can send people a link to it, and they can run it in a web browser on their computer, too! (See Sharing Your Code Using JSFiddle.)

Writing Some JavaScript

Let’s write a bit of simple JavaScript in Google Chrome (http://www.google.com/chrome/). Install Chrome on your computer (if it’s not already installed), and then open it and type about:blank in the address bar. Now press ENTER and you’ll see a blank page, like the one in Figure 1-4.

We’ll begin by coding in Chrome’s JavaScript console, which is a secret way programmers can test out short JavaScript programs. On Microsoft Windows or Linux, hold down the CTRL and SHIFT keys and press J. On Mac OS, hold down the COMMAND and OPTION keys and press J.

If you’ve done everything correctly, you should see a blank web page and, beneath that, a blinking cursor (|) next to a right angle bracket (>), as shown in Figure 1-4. That’s where you’ll write JavaScript!

Note

The Chrome console will color your code text; for example, the text you input will be blue, and output will be colored based on its type. In this book, we’ll use similar colors for our code text wherever we’re using the console.

Google Chrome’s JavaScript console

Figure 1-4. Google Chrome’s JavaScript console

When you enter code at the cursor and press ENTER, JavaScript should run, or execute, your code and display the result (if any) on the next line. For example, type this into the console:

3 + 4;

Now press ENTER. JavaScript should output the answer (7) to this simple bit of addition on the following line:

3 + 4; 7

Well, that’s easy enough. But isn’t JavaScript more than a glorified calculator? Let’s try something else.

The Structure of a JavaScript Program

Let’s create something a bit sillier—a JavaScript program to print a series of cat faces that look like this:

=^.^=

Unlike our addition program, this JavaScript program will take up multiple lines. To type the program into the console, you’ll have to add new lines by pressing SHIFT-ENTER at the end of each line. (If you just press ENTER, Chrome will try to execute what you’ve written, and the program won’t work as expected. I warned you that computers were dumb!)

image with no caption

Type this into your browser console:

// Draw as many cats as you want! var drawCats = function (howManyTimes) {

 

 

for (var i = 0; i < howManyTimes; i++) {

 

   

console.log(i + =^.^=);

 

 

} };

 

 

drawCats(10); // You can put any number here instead of 10.

At the very end, press ENTER instead of SHIFT-ENTER. When you do that, you should see the following output:

0 =^.^=

1 =^.^=

2 =^.^=

3 =^.^=

4 =^.^=

5 =^.^=

6 =^.^=

7 =^.^=

8 =^.^=

9 =^.^=

If you made any typos, your output might look very different or you might get an error. That’s what I mean when I say computers are dumb—even a simple piece of code must be perfect for a computer to understand what you want it to do!

image with no caption

I won’t go through exactly how this code works for now (we’ll return to this program in Chapter 8), but let’s look at some of the features of this program and of JavaScript programs in general.

Syntax

Our program includes lots of symbols, including parentheses (), semicolons ;, curly brackets {}, plus signs +, and a few words that might seem mysterious at first (like var and console.log). These are all part of JavaScript’s syntax—that is, JavaScript’s rules for how to combine symbols and words to create working programs.

When you’re learning a new programming language, one of the trickiest parts is getting used to the rules for how to write different kinds of instructions to the computer. When you’re first starting out, it’s easy to forget when to include parentheses, or to mix up the order in which you need to include certain values. But as you practice, you’ll start to get the hang of it.

In this book, we’ll go slow and steady, introducing new syntax little by little so that you can build increasingly powerful programs.

Comments

The first line in our cats program is this:

// Draw as many cats as you want!

This is called a comment. Programmers use comments to make it easier for other programmers to read and understand their code. The computer ignores comments completely. Comments in JavaScript start with two forward slashes (//). Everything following the slashes (on the same line) is ignored by the JavaScript interpreter, so the comments don’t have any effect on how a program is executed—they are just there to provide a description.

In the code in this book, you’ll see comments that describe what’s happening in the code. As you write your own code, add your own comments. Then when you look at your code later, your comments will remind you how the code works and what’s happening in each step.

There’s another code comment on the last line of our program. Remember, everything after that // isn’t run by the computer!

drawCats(10); // You can put any number here instead of 10.

Code comments can be on their own line, or they can come after your code. If you put the // at the front, like this:

// drawCats(10);

. . . nothing will happen! Chrome sees the whole line as a comment, even if it’s JavaScript.

Once you start reading JavaScript code out in the wild world, you’ll also see comments that look like this:

/*

Draw as many cats

as you want!

*/

This is a different style of commenting, which is typically used for comments that are longer than one line. But it does the same thing: everything between the /* and the */ is a comment that the computer won’t run.

What You Learned

In this chapter, you learned a bit about what JavaScript is and what it can be used for. You also learned how to run JavaScript using the Google Chrome browser and tried out a sample program. All of the code examples in this book, unless I say otherwise, can (and should!) be used in Chrome’s JavaScript console. Don’t just read the code—try typing things out! It’s the only way to learn to program.

In the next chapter, you’ll start learning the fundamentals of JavaScript, beginning with the three basic types of information you can work with: numbers, strings, and Booleans.

image with no caption

Chapter 2. Data Types and Variables

Programming is all about manipulating data, but what is data? Data is information that we store in our computer programs. For example, your name is a piece of data, and so is your age. The color of your hair, how many siblings you have, where you live, whether you’re male or female—these things are all data.

In JavaScript, there are three basic types of data: numbers, strings, and Booleans. Numbers are used for representing, well, numbers! For example, your age can be represented as a number, and so can your height. Numbers in JavaScript look like this:

5;

Strings are used to represent text. Your name can be represented as a string in JavaScript, as can your email address. Strings look like this:

Hi, I'm a string;

image with no caption

Booleans are values that can be true or false. For example, a Boolean value about you would be whether you wear glasses. Another could be whether you like broccoli. A Boolean looks like this:

true;

There are different ways to work with each data type. For example, you can multiply two numbers, but you can’t multiply two strings. With a string, you can ask for the first five characters. With Booleans, you can check to see whether two values are both true. The following code example illustrates each of these possible operations.

99 * 123; 12177 This is a long string.slice(0, 4);

 

"

This" true && false; false

All data in JavaScript is just a combination of these types of data. In this chapter, we’ll look at each type in turn and learn different ways to work with each type.

Note

You may have noticed that all of these commands end with a semicolon (;). Semicolons mark the end of a particular JavaScript command or instruction (also called a statement), sort of like the period at the end of a sentence.

Numbers and Operators

JavaScript lets you perform basic mathematical operations like addition, subtraction, multiplication, and division. To make these calculations, we use the symbols +, -, *, and /, which are called operators.

You can use the JavaScript console just like a calculator. We’ve already seen one example, adding together 3 and 4. Let’s try something harder. What’s 12,345 plus 56,789?

12345 + 56789; 69134

That’s not so easy to work out in your head, but JavaScript calculated it in no time.

You can add multiple numbers with multiple plus signs:

22 + 33 + 44; 99

JavaScript can also do subtraction . . .

1000 - 17; 983

and multiplication, using an asterisk . . .

123 * 456; 56088

and division, using a forward slash . . .

12345 / 250; 49.38

You can also combine these simple operations to make something more complex, like this:

1234 + 57 * 3 - 31 / 4; 1397.25

Here it gets a bit tricky, because the result of this calculation (the answer) will depend on the order that JavaScript does each operation. In math, the rule is that multiplication and division always take place before addition and subtraction, and JavaScript follows this rule as well.

The order of operations: multiplication, division, addition, subtraction

Figure 2-1. The order of operations: multiplication, division, addition, subtraction

Figure 2-1 shows the order JavaScript would follow. First, JavaScript multiplies 57 * 3 and gets 171 (shown in red). Then it divides 31 / 4 to get 7.75 (shown in blue). Next it adds 1234 + 171 to get 1405 (shown in green). Finally it subtracts 1405 - 7.75 to get 1397.25, which is the final result.

What if you wanted to do the addition and the subtraction first, before doing the multiplication and division? For example, say you have 1 brother and 3 sisters and 8 candies, and you want to split the candies equally among your 4 siblings? (You’ve already taken your share!) You would have to divide 8 by your number of siblings.

Here’s an attempt:

8 / 1 + 3; 11

That can’t be right! You can’t give each sibling 11 candies when you’ve only got 8! The problem is that JavaScript does division before addition, so it divides 8 by 1 (which equals 8) and then adds 3 to that, giving you 11. To fix this and make JavaScript do the addition first, we can use parentheses:

8 / (1 + 3); 2

That’s more like it! Two candies to each of your siblings. The parentheses force JavaScript to add 1 and 3 before dividing 8 by 4.

image with no caption

Try It Out!

Let’s say your friend is trying to use JavaScript to work out how many balloons to buy. She’s throwing a party and wants everyone to have 2 balloons to blow up. There were originally 15 people coming, but then she invited 9 more. She tries the following code:

15 + 9 * 2; 33

But that doesn’t seem right.

The problem is that the multiplication is happening before the addition. How would you add parentheses to make sure that JavaScript does the addition first? How many balloons does your friend really need?

Variables

JavaScript lets you give names to values using variables. You can think of a variable as a box that you can fit one thing in. If you put something else in it, the first thing goes away.

To create a new variable, use the keyword var, followed by the name of the variable. A keyword is a word that has special meaning in JavaScript. In this case, when we type var, JavaScript knows that we are about to enter the name of a new variable. For example, here’s how you’d make a new variable called nick:

var nick; undefined

We’ve created a new variable called nick. The console spits out undefined in response. But this isn’t an error! That’s just what JavaScript does whenever a command doesn’t

Enjoying the preview?
Page 1 of 1