JavaScript Fundamentals
By the end of this lesson
Work with variables, functions and control flow in JavaScript.
HTML describes the content and CSS describes the appearance. JavaScript is what makes the page do something: filter the employee list as someone types, add a row when a claim is submitted, work out a total.
This lesson covers the parts of the language you need before touching the page itself: holding values, making decisions, and packaging work into functions.
const companyName = "Anvi";
let claimCount = 0;
claimCount = claimCount + 1;
const employee = {
id: "E-00417",
name: "Priya Raman",
department: "Finance",
isActive: true,
};
const departments = ["Finance", "Engineering", "Support"];
console.log(employee.name); // "Priya Raman"
console.log(departments.length); // 3- const creates a name that cannot be pointed at a different value later. Reach for it first; switch to let only when you know the value has to change.
- let creates a name you can reassign, which is what claimCount needs.
- An object is a set of named values. Reach into it with a dot: employee.name.
- An array is an ordered list. Positions start at 0, and length tells you how many items there are.
- There is a distinction worth getting straight early: const stops you reassigning the name, not changing the contents. employee.department = "Payroll" is allowed on a const object. The name still points at the same object; the object changed.
- console.log prints to the browser's console, which is the developer tools panel. It is the simplest way to see what a value actually is.
function formatAmount(amount) {
return "GBP " + amount.toFixed(2);
}
const isOverLimit = (amount, limit) => amount > limit;
function describeClaim(amount, limit = 50) {
if (isOverLimit(amount, limit)) {
return formatAmount(amount) + " needs approval";
}
return formatAmount(amount) + " is within limit";
}
console.log(describeClaim(74.5)); // "GBP 74.50 needs approval"
console.log(describeClaim(12)); // "GBP 12.00 is within limit"- A function takes inputs, does some work, and returns a result. formatAmount turns a number into text for display.
- toFixed(2) gives two decimal places as a string, so 74.5 displays as 74.50 rather than 74.5.
- The arrow form is shorter. With no braces, the expression after the arrow is what gets returned — there is no need to write return.
- limit = 50 is a default. Call describeClaim(74.5) and limit is 50; pass a second argument and it is used instead.
- Returning early from inside the if avoids an else. With several conditions this keeps functions much flatter and easier to read.
- Both forms are fine for this. The arrow form has different behaviour around the value of this, which matters once you write methods on objects — for plain functions like these, pick a style and keep to it.
Any value can be tested as a condition. These are the only values that count as false — everything else, including "0" as text and an empty array, counts as true:
- false
- 0 and -0
- "" — an empty string
- null — deliberately no value
- undefined — no value has been set
- NaN — the result of arithmetic that made no sense, such as multiplying by a word
JavaScript has two equality operators, and the difference is the source of a specific set of surprises:
| === (strict) | == (loose) | |
|---|---|---|
| What it does | Compares type and value. Different types are never equal | Converts the values to a common type first, then compares |
| "50" and 50 | false — one is text, one is a number | true — the text is converted to a number |
| 0 and "" | false | true — the empty string converts to 0 |
| null and undefined | false — they mean different things | true — the one conversion that is often genuinely useful |
| Readability | The result follows from the values you can see | Requires knowing the conversion rules to predict |
| When to use | Effectively always | Only for value == null, which checks for null or undefined in one step |
Summary
- Use const by default and let when a value must change; var is block-blind and silently redeclarable
- const prevents reassigning the name, not changing an object's contents
- Functions take inputs and return results; the arrow form returns its expression without the return keyword
- Six values are falsy, and 0 being one of them breaks the common if (value) shortcut
- Use === so comparisons follow the values you can see, and convert types deliberately
Practice
Attempt each one before opening the solution. Getting it wrong first is how the idea sticks.
Try it yourself
Read a value from a form and use it
Write a function that takes the amount an employee typed into an expense field — remember that arrives as text — plus their department, and returns one of three strings: rejected if the amount is not a valid number, needs approval over 50, or approved otherwise.
Make sure an amount of 0 is treated as a real value and not as missing.
Show solution
The conversion is the important part. Number("") is 0, which is a valid number, so checking for an empty string before converting is what stops a blank field being read as a zero claim.
Number.isFinite is a more useful check than comparing against NaN, because NaN === NaN is false and any direct comparison fails. It also rejects Infinity, which Number("1e400") produces.
Comparing with > rather than >= is a decision, not a detail. Is a claim of exactly 50 over the limit? Write the boundary down and test it, because this is where requirements are usually vague.
function reviewClaim(amountText, department) {
if (amountText.trim() === "") {
return "rejected: no amount given";
}
const amount = Number(amountText);
if (!Number.isFinite(amount) || amount < 0) {
return "rejected: amount is not a valid figure";
}
if (amount > 50) {
return "needs approval from " + department;
}
return "approved";
}
console.log(reviewClaim("0", "Finance")); // "approved"
console.log(reviewClaim("", "Finance")); // "rejected: no amount given"
console.log(reviewClaim("74.50", "Finance")); // "needs approval from Finance"
console.log(reviewClaim("abc", "Finance")); // "rejected: amount is not a valid figure"Knowledge check
Nothing is recorded and there is no score. The explanation appears either way.
Saved in this browser only.