Values, functions, arrays and objects
Why:HTML and CSS decide nothing: JavaScript does. Afterwards you’ll read and write short programs: keep the items of your list in an array of objects, turn them into other data with functions, and know how a type, a variable and a scope differ.
25 minutes
Read by speech synthesis (Qwen3-TTS); the voice is not a person’s.
JavaScript is the browser’s programming language. It works with typed values, keeps data in arrays and objects and processes it with functions.
A language that can decide
HTML says what is on the page. CSS says how it looks. But neither can decide anything: open a menu when it’s pressed, check that a phone number was entered in full, show only the items of a list that a visitor searched for. That takes a programming language, and the browser has exactly one: JavaScript (often shortened to JS).
A short history. In 1995 a company called Netscape (we met it in the story of the browser wars) had Brendan Eich write a language for its browser, and by his own account the first version took ten days. It got the name JavaScript because Java was fashionable, and the two share nothing but the start of the word. Then Microsoft made its own copy for Internet Explorer, and web developers lived through years of writing the same script twice. To end that, the language was handed to an organization called Ecma International. Its standard is called ECMAScript, and a new edition comes out every year. In the browser the code is run by an “engine”: V8 in Chrome and the browsers built on it, SpiderMonkey in Firefox, JavaScriptCore in Safari.
Where to write it
There are two places.
- The console in the developer tools (F12, the Console tab; you opened it on the workbench). Type a line, press Enter, see the result. It’s the best way to try something for five seconds.
- The
<script>tag on a page. The browser runs its code when parsing reaches it. Remember the pipeline from the lesson on rendering: until an ordinary script has run, HTML parsing waits, and a script at the top of the page can’t see elements that haven’t been parsed yet. The simplest way to avoid this today is<script type="module">. Such a script runs only after the page is parsed, and everything it declares stays inside it and doesn’t disturb other scripts. (The old ways were to put the script at the very end of<body>, or to add thedeferattribute.)
In a real project the code lives in a separate file (<script type="module" src="script.js"></script>). In our editor the script is written straight into the page, inside the tag, so that the checks can read your code. That’s fine, it’s the same JavaScript. We’ll say what a module is later, in the lesson on modules. For now it’s enough that “such a script can trust that the page is ready”.
Values and types
A program works with values, and every value has a type:
- a number (
number):42,3.14. Whole numbers and fractions share one type in JavaScript; - a string (
string): text in quotes,'Tablecloth'or"Tablecloth"; - a boolean (
boolean):trueorfalse, “yes” and “no”; undefined: “there is no value”, for example when a variable was declared and nothing was put into it;null: “it is empty on purpose”;- objects, which include arrays and functions (more on them below).
The typeof operator shows the type of any value: typeof 42 gives 'number'.
A value is put into a variable: a name you use to get it back later.
const price = 4500; // const: the name is tied to the value for good
let count = 0; // let: the value can be replaced later
count = count + 1; The rule is this: write const by default, and take let when the value really has to change. There’s a third word, var. Until 2015 it was the only way to declare a variable, and its rules are odd: the variable “jumps” to the top of the function and is visible where you don’t expect it. New code doesn’t use var. If you meet it in old code, it’s a sign of that code’s age.
Compare values with the triple equals sign, ===. It compares both the value and the type. The double == first tries to convert the types to match, and the results are surprising: 0 == '' is true. Get used to === and forget ==.
Types sometimes set traps. Plus can both add and glue strings, so '5' + 3 gives the string '53', while '5' - 3 gives the number 2. Values from form fields always arrive as strings, and Number('42') turns a string into a number. Try some examples:
typeof 42
'number'
Type of the result: string. typeof names the type of a value. Whole numbers and fractions share one type: number.
The answers are written in advance: the page never runs typed text as code. Try the same lines in the browser’s console.
Check yourself: what does the text 5 plus the number 3 give, and why?
The string '53'. If at least one operand is a string, plus glues text instead of adding numbers.
Objects and arrays
An object is a card: a set of “key: value” pairs. One item of your list (a service, a product, a dish) is naturally written as an object:
const item = { title: 'Portrait session', price: 'from £000' };
item.title; // 'Portrait session'
item.price; // 'from £000' An array is a numbered list. The numbers start at zero, and the length is in the length property:
const names = ['Portrait session', 'Reportage', 'Prints'];
names[0]; // 'Portrait session'
names.length; // 3 Together they give the main way to store data: an array of objects. The items list from your brief looks exactly like this, and the whole part rests on it: it’s drawn, filtered and fetched from a server. A notation very close to it is called JSON, and we’ll take it apart in the lesson on fetch.
const items = [
{ title: 'Portrait session', price: 'from £000' },
{ title: 'Reportage', price: '' }
]; Functions
A function is a named sequence of actions. You pass it data (parameters), and it returns a result (return).
function priceOf(item) {
return item.price;
}
const titleOf = (item) => item.title; // arrow notation, since 2015 The two forms do almost the same thing. The arrow form is used when the function is short and needed on the spot. A function is called by its name with parentheses: priceOf(items[0]). A function without return returns undefined.
The best habit is to make functions pure. A pure function takes data from its parameters, returns a result and touches nothing else. It’s easy to check (“I gave it this, I got that”), easy to reuse, and there’s nowhere in it for the error “someone changed my array” to hide.
Scope says where a name exists. A variable declared inside a function or a block { ... } is visible only there. You can look outward from inside, but not inward from outside. That’s why two functions can each have a variable total without mixing them up. (There’s a subtlety too: a function remembers the variables of the place where it was created. This is called a closure, and it’s what will let you keep a menu’s state in one place in the lesson on events.)
Check yourself: why does console.log(secret) outside a function give an error if secret was declared inside it?
A variable lives only in its own scope. Outside the function, there’s no such name.
map, filter, reduce: a pipeline instead of a loop
Work on a list is often described with a loop and a counter. It’s more natural and more reliable to describe it with array methods that take a function:
map(f)returns a new array of the same length:fwas applied to each item;filter(f)returns a new array of the items for whichfreturnedtrue;reduce(f, start)folds an array into one value: a sum, the largest, the cheapest;join(', ')glues an array of strings into one string.
The main property: they do not change the original array. But push, sort and splice change it in place, and programs break because of them more than anything else (“I only sorted it for display, and the list vanished somewhere else”). The methods can be joined in a chain, and it reads like a sentence:
items
.filter((item) => item.price !== '') // keep those with a price
.map((item) => item.title) // take the titles
.join(', '); // glue into a string Build a pipeline on the items of your own list. They are the same items as in the brief:
items .filter((item) => item.price !== '') .map((item) => item.title);
[ 'First service', 'Third service' ]
[
{ title: 'First service', price: '£000' },
{ title: 'Second service', price: '' },
{ title: 'Third service', price: '£000' }
]The original array is unchanged. map and filter make a new array every time and leave the old one alone. That is why you can chain them without fear of breaking anything.
Reading errors
Red lines in the console aren’t a verdict but a hint: they name the error, say what is wrong, and give the file and line. The three most common:
ReferenceError: x is not defined: a typo in a name, or a variable used outside its scope;TypeError: Cannot read properties of undefined (reading 'title'): you took a field from something that isn’t there, for exampleitems[10].titlewhen the list has three items;SyntaxError: a lost bracket, quote or comma. The script doesn’t start at all.
And console.log(value) remains the main way to look inside a program: what is in the variable at this point. Read the error whole and from the top before you change anything at random.
Practice
You’re on a 2014 site whose page is already responsive but has no script yet. Add the first one. It will take the list of your items, work out a summary and show it in the footer.
For now the data sits right in the script, copied from the markup. That is temporary: a little later (the lessons on the DOM and on fetch) we’ll teach the script to read it from the page and from a server. The code you write here will still be useful: the same functions work on any data.
Notice how the checks work. They read the text of your script: is there an array of objects with your titles, is there no var, is there no push. They don’t run the script to see what it does: you see that yourself, in the footer of the preview a line like “Items in total: 3, with a price: 3. Portrait session, Reportage…” should appear. If it doesn’t, open the console of the preview window (F12; in the console’s list of contexts choose the preview frame) and read the red line.
What was wrong with 2005
In the 2000s JavaScript was written differently. Handlers were hung straight in the markup (onclick="..."), links were given the address javascript:void(0), values were kept in global variables, and messages were shown with an alert() window. The result: logic smeared across the HTML, any name could be overwritten by another script by accident, and without scripts the links didn’t work. The browser was detected by its name (navigator.userAgent), because Internet Explorer and Netscape differed.
Something right survived: small functions with clear names, and one source of data instead of copies. And the fact that const, let and arrow functions arrived in 2015, and then the language began to get an update every year, means that code from 2025 is noticeably shorter and more reliable than code from 2005.
Practice
Preparing your page…
Test
Question 1 of 7
Cards
These cards go into your review once you finish the lesson.
What types of value does JavaScript have?
Answer
Number, string, boolean (true and false), undefined (no value), null (deliberately empty), and objects, which include arrays and functions. The typeof operator shows the type.
How does const differ from let, and why not var?
Answer
const: the name is tied to the value for good. let: the value can change. var is outdated: its scope is odd, and new code doesn’t use it. The default is const.
How does === differ from ==?
Answer
=== compares the value and the type. == converts the types first and gives surprises (0 == empty string is true). Always write ===.
What do map, filter and reduce do?
Answer
map: a new array where a function was applied to each item. filter: a new array of the items that fit. reduce: fold an array into one value. None of them changes the original array.
What is scope?
Answer
The place where a variable’s name exists. A variable from a function or block can’t be seen outside it, while an outer one can be seen from inside.
Sources
- JavaScript Guide (MDN) CC BY-SA, in English
- JavaScript basics (MDN) CC BY-SA, in English
- The Modern JavaScript Tutorial (javascript.info) link only, in English
- JavaScript (Wikipedia) CC BY-SA, in English
- Eloquent JavaScript (Marijn Haverbeke) link only, in English
Next
You now know: values and types, functions and scope, arrays and objects.