Courses Learn Blog Contact
Get Started →
Lesson 1

Day 1: The JavaScript Mental Model

Variables, types, operators and template literals: the vocabulary every line of JavaScript is made of, and the type coercion trap that breaks a beginner's first total.

Webbo3 Level 2: JavaScript Development 18 min read Free

Webbo3 Level 2 · JavaScript Development · Day 1 of 20

The JavaScript Mental Model

Variables, types, operators and template literals: the vocabulary every line of JavaScript you ever write is made of.

By the end of today you can

  • Explain what JavaScript actually adds to a page you already built
  • Choose between const and let without guessing
  • Name the seven types you will meet all month and spot which one you are holding
  • Build a string out of live values with a template literal
  • Read your own output in the browser Console instead of guessing at it

Last month you built pages. Real ones, with flexbox, grid and Tailwind, and they looked good. But they did nothing. A button that goes nowhere. A form that forgets everything the moment you press submit. A price that never changes. Today that stops.

HTML is the structure. CSS is the appearance. JavaScript is the behaviour: the part that reacts, calculates, remembers and changes things after the page has already loaded. Every interactive thing you have ever used on the web, from the search box that suggests as you type to the cart that updates its total, is JavaScript doing exactly what you are about to learn to do.

1. Where JavaScript actually runs

JavaScript runs in an engine built into the browser. Chrome and Edge use one called V8. Firefox uses SpiderMonkey. Safari uses JavaScriptCore. You do not install anything, you do not compile anything: you hand the browser some JavaScript and it runs it, top to bottom, the moment it reaches it.

The same V8 engine, pulled out of Chrome and given a command line, is Node.js. That is the only difference worth holding in your head today. Same language, two places to run it: the browser, where it can touch the page, and Node, where it cannot but can touch your files. Every console pane in this course is real Node output, so you are already looking at the second one.

Open this now, not later

Press F12 in your browser, or right-click and choose Inspect, then open the Console tab. Type 2 + 2 and press Enter. That is a JavaScript engine answering you directly. You will live in this tab for the next four weeks.

2. Variables: a name for a value

A variable is a labelled box. You put a value in it, and afterwards you can refer to the value by the label instead of writing it out again. You will declare them two ways, and the choice is not stylistic.

JSapp.js
// const: the label can never be pointed at a different value
const priceOfData = 1500;

// let: the label can be re-pointed later
let bundlesBought = 1;
bundlesBought = 3;

console.log(priceOfData, bundlesBought);
Console

The rule professionals actually follow: reach for const first, every single time. Only change it to let when you find yourself needing to re-assign it. This is not pedantry. A const is a promise to whoever reads the code next, including you in three weeks, that this name will still mean the same thing further down the file.

Break the promise and the engine stops you immediately, which is the point:

JSapp.js
const price = 1500;
price = 2000;
Console

The one that confuses everybody

const freezes the label, not the contents. An array or object held in a const can still have things added to it or changed inside it. What you cannot do is point the label at a different array. You will meet this properly on Day 3, and it catches nearly everyone once.

JSapp.js
const cart = ['rice'];
cart.push('beans');        // fine: same array, new contents
console.log(cart);
Console
You will also see `var` in old code. Should you use it?

No. var leaks out of the block it was declared in, which produces bugs that are genuinely hard to trace, and it was effectively replaced in 2015. Recognise it when you read somebody else's code, and never write it. That is the whole of your relationship with var.

3. The types you are actually holding

Every value in JavaScript has a type, and most confusing bugs a beginner hits are really one thing: they thought they were holding one type and they were holding another. typeof tells you the truth.

JSapp.js
console.log(typeof 'Chidinma');     // text
console.log(typeof 2500);           // a number
console.log(typeof true);           // yes or no
console.log(typeof undefined);      // declared, never given a value
console.log(typeof null);           // deliberately empty
console.log(typeof { name: 'Ada' }); // a bundle of named values
console.log(typeof [1, 2, 3]);      // a list
Console

Two of those answers are worth stopping on. typeof null returns "object", which is simply a bug in the language, shipped in 1995 and never fixed because fixing it would break the web. Every JavaScript developer alive knows this and works around it. And typeof [] also returns "object", because an array is a kind of object. To ask whether something is really an array you use Array.isArray().

JSapp.js
console.log(typeof null);              // the famous mistake
console.log(Array.isArray([1, 2, 3])); // the honest answer
console.log(Array.isArray('rice'));
Console
TypeWhat it holdsExample
stringText, in quotes'Lagos'
numberWhole or decimal, one type for both2500, 19.99
booleanExactly two valuestrue, false
undefinedDeclared but never given a valuelet x;
nullDeliberately empty, set by youconst found = null;
objectNamed values bundled together{ name: 'Ada' }
arrayAn ordered list['a', 'b']

4. Operators, and the one that will bite you

Arithmetic behaves the way you expect. String concatenation with + behaves the way you expect. The trouble starts when you mix them.

JSapp.js
console.log(10 + 5);        // 15, arithmetic
console.log('10' + 5);      // the plus sign joins text instead
console.log('10' - 5);      // but the minus sign has no text meaning
console.log(10 / 3);
console.log(10 % 3);        // remainder: useful more often than you expect
Console

'10' + 5 gives "105" because + means two different things and JavaScript picks "join the text" as soon as either side is a string. '10' - 5 gives 5 because - only ever means arithmetic, so the string is converted to a number first. This is called type coercion, and it is the single most common source of "why is my total wrong" in a beginner's first week.

Where this hits you for real

Everything a user types into a form arrives as a string, even when they typed digits. Add two form values together without converting and you get "1500" + "2000" = "15002000" instead of 3500. Convert first, every time.

JSapp.js
const typedPrice = '1500';   // as it arrives from a form
const typedQty = '3';

console.log(typedPrice + typedQty);            // joined, wrong
console.log(Number(typedPrice) * Number(typedQty)); // converted, right
Console
Predict before you open: what does `Number("1,500")` give you?

NaN, which stands for Not a Number. The comma is not part of a valid number, so the conversion fails. It does not throw an error and it does not warn you: it hands back NaN and every calculation downstream quietly becomes NaN too. Strip separators before converting, and check the result with Number.isNaN() when the value came from a human.

JSapp.js
console.log(Number('1,500'));
console.log(Number('1500'));
console.log(Number.isNaN(Number('1,500')));
Console

5. Comparison: always three equals signs

There are two ways to ask whether two values are equal, and one of them lies to you.

JSapp.js
console.log(5 == '5');    // loose: converts, then compares
console.log(5 === '5');   // strict: compares type as well
console.log(0 == false);
console.log(0 === false);
Console

Make this a habit today

Use === and !== always. Use == never. There is no situation in this course where == is the right answer, and the loose version has produced enough production bugs that most professional codebases ban it outright with a linter.

6. Template literals: stop gluing strings together

You can join text with +, and for years everybody did. Backticks are better, and once you have used them for a day you will not go back.

JSapp.js
const name = 'Chidinma';
const bundles = 3;
const price = 1500;

// the old way
console.log('Hi ' + name + ', ' + bundles + ' bundles cost N' + (bundles * price));

// the readable way
console.log(`Hi ${name}, ${bundles} bundles cost N${bundles * price}`);
Console

Backticks let you drop any expression inside ${...}, including arithmetic, and they let a string run across several lines without any escaping. That second part matters more than it sounds: from Day 4 you will be building chunks of HTML out of data, and doing that with + is genuinely painful.

JSapp.js
const student = 'Musa';
const score = 84;

const report = `
Student: ${student}
Score:   ${score}
Status:  ${score >= 50 ? 'Pass' : 'Fail'}
`;

console.log(report);
Console

7. Reading your own output

console.log is not a beginner tool you grow out of. Professionals with fifteen years of experience use it constantly. Two habits make it far more useful than most people realise.

JSapp.js
const rate = 1500;
const qty = 4;

// label what you are printing, or five logs later you will not know which is which
console.log('rate:', rate, 'qty:', qty);

// print an object with its own names attached
console.table([{ item: 'Data', qty: 4, total: rate * qty }]);
Console

Do this now

Four small programs. Write each one in a file, run it, and check the output is what you predicted before you ran it. Twenty minutes each at most.

  1. Age calculator. Given a birth year, print the age this year. Then handle the case where somebody types the year as text.
  2. Transport fare. Given a fare per trip and trips per week, print the weekly and monthly cost in a template literal.
  3. Temperature converter. Convert 37 degrees Celsius to Fahrenheit with c * 9 / 5 + 32, and print both in one sentence.
  4. Score summary. Given three test scores, print the total, the average to one decimal place with .toFixed(1), and whether the average passes 50.

The one rule for tonight

Predict the output out loud before you press run, every single time. When the prediction and the output disagree, you have just found the exact edge of what you understand, and that is the most valuable thing that can happen to you this week.

JSapp.js
// Score summary: the shape of the answer, not the whole answer
const scores = [72, 65, 88];
const total = scores[0] + scores[1] + scores[2];
const average = total / 3;

console.log(`Total ${total}, average ${average.toFixed(1)}, ${average >= 50 ? 'pass' : 'fail'}`);
Console

Checkpoint

Q1. Why should `const` be your default rather than `let`?

Because it is a promise that the name will not be re-pointed later, which makes the code readable, and because the engine enforces the promise instead of leaving you to remember it. Use let only where you genuinely re-assign.

Q2. A form gives you "20" and "30". What does `"20" + "30"` produce, and why?

"2030". Both sides are strings, so + joins them instead of adding. Convert with Number() first. This is the bug you will hit in your own Day 5 project if you skip it.

Q3. What is the difference between `null` and `undefined`?

undefined is what the engine gives a variable you declared but never assigned: nobody has set it yet. null is a value you set deliberately to mean "empty on purpose". The first is an accident, the second is a decision.

Q4. Why is `typeof null` equal to `"object"`?

It is a bug from the first version of the language in 1995. It was never corrected because correcting it would break existing websites. Use value === null to test for null, not typeof.

Tick before you move on

  • I opened the Console and ran an expression in it
  • I wrote all four programs and predicted each output first
  • I hit a type coercion surprise at least once and understood why
  • I used a template literal instead of joining with plus

Quick recap

const by default, let only when you re-assign, never var · Seven types, and typeof tells you which one you are holding · + joins text as soon as one side is a string, so convert form input first · === always, == never · Backticks and ${} beat gluing strings together with plus

Tomorrow, Day 2: decisions and functions. You will turn these values into logic that chooses, and package that logic into something you can reuse.

Learn this with a real instructor

Free lessons take you a long way on your own. The full programmes add live classes, assignments, Skill Points and a certificate — built for African students.