Skip to content

8 min read

American Corners

JavaScript basics

The language that makes pages do things

So far your pages have structure from HTML and looks from CSS, but they just sit there. They cannot count, decide, or react to a click. For that you need a real programming language, and on the web that language is JavaScript. It is what lets a page respond: check a form, update a total, show and hide a message. If HTML is the frame and CSS is the paint, JavaScript is the wiring that makes the lights come on.

The good news is that you already know how to program. The loops, conditions, variables and functions you learned in Python all have close cousins here. The words and punctuation differ, but the thinking is the same.

Putting JavaScript on a page

You attach JavaScript to a page much as you attached CSS: with a tag that points to a separate file. Keep your code in a file such as script.js and load it near the end of the body.

<body>
  <h1>My page</h1>
  <script src="script.js"></script>
</body>

The <script> tag pulls in your file and runs it, so the code can act on the page. Loading it at the end of the body is a good habit: the browser builds the page first, and only then runs your script, so your code finds everything already in place.

Variables and values

A variable is a name for a value you want to keep. In JavaScript you usually create one with the keyword let, which means the value can change later, or const, which means it must not.

let score = 0;
const maxTries = 3;
score = score + 1;

Here score starts at 0 and is free to change, so the last line raises it to 1. maxTries is fixed at 3 and would raise an error if you tried to reassign it. Text values, called strings, go in quotes: let name = "Ada";. A useful way to watch what your code is doing is console.log, which prints a value to the browser's developer console.

let total = 5 + 3;
console.log(total);

That prints 8. Reach for console.log whenever you want to check what a value actually is rather than what you assume it is.

Functions

A function is a named block of steps you can run whenever you need it, so you write the logic once and reuse it. You define it with the function keyword, list any inputs in the brackets, and hand back a result with return.

function areaOfRoom(width, height) {
  return width * height;
}

let size = areaOfRoom(4, 5);
console.log(size);

areaOfRoom takes two inputs, multiplies them, and returns the answer. Calling areaOfRoom(4, 5) gives back 20, which we store in size and print. The same function works for any pair of numbers, which is the whole point: name a piece of logic once, then call it as often as you like.

Tip

JavaScript ends statements with a semicolon and wraps blocks in curly braces, just like the rules of CSS but for logic. If a function behaves oddly, check your braces match and that you actually wrote return; a function with no return hands back nothing.

A worked example: splitting a bill

Say a few friends share a meal and want to split the cost evenly, rounding each share up to the nearest whole number so nobody underpays. That is a clear job for a function.

function sharePerPerson(total, people) {
  return Math.ceil(total / people);
}

console.log(sharePerPerson(1000, 3));
console.log(sharePerPerson(1000, 4));

sharePerPerson divides the total by the number of people, and Math.ceil rounds that result up to the next whole number. With a bill of 1000 split three ways it prints 334; split four ways it prints 250. Notice how the logic lives in one place: change the numbers you pass in, and the same function answers every version of the question. That reuse, one definition and many calls, is the habit that carries straight over from your Python work into the browser.

Try this now

Create a script.js, load it from a page with <script src="script.js"></script> at the end of the body, and write one function that takes two numbers and returns something useful, like areaOfRoom. Call it with real numbers, console.log the result, then open the browser's developer console to read what it printed.

Check yourself

  1. HTML and CSS were described as structure and looks. In your own words, what does JavaScript add that neither of them can provide?
  2. What is the difference between declaring a variable with let and with const, and how would you choose between them?
  3. A function is supposed to give you a number back, but the value you print is empty. Given how functions hand back results, what is the most likely thing missing?

Where this lesson comes from

Built from

  • Data Structures and Algorithms: web development session

alphaPlan courses are built from taught programmes rather than invented for the web. Where a claim rests on an outside standard or a reported case, it is named above so you can check it rather than take our word for it.

This course was developed by alphaPlan Center from programs delivered in partnership with the American Corners network.

Found something unclear, outdated or improvable? Suggest an improvement