Running JavaScript with Node.js, and arrays
🏠The everyday picture
Until now your JavaScript lived inside a web page, like a cook who only works in one restaurant's kitchen. Node.js gives the same cook a kitchen of their own. And an array is the cook's numbered row of jars.
📘What it really is
-
Node.js runs JavaScript outside the browser, straight from the terminal. In Level 3 you'll write programs that don't need a page at all. (You met Node.js in Choosing Your Tools, Lesson 1.)
-
Install the LTS (long-term support) version from nodejs.org. Check it worked:
node --version. - Run a file with
node catalogue.js.console.lognow prints in the terminal. - An array is an ordered list. Each item has a position, its index, counted from 0:
const products = ["Notebook", "Pen", "Bag"];
console.log(products[0]); // Notebook
console.log(products.length); // 3
console.log(products[products.length - 1]); // Bag, the last item
- An array can hold anything: numbers, text, other arrays, objects. Usually every item is the same kind of thing.
conststops the variable being pointed at a different array, but the array's contents can still change.
🖱️Try it
- Install Node.js (LTS) and check
node --versionin a new terminal. - Make a folder
level-3, open it in VS Code, rungit init, and createcatalogue.js. - Put the code above in it and run
node catalogue.js. - Add a fourth product and print the new last item.
✅Quick check
An array has 5 items. What's the index of the last one?
Show the answer
- Indexes start at 0, so the last is
length - 1.
Can you add an item to an array declared with const?
Show the answer
Yes. const means the name always points to the same array; its contents can still change.
