Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Full-Stack Web Development — Alpha School

Lesson 9: JavaScript Basics: Variables, Types and Functions

JavaScript is the programming language of the web, and it is what turns a static page into something interactive. HTML describes content, CSS describes appearance, and JavaScript describes behaviour: what happens when a visitor clicks a button, types in a field, or scrolls to the bottom of a page. It runs in the browser, so every visitor already has it, and it is also used on servers, which you will meet in Unit 4, so learning it once opens both sides of web development. This lesson starts at the beginning: storing values in variables, the kinds of values JavaScript understands, and bundling instructions into functions you can reuse.

Variables: let, const and var

A variable is a named box that holds a value, and you create one with let or const, as in let score = 0; or const siteName = 'Alpha School';. Use const when the value will not change, and let when it will, which makes your intentions clear to anyone reading the code. The older keyword var still works, but it behaves in surprising ways, such as being visible outside the block where it was created, so modern code avoids it, and this course will not use it. Variable names should describe what they hold, using camelCase, such as totalLessons or userName, and they cannot start with a number or contain spaces. A good habit is to declare each variable where you first need it, give it a sensible starting value, and never reuse one name for two different jobs.

Types and values

JavaScript values come in a few basic types: numbers, such as 42 or 3.14; strings, text in quotes, such as 'hello'; booleans, true or false; and the special values null, meaning deliberately empty, and undefined, meaning not set yet. Arrays hold ordered lists, such as ['red', 'green', 'blue'], and objects hold named values, such as { name: 'Maya', age: 14 }. JavaScript is loosely typed, which means a variable can hold a number one moment and a string the next, and the + operator does double duty: it adds numbers but joins strings, so 2 + 3 is 5 while '2' + '3' is '23', a classic source of bugs when a value arrives as text from a form. When in doubt, check a value's type with typeof, and convert deliberately with Number() or String() rather than hoping JavaScript guesses right.

const siteName = 'Alpha School';
let score = 0;
const lessons = ['HTML', 'CSS', 'JavaScript'];

function addPoints(points) {
  score = score + points;
  return score;
}

console.log(addPoints(10)); // 10
console.log(lessons.length); // 3

Functions: reusable instructions

A function is a named block of instructions you can run whenever you need it, by writing its name followed by brackets. The function addPoints above takes a parameter called points, adds it to score, and returns the new total, and calling addPoints(10) runs those steps with points set to 10. Parameters let one function handle many cases: a function greet(name) can greet any visitor, and a function area(width, height) can calculate any rectangle. Functions can also return values, which lets you chain them together, such as const total = addPoints(5) + addPoints(5);, and they keep your code organised, because a problem split into small functions is easier to read, test and fix than one long list of instructions. Aim for functions that do one job, give them clear names that start with a verb, and write them before you need them, not after the code gets tangled.

Running JavaScript and reading errors

You can run JavaScript in three places: in the browser console, opened with F12, where you can type lines and see results immediately, which is the best place to experiment; in a <script> element at the end of a page's body, which runs when the page loads; or in a separate .js file linked from the page, which is the professional choice for real projects. When something goes wrong, the console tells you what happened and on which line, and learning to read those messages is a core skill: “Uncaught ReferenceError: score is not defined” means you used a name that does not exist, usually a typo, and “Unexpected token” means a missing bracket or quote nearby. Read the error, look at the line it names, fix one thing at a time, and refresh to test again. Every developer, however experienced, spends part of every day doing exactly this.

Key Terms

JavaScript
The programming language of the web, used for behaviour and interactivity in the browser and on servers.
Variable
A named place that holds a value, created with let or const.
const / let
Keywords for declaring variables; const values do not change, let values may change.
Type
The kind of a value, such as a number, a string, a boolean, an array or an object.
Function
A named block of instructions that can be run by calling its name, optionally with parameters.
Parameter
A value a function receives when it is called, such as points in addPoints(points).
Console
The browser tool where you can run JavaScript and read error messages.

Discussion Questions

  1. Why should you use const for values that will not change, instead of let for everything?
  2. JavaScript lets a variable hold a number one moment and a string the next. Is that flexibility helpful or dangerous? Give an example.
  3. Why is it better to split a program into small functions than to write one long list of instructions?

Practice Questions

  1. Which keyword should you use for a value that will not change, and which for one that will?
  2. What is the result of '2' + '3' in JavaScript, and why?
  3. What does the function addPoints(10) do in the example above?
  4. What is the difference between null and undefined?
  5. Where is the best place to experiment with a few lines of JavaScript?
Show answers
  1. Use const for values that will not change and let for values that will. It makes your intentions clear and stops accidental changes to values that should stay fixed.
  2. '23', a string. The + operator joins strings, so when both values are strings it concatenates them instead of adding.
  3. It adds 10 to score and returns the new total. The parameter points is set to 10 for that call, so score grows by 10.
  4. null means deliberately empty; undefined means not set yet. A variable you declared but never gave a value is undefined, while null is a value you assign on purpose to mean “nothing here”.
  5. In the browser console. You can type lines, see results immediately, and read error messages without changing any files.
Keep reading to complete this lesson