1.Values and types — values come in kinds
In Lesson 1 you printed numbers and text with console.log. Each piece of data a program handles like this is called a value, and the kind of value is called its type. People can tell the character "3" from the number 3 by context, but a computer labels every value with a kind and decides what can be done with it based on that kind. Numbers can be added and multiplied; text can be joined together or have its length counted.
JavaScript has five basic types you will use most often. Numbers (number) do not distinguish between whole numbers and decimals; they are all one kind. Strings (string) are characters wrapped in quotes. Booleans (boolean) have only two values, true (true) and false (false), and play a central role in the conditionals of Lesson 3. undefined means "no value has been set yet," and null means "deliberately marked as having no value." There is also bigint for very large integers and symbol for unique markers, but this course rarely uses them.
You can check the kind of a value with the typeof operator. The result is a string containing the name of the type. There is one long-standing exception: typeof null gives "object", not "null". It is a leftover from JavaScript's early design, and it stays because changing it now would break existing web pages. So when you want to check whether a value is null, use the === null comparison you will learn in Lesson 3 instead of typeof.
console.log(typeof 42, typeof 3.14);
console.log(typeof "hello", typeof "42");
console.log(typeof true, typeof undefined);
console.log(typeof null); // a long-standing exceptionnumber number string string boolean undefined object
| Type | Examples | `typeof` result | Used for |
|---|---|---|---|
| Number | 42, 3.14, -7 | "number" | Calculations such as counts, amounts, and scores |
| String | "Alex", '42' | "string" | Text you do not calculate with, such as names, sentences, and phone numbers |
| Boolean | true, false | "boolean" | Yes/no, decisions in conditions |
undefined | undefined | "undefined" | A value that has not been set yet |
null | null | "object" (exception) | Deliberately marking that there is no value |
2.Variables — name tags with `let` and `const`
To use the same value several times or to keep a calculation result for a while, you need to give the value a name. That name is called a variable. A variable is less like a box and more like a name tag attached to a value. When you write const price = 1200;, the name tag price is attached to the value 1200, and from then on writing just price refers to 1200. Here = does not mean "equals" as in math; it means "put the value on the right into the name on the left."
There are two ways to create a variable. A const variable cannot be given a different value once it is set, while a let variable can be changed to a different value later. A good habit is to use const by default and use let only when the value has to change (when accumulating a total or counting things, for example). That way the code shows which values never change, which reassures the reader, and if you overwrite one by mistake you get an error right away. The var you see in old code is an older style with confusing rules, so new code does not use it.
Choose names that say what they hold. price and totalCount are far easier to read than a or x2. In JavaScript, when joining several words it is common to capitalize the first letter of every word after the first (totalPrice). A name cannot start with a digit or contain spaces, and you cannot use reserved words such as let or if. Names are case-sensitive, so price and Price are different variables.
const; values that change use letconst price = 1200;
const count = 3;
const total = price * count;
console.log("Total:", total);
let visits = 0;
visits = visits + 1;
visits = visits + 1;
console.log("Visits:", visits);Total: 3600 Visits: 2
const variable again stops with an error at line 3const rate = 0.05;
console.log("Rate:", rate);
rate = 0.07;
console.log("New rate:", rate);Rate: 0.05
TypeError: Assignment to constant variable.undefinedlet memo;
console.log(memo);
memo = "groceries";
console.log(memo);undefined groceries
visits = visits + 1 makes no sense as math, but in code it means "take the current value of visits, add 1, and put the result back into visits." It can be shortened to visits += 1. You will use this accumulation pattern constantly with the loops in Lesson 4.3.Operators — calculating and joining
Besides the four basic operations +, -, *, and /, numbers have % for the remainder and ** for exponents. % is used more often than you might think. If a number divided by 2 leaves a remainder of 0, it is even, and you can turn a time in minutes into "hours and minutes" with the quotient and remainder of dividing by 60. The order of operations is the same as in math, so multiplication and division come before addition and subtraction; if in doubt, add parentheses to make your intent clear.
Even when a division does not come out even, JavaScript answers with a decimal. 7 / 2 is 3.5. If you need only the whole part, use Math.floor to drop the decimals; use Math.round to round and Math.ceil to round up. Dividing by 0 does not cause an error but gives Infinity, and a calculation that cannot produce a number gives NaN, which means "not a number." Remember also that, despite its name, NaN is a special number value whose typeof is "number".
+ also works on strings. Adding two strings with + joins them. "Hello, " + "world" becomes "Hello, world". To put the value of a variable inside a string, a "template literal" is handy: you wrap the string in backticks (the key usually to the left of the 1 key) and put the variable inside a dollar sign and curly braces. See what it looks like in the code example below. Lesson 7 covers strings in more detail.
% is the remainder, ** is the exponentconsole.log(7 + 2, 7 - 2, 7 * 2, 7 / 2);
console.log(7 % 2, 2 ** 10);
console.log(Math.floor(7 / 2), Math.round(2.5));
console.log(Math.ceil(2.1), 1 / 0);9 5 14 3.5 1 1024 3 3 3 Infinity
const minutes = 135;
const h = Math.floor(minutes / 60);
const m = minutes % 60;
console.log(h + " h " + m + " min");
console.log(`${h} h ${m} min`);2 h 15 min 2 h 15 min
4.The coercion trap — why is `"1" + 2` equal to `"12"`?
When you mix values of different kinds in a calculation, JavaScript does not raise an error; it converts one side on its own and carries on. This is called implicit type coercion. It is sometimes convenient, but it is a major source of beginner mistakes. The most famous example is "1" + 2. If either side of + is a string, JavaScript treats it as joining, converts the number 2 into the string "2", and the result is "12".
But "5" - 2 is 3. -, *, and / are operations that cannot be done on strings, so this time the string is converted into a number before the calculation. Same string, same number, yet depending on the operator the result is a string or a number, so confusion is inevitable. This problem happens all the time in practice. Values read from an input box, a text file, or a CSV look like numbers but are usually strings, so if you add them as they are you get the characters strung together instead of a total (Lesson 9).
The fix is to convert to a number yourself before calculating. This is called explicit type conversion. Number("12") becomes the number 12, and if characters that cannot be read as a number are mixed in, as in Number("12 won"), the result is NaN. In the other direction, use String(12) to turn a number into a string. When a result looks odd, get into the habit of printing the type of the value with typeof first. Debugging in Lesson 8 also starts with checking "is this value the kind I think it is?"
+ is a string, it joins instead of addingconsole.log("1" + 2);
console.log(1 + 2 + "3");
console.log("5" - 2, "5" * "2");
console.log(typeof ("1" + 2));12 33 3 10 string
Number before calculatingconst a = "3000";
const b = "4500";
console.log(a + b);
console.log(Number(a) + Number(b));
console.log(Number("12 won"), Number(""));
console.log(String(12) + String(3));30004500 7500 NaN 0 123
- If a sum comes out strangely long, suspect that strings were joined together
- Convert values read from outside (input, files, tables) with
Numberbefore calculating - If
NumbergivesNaN, non-numeric characters (units, commas, and so on) are mixed in - Watch out: the empty string
""becomes0withNumber— decide whether a blank cell should count as 0 or be handled separately
5.`0.1 + 0.2` is not `0.3`
If you print 0.1 + 0.2 in the playground, you get 0.30000000000000004. It is not that JavaScript cannot do arithmetic. Computers store numbers in binary, and the decimal 0.1 is a never-ending fraction in binary, so it gets cut off very slightly when it is stored in a fixed number of digits. It is the same reason you cannot write 1/3 out completely in decimal as 0.333…. This method (floating point) follows the same standard in almost every programming language, so the same thing happens in other languages too.
The error is tiny and does not matter in most calculations, but there are two cases where you need to be careful. The first is comparing for equality. 0.1 + 0.2 === 0.3 is false. The second is calculations like money, where even one unit off is not acceptable. Adding and multiplying decimals many times can let small errors pile up until they show in the displayed result.
There are three common fixes. If you convert to whole numbers of the smallest unit, such as won or cents, no error arises while you add, subtract, and multiply whole numbers (as long as the numbers are not enormous). If division is involved, round once, at the end. Only when displaying, match the number of decimal places with toFixed or round with Math.round. When comparing, check whether the difference between the two values is very small. The playground's grader also treats decimal results as equal when they differ by a tiny amount. Just do not forget that the result of toFixed is a string, not a number.
toFixed returns a stringconsole.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log((0.1 + 0.2).toFixed(2));
console.log(typeof (0.1 + 0.2).toFixed(2));0.30000000000000004 false 0.30 string
// $1.10 + $2.20 calculated in cents (whole numbers)
const cents = 110 + 220;
console.log(cents / 100);
console.log(1.1 + 2.2);3.3 3.3000000000000003
const total = 1200 * 3;
const pay = Math.round(total * 90 / 100);
console.log("Amount to pay:", pay);Amount to pay: 3240
- Step 1 The total is whole-number arithmetic, so it is safe: 1200 * 3 = 3600.
- Step 2 Instead of multiplying by the decimal 0.9, use whole-number multiplication and division: 3600 * 90 / 100 = 3240.
- Step 3 Since the division may not come out even, apply
Math.round(orMath.floor, depending on the policy) to get whole won. - Check: 10% of 3600 is 360, so 3600 − 360 = 3,240 won, the same.
6.`null` and `undefined` — two faces of emptiness
JavaScript has two values that represent "no value." undefined is usually a value JavaScript fills in by itself. It appears when you create a variable without giving it a value, when you read a property an object does not have (Lesson 6), and when a function returns nothing (Lesson 5). null is a value people put in on purpose, as a marker meaning "I know this is empty." For example, you might put null in a phone-number field that has not been filled in yet.
Using either in a calculation gives strange results. null is treated like 0 in number calculations, so null + 1 is 1, while undefined cannot be converted to a number, so undefined + 1 is NaN. These results are more dangerous because they spread quietly, with no error message. If a total comes out as NaN, read it as a sign that an undefined slipped in somewhere in the calculation.
The bigger problem is trying to take something out of an empty value. If you try to read a property of null or undefined, the program stops with a TypeError. It is an error you often see in AI-written code too, and the cause is not handling the case where the data is empty. In Lesson 3 you will learn how to filter out such cases in advance with conditionals.
console.log(null + 1, undefined + 1);
let phone = null;
console.log("Phone:", phone);
console.log(phone.length);1 NaN
Phone: null
TypeError: Cannot read properties of null (reading 'length')📌 Key points
- The basic types are number, string, boolean,
undefined, andnull, checked withtypeof(typeof nullis the exception:"object") - Use
constby default,letonly when the value must change, and nevervar +joins instead of adding when either side is a string — convert values you read in withNumberbefore calculating- The
0.1 + 0.2error comes from storing numbers in binary; calculate money in whole units and round when displaying - If you see
NaNor aTypeError, suspect thatundefinedornullgot mixed into the calculation
🧪 Code lab
In these exercises you fill in the blanks inside a function. Functions are covered in detail in Lesson 5; for now you only need to know that a function receives values through the names in its parentheses and hands back the value after return.
Your code runs only inside an isolated sandbox in this browser and is never sent to a server. It has no network access and is stopped after 2 seconds. Edited code is saved only in this browser. Ctrl+Enter (⌘+Enter) runs it; Tab inserts two spaces (press Esc, then Tab, to move on).
JavaScript is off, so the code can't run here, but you can still read each task, its starter code, the automatic checks and a sample solution.
1Compute a total
totalPrice(price, count) takes a price price and a quantity count (both numbers) and returns the total. If the quantity is 0, the total is 0.
totalPrice(1200, 3)expected3600totalPrice(2500, 1)expected2500totalPrice(990, 0)expected0totalPrice(0, 5)expected0
💡 Hint
Multiplication is *. const total = price * count;
Show a sample solution
function totalPrice(price, count) {
const total = price * count;
return total;
}
2Add numbers written as strings
addStrings(a, b) takes two strings containing numbers (for example "3000" and "4500") and returns the sum of the two numbers as a number. Be careful: plain a + b just joins them.
addStrings("3000", "4500")expected7500addStrings("1", "2")expected3addStrings("0", "0")expected0addStrings("-5", "2.5")expected-2.5
💡 Hint
Number(a) converts the string a into a number.
Show a sample solution
function addStrings(a, b) {
return Number(a) + Number(b);
}
3Report the type name
typeName(v) returns the name of the type of the value v as a string. It works like typeof, except that for null it returns "null" instead of "object".
typeName(42)expected"number"typeName("42")expected"string"typeName(true)expected"boolean"typeName(null)expected"null"typeName("")expected"string"
💡 Hint
Put if (v === null) { return "null"; } before return typeof v;. You will learn if in detail in Lesson 3.
Show a sample solution
function typeName(v) {
if (v === null) {
return "null";
}
return typeof v;
}
4Splitting the bill
splitBill(total, people) returns how much each person pays when people people split a bill of total won. Round up to the nearest 10 won so the payment never falls short. Example: 10,000 won among 3 people is 3,333.33… won → 3,340 won.
splitBill(10000, 3)expected3340splitBill(9000, 3)expected3000splitBill(25010, 2)expected12510splitBill(0, 4)expected0splitBill(1, 1)expected10
💡 Hint
Divide by 10, round up with Math.ceil, then multiply by 10 again. An amount already in whole tens stays the same.
Show a sample solution
function splitBill(total, people) {
const each = total / people;
return Math.ceil(each / 10) * 10;
}
🤖 Try asking AI like this
Copy a prompt and replace the [ ] parts with your own situation. Don't take the answer on trust — check it against this lesson.
When a calculation gives a strange result
The JavaScript code below gives [actual value] instead of [expected value]. Show me in a table what the type (`typeof`) of each variable is on each line, and point out where type coercion happens. Show the fixed code at the end. Code: [paste code]
When you want to practice your feel for type coercion
Make 8 JavaScript type coercion problems like `"1" + 2`, `"5" - 2`, and `null + 1`. Hide the answers, and when I send the value I predict, tell me whether I was right and why. Make the last 2 problems look like real work (adding amounts read from a spreadsheet).
When reviewing money-calculation code
Review the following JavaScript code that calculates amounts and tell me where decimal errors or rounding problems could occur. Show what it would look like if it calculated in whole units of the currency, and state in comments whether it rounds or truncates. Code: [paste code]
🧰 Related tools
Tools for checking and tidying the JSON, regular expressions and text from this lesson. Don't paste real personal data or passwords.
- JSON FormatterIn JSON,
"42"(a string) and42(a number),null, andtrueare kept distinct. You can see how types show up in values in real data. - Unix Timestamp ConverterA classic example of handling dates as numbers (seconds or milliseconds). You can see how the same moment is expressed differently as a number and as a string.
- Character CounterCounting characters shows that a string that looks like a number is still just a sequence of characters.
- MDN Web Docs — JavaScript Guide: Grammar and types, Expressions and operators
- MDN Web Docs — reference pages on typeof, Number, and floating-point numbers
- General explanations of the IEEE 754 floating-point standard
Reached every goal above? Mark the lesson complete.
Storage is unavailable in this browser, so this lasts only for this page.💻 Coding Basics
- 1What Is a Program? — Breaking Work into Sequence, Choice, and Repetition
- 2Values, Variables, and Types — Putting Name Tags on Values
- 3Conditionals — Taking Different Paths Depending on the Situation
- 4Loops — Doing the Same Thing Many Times, Exactly
- 5Functions — Splitting Work into Small Named Machines
- 6Arrays and Objects — Storing and Handling Data
- 7Strings and Text — Cutting, Finding and Replacing Characters
- 8Debugging and Reading Errors — Turning Red Text into Clues
- 9Simple Automation — Spreadsheet Math and Text Cleanup in Code
- 10Reading and Verifying AI-Written Code — Tests, Security, Licenses, Privacy