JavaScript the Basics: 10 Code-Along Examples

Learn JavaScript fundamentals by running them. Ten copy-and-run examples covering let and const, primitive types, typeof, objects, arrays, functions and return values, ending with a complete price calculator.

The JavaScript basics article covers the foundations everything else is built on: variables, data types, objects, arrays, and functions. This workbook turns each idea into a small runnable example, ending with the price calculator that ties them all together. Every example links a separate script.js, so open the console alongside the page and watch each concept in action.

1. Declaring variables with let

let creates a variable whose value can change later. Give it a clear, descriptive name, since that name is what makes the code readable months from now.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
let name = 'Sam';
console.log(name); // Sam
name = 'Priya'; // let allows reassignment
console.log(name); // Priya

name starts as 'Sam' and is later reassigned to 'Priya'. That reassignment is exactly what let is for: a value that is expected to change while the program runs.

2. Constants with const

const also creates a variable, but its value can never be reassigned. Use it for anything that should stay fixed, like a rate or a configuration value, so a future edit cannot accidentally change it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
const interestRate = 0.3;
console.log(interestRate); // 0.3
// interestRate = 0.5; // this line would throw a TypeError if uncommented

Uncomment that last line and rerun it, and JavaScript refuses with a TypeError, because interestRate was declared with const. Reaching for const by default, and only using let when a value genuinely needs to change, is a habit worth building early.

3. The five primitive data types

JavaScript’s simplest values fall into five primitive types: string, number, boolean, undefined, and null. Seeing one of each side by side makes the categories concrete.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
let city = 'London'; // string: text
let temperature = 18; // number: any numeric value
let isRaining = false; // boolean: true or false
let forecast; // undefined: declared but not yet assigned
let noReading = null; // null: deliberately empty
console.log(city, temperature, isRaining, forecast, noReading);
// London 18 false undefined null

undefined and null look similar but mean different things. undefined is what a variable holds before you have given it a value; null is a value you assign on purpose to mean “nothing here.” That distinction matters once you start checking for missing data.

4. Checking a type with typeof

typeof tells you which type a value is at runtime, which is useful when a value’s type is not obvious from reading the code alone, such as data arriving from a form or an API.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
console.log(typeof 'London'); // string
console.log(typeof 18); // number
console.log(typeof false); // boolean
console.log(typeof undefined); // undefined
let mystery;
console.log(typeof mystery); // undefined, since it has no value yet

Notice that typeof mystery reports "undefined" even though we never wrote that word ourselves. That is JavaScript telling you the variable exists but has not been given a value.

5. Objects group related data under one name

An object bundles several related values together as named properties, so you no longer need a separate variable for every piece of data about the same thing. Access a property with dot notation.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
const traveller = {
name: 'Sam',
city: 'London',
isMember: true
};
console.log(traveller.name); // Sam
console.log(traveller.city); // London
console.log(traveller.isMember); // true

traveller is one const, yet it holds three separate pieces of related information. Dot notation, traveller.name, is how you reach into the object and pull out a single property.

6. Arrays hold ordered lists

An array stores a list of values in order, and each item has a numeric position called an index, starting at zero. That zero-based counting is one of the classic beginner gotchas.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
const colors = ['red', 'green', 'blue'];
console.log(colors[0]); // red, the FIRST item
console.log(colors[2]); // blue, the THIRD item
console.log(colors.length); // 3, how many items are in the array

colors[0] is 'red', not colors[1], because counting starts at zero. colors.length tells you how many items there are, so the last valid index is always colors.length - 1.

7. Writing a function

A function packages up a block of code you want to reuse, taking input through parameters and running the same logic every time it is called. This one greets a person by their first and last name.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
function greet(firstName, lastName) {
console.log('Hello, ' + firstName + ' ' + lastName + '!');
}
greet('Ada', 'Lovelace'); // Hello, Ada Lovelace!
greet('Alan', 'Turing'); // Hello, Alan Turing!

firstName and lastName are parameters, placeholders that get filled in with whatever you pass when you call greet(...). Calling the same function twice with different arguments produces two different greetings without duplicating any code.

8. Returning a value from a function

A function does not have to just print something; it can compute a value and hand it back with return, so the caller can store or reuse the result.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
function addTax(price, rate) {
return price + (price * rate);
}
const total = addTax(100, 0.2);
console.log(total); // 120

Because addTax returns a value instead of just logging one, the result can be stored in total and used again later, passed to another function, or displayed on a page. return is what makes a function useful as a building block rather than a dead end.

9. Objects and arrays together

Objects and arrays combine naturally: an array can hold a list of objects, which is how you represent a collection of similar things, each with its own set of properties.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the output.</p>
</body>
</html>
const products = [
{ name: 'Keyboard', price: 80 },
{ name: 'Mouse', price: 25 },
{ name: 'Monitor', price: 300 }
];
console.log(products[0].name); // Keyboard
console.log(products[1].price); // 25
console.log(products.length); // 3

products is an array, so it still has an index and a length, but each item inside it is an object with its own named properties. products[0].name reads as “the first item’s name,” which is the everyday shape of real-world data in JavaScript.

10. Putting it together: a price calculator

This final example combines every concept from the workbook into one small, realistic tool: const for a fixed tax rate, an array of product objects, a function with a return value, and a loop-free walk through the array to build a receipt.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="script.js" defer></script>
</head>
<body>
<p>Open the console to see the receipt.</p>
</body>
</html>
const TAX_RATE = 0.2; // const: this never changes
const cart = [
{ name: 'Keyboard', price: 80 },
{ name: 'Mouse', price: 25 }
];
function priceWithTax(price) {
return price + (price * TAX_RATE); // a function that returns a value
}
let receiptTotal = 0; // let: this changes as we add each item
for (let i = 0; i < cart.length; i++) {
const item = cart[i]; // array indexing inside a loop
const finalPrice = priceWithTax(item.price);
receiptTotal = receiptTotal + finalPrice;
console.log(item.name + ': £' + finalPrice.toFixed(2));
}
console.log('Total: £' + receiptTotal.toFixed(2));
// Keyboard: £96.00
// Mouse: £30.00
// Total: £126.00

Every idea from this workbook appears here: TAX_RATE is a const because it should not change, receiptTotal is a let because it accumulates, cart is an array of objects, priceWithTax is a function that returns a value, and the loop reads through the array by index. This is exactly the kind of small, realistic program the individual concepts exist to build toward.

Work through these ten examples and you will have touched every idea in the basics guide: let and const, the five primitive types, typeof, objects, arrays, functions, and return. Once these feel automatic, you are ready for the next step in the series: operators and control flow, which is where these building blocks start making real decisions.

See you soon, Andrei.

View Comments (2)

Leave a Reply

Prev Next

Subscribe to My Newsletter

Subscribe to my email newsletter to get the latest posts delivered right to your email. Pure inspiration, zero spam.

Discover more from Discuss Data Science, Machine Learning and Analytics

Subscribe now to keep reading and get access to the full archive.

Continue reading