This lesson adds decisions and calculations with JavaScript.
You will declare variables, identify value types, evaluate expressions, convert text deliberately, compare values, and write small conditions, loops and functions.
Our running task is a workshop seat check: read the available seats and reserved seats, validate the input and calculate the remaining places.
The important skill is explaining each step, including why text from a form cannot simply be treated as an already validated number.
๐ฆ
Values
Distinguish a binding from the value it currently holds.
๐งฎ
Expressions
Predict an operation from the operand types.
๐งญ
Logic
Choose a branch and stop a bounded loop correctly.
๐งช
Checks
Test ordinary, zero, blank and invalid input deliberately.
02
๐งฉHTML, CSS and JavaScript โ Three Roles
HTML gives the workshop page meaningful structure.
CSS arranges and styles its cards.
JavaScript can calculate remaining seats, react to an action and update feedback.
These roles cooperate: JavaScript does not replace a native button or make an unclear page understandable by itself.
JavaScript and Java are different languages.
The similar names do not mean the same syntax, runtime or type system.
This lesson uses JavaScript in a browser; some of the same language features also run in environments such as Node.js.
Keep useful learning content in the document even when scripting is unavailable.
Add behavior to meaningful controls rather than making a styled paragraph pretend to be a button.
Workshop page responsibilities
๐HTML
Heading, labeled inputs, button and result region.
๐จCSS
Readable layout, spacing and visible focus.
โ๏ธJavaScript
Validate values, calculate and report a result.
03
๐Language and Runtime โ Know Where Code Runs
The JavaScript language defines values, expressions, functions and control flow.
A browser supplies additional facilities such as document, event handling and developer tools.
Console is supplied by common runtimes rather than being an ECMAScript language keyword.
A page script normally runs with the pageโs environment.
Node.js supplies a different environment and does not provide a page document by default.
If a browser example uses document.getElementById, copying it into a plain Node program is not enough to create a webpage.
Use the browser console for small trusted experiments.
A console log is a diagnostic output, not automatically visible lesson content.
A real user-facing result should appear in an appropriate page element.
String length counts UTF-16 code units, so it is not always the number of user-perceived characters.
For this lessonโs numeric input, the important distinction is text versus Number, not an advanced character-counting algorithm.
11
๐Conversion and Validation Are Different
An HTML inputโs value is a string.
Number converts a whole string according to numeric conversion rules.
Number("12") becomes 12, while Number("12 seats") becomes NaN.
Number("") and Number(" ") become 0, so conversion alone does not prove that a learner entered a value.
ParseInt can read an initial integer part: parseInt("12 seats", 10) produces 12.
That behavior can be useful in another task but is unsuitable if the whole seat-count field must be valid.
Decide which format is acceptable before choosing a parser.
For this workshop, accept decimal digits only, convert them, require a safe integer in the range 0โ1000, and require reserved not to exceed capacity.
The range is a teaching policy, not a JavaScript language limit.
Zero is a valid entry; blank text is not.
function readSeatCount(text) {
const trimmed = text.trim();
if (!/^\d+$/.test(trimmed)) return null;
const value = Number(trimmed);
if (!Number.isSafeInteger(value) || value > 1000) return null;
return value;
}
Null here means invalid under our functionโs contract.
The caller must check it explicitly.
Do not use if (!value) to reject a seat count, because that would also reject the valid Number 0.
12
โ๏ธAssignment, Strict Equality and Loose Equality
The single equals sign assigns.
Strict equality, ===, compares without converting different operand types to match.
Loose equality, ==, follows coercion rules that can match differently typed values.
Use strict equality in new beginner examples when you want the type distinction to remain visible.
Both strict equality and loose equality have rules beyond a simple slogan.
NaN is not equal to itself using either operator.
Objects are compared by identity rather than by automatically comparing all properties.
A complete sameness discussion belongs after these basics.
"12" === 12; // false: different types
"12" == 12; // true: coercion in this case
12 === 12; // true
NaN === NaN; // false
let remaining = 18;
remaining = 0; // assignment, not a comparison
In an if condition, an accidental assignment can change data and then test the assigned value.
Inspect the operator carefully when a branch behaves unexpectedly.
For NaN checks, use Number.isNaN on an already converted Number.
13
๐กTruthiness and Logical Operators
Conditions can convert a value to boolean.
Falsy values include false, 0, -0, 0n, the empty string, null, undefined and NaN.
An ordinary non-empty string such as "0" or "false" is truthy.
The stringโs spelling does not make it the corresponding boolean value.
The && and || operators short-circuit and return one of their operands; they do not always produce a boolean.
The ! operator produces a boolean negation.
The ?? operator uses its fallback only for null or undefined, so it can preserve a useful zero.
Boolean("0"); // true
Boolean(0); // false
const remaining = 0;
remaining || 10; // 10: zero is falsy
remaining ?? 10; // 0: zero is not null or undefined
A default of ten remaining seats would be wrong when the real result is zero.
Match the fallback operator to the missing-value policy.
For a numeric range check, compare the numeric value explicitly rather than relying only on truthiness.
14
๐งญControl Flow โ Conditions and Bounded Loops
An if/else statement selects a branch from a condition.
Check invalid values before the main calculation.
Keep mutually exclusive outcomes clear: invalid input, overbooked capacity, full workshop, or available seats.
A loop repeats a body while its control rules permit another iteration.
A for loop states its initialization, condition and update together.
Think about the first value, final accepted value and what changes each time.
A loop whose condition never becomes false can freeze the page.
For this loop, seat begins at 1, the condition permits 1, 2 and 3, and the next update makes it 4 so the body stops.
Changing <= to < would omit Seat 3.
Start with a small bounded count before using a user-provided loop limit.
15
๐ ๏ธFunctions โ Inputs, Return Values and Scope
A function packages a task.
Parameters name incoming values; arguments are the actual values supplied at a call.
Return gives a result to the caller and ends that function invocation.
Console.log prints a diagnostic message and is not a substitute for returning the result.
A function that reaches its end without an explicit returned value yields undefined.
Put the return expression on the same line as return in these beginner examples.
A local binding belongs to its applicable scope rather than automatically becoming a global page variable.
function remainingSeats(capacity, reserved) {
return capacity - reserved;
}
const result = remainingSeats(30, 12);
console.log(result); // 18
This function assumes already validated numeric arguments.
It does not read or validate an HTML input by itself.
Keep those assumptions visible rather than claiming a two-line subtraction function handles every user entry.
Arrow functions offer another function syntax, such as const double = value => value * 2.
Learn the task and return behavior first; different syntaxes also have differences such as their handling of this, which later lessons will cover.
16
๐Premium Visualizer โ From Text to a Result
Follow a fixed workshop example through reading, validation, conversion, calculation and reporting. Use the familiar numbered timeline and playback controls. Explain why each stage is needed instead of jumping directly from a string to an assumed answer.
JAVASCRIPT VALUE TRACE
Step 1 of 5
๐ค
STEP 01
Begin with text input
The fixed teaching values are the strings "30" and "12".
capacityText = "30"
reservedText = "12"
What is happening?
Input.value provides text. Similar-looking text and numbers can behave differently.
17
๐งชPremium Interactive โ Values and Seat-Count Lab
Choose one of six explained operations and supply two text values.
The lab uses real, fixed JavaScript operations; it does not execute arbitrary pasted code.
The expression and result are displayed as text.
A and B start as strings, just as values read from ordinary inputs do.
Compare string concatenation with explicit numeric addition.
The equality examples compare string A with Number(B), which makes the type distinction visible.
The truthiness example uses A only.
The final scenario validates decimal seat counts and reports the remaining capacity.
Blank text is useful for the conversion experiment: Number("") is 0.
In the seat-count scenario, blank text is rejected.
General numeric addition requires finite converted values; the seat scenario has the stricter integer, range and relationship rules explained above.
Ready to check 30 capacity and 12 reserved.
Operation and inputs
Result and value type
18
๐ ๏ธDebugging โ Find the First Wrong Assumption
๐
Load
Check the external script path and the first console error.
๐ท๏ธ
Type
Inspect the value and typeof before an unexpected operation.
๐
Input
Distinguish blank, invalid, converted and accepted input.
๐งญ
Flow
Check the selected branch, loop boundary and returned value.
A SyntaxError indicates a parsing problem, such as an unmatched bracket.
A ReferenceError can indicate an unknown identifier or a binding accessed too early.
A TypeError can arise from an operation inappropriate for the value, such as reading a property from null.
Read the first relevant message and its location before editing unrelated CSS.
If addition creates 3012, check whether both operands are strings.
If a zero count is rejected, look for a truthiness check that treats zero as missing.
If a function call returns undefined, inspect its return path rather than assuming the console output was returned.
After a correction, repeat the case that failed and one neighboring case.
For the workshop, capacity 30/reserved 12 should give 18; capacity 30/reserved 30 should report full; capacity 30/reserved 31 should be rejected.
19
๐ฌInterview Questions โ Flip to Explain
QUESTION
What does dynamically typed mean?
Click or press Enter to explain
ANSWER
Bindings can hold values of different types over time. The values still have types that affect operations.
QUESTION
Does const make an object immutable?
Click or press Enter to explain
ANSWER
No. It prevents reassignment of that binding; allowed properties of the referenced object can still change.
QUESTION
Why can "30" + "12" produce "3012"?
Click or press Enter to explain
ANSWER
The operands are strings, so + concatenates them. Convert deliberately before numeric addition.
QUESTION
Is Number conversion enough to validate a seat count?
Click or press Enter to explain
ANSWER
No. Blank text converts to zero, and other results still need format, integer, range and relationship checks.
QUESTION
How do === and == differ?
Click or press Enter to explain
ANSWER
Strict equality does not coerce different types to match. Loose equality applies coercion rules, which can match a string and number.
QUESTION
Why is "0" truthy while 0 is falsy?
Click or press Enter to explain
ANSWER
The first is a non-empty string; the second is numeric zero. Truthiness depends on the actual value.
QUESTION
What is the difference between returning and logging?
Click or press Enter to explain
ANSWER
Return supplies a result to the function caller and ends the invocation. Logging prints a diagnostic output.
QUESTION
Why can <= and < change a loop result?
Click or press Enter to explain
ANSWER
They include or exclude the boundary value. Trace initialization, condition, update and the intended final iteration.
20
โMCQ Practice โ Predict Before Running
PRACTICE
1. Which binding should you use when reassignment is intended?
PRACTICE
2. What does const prevent?
PRACTICE
3. What is the result of "3" + "4"?
PRACTICE
4. What does Number("") produce?
PRACTICE
5. What does typeof null produce?
PRACTICE
6. What is the result of "12" === 12?
PRACTICE
7. Which ordinary value is truthy?
PRACTICE
8. What does 0 ?? 10 produce?
PRACTICE
9. What does 2 + 3 * 4 produce?
PRACTICE
10. How many body executions occur for i = 1; i <= 3; i += 1?
PRACTICE
11. What does a function return when it ends without a returned value?
PRACTICE
12. Under this lessonโs seat policy, capacity 30 and reserved 31 should beโฆ
21
๐ปExtra Practice โ Specific Inputs and Expected Results
๐ค
Text addition
Use A="3", B="4" in concatenation. Expected: string "34". Switch to numeric addition: number 7.
๐ญ
Blank input
Use A="", B="4" in numeric addition. Expected: 4 after conversion. Seat validation must reject the blank capacity.
โ๏ธ
Equality
Use A="12", B="12". Expected: strict comparison against Number(B) is false; loose comparison is true.
๐ก
Zero text
Use A="0" in Boolean(A). Expected: true. Compare Boolean(0) in your own small script: false.
๐ช
Available seats
Use capacity 30 and reserved 12. Expected: 18 available.
๐ซ
Invalid reservation
Use capacity 30 and reserved 31. Expected: relationship error; do not report a negative availability.
๐
Loop boundary
Print seat numbers 1โ3 with <=. Expected: three lines. Switch to <: two lines.
๐ ๏ธ
Function return
Write a pure subtraction function with validated numeric arguments 10 and 4. Expected returned Number: 6.
22
๐Quick Revision
๐ฆBinding: Use const by default and let for intended reassignment.
๐ท๏ธTypes: A text numeral and a Number are different values.
๐Inspection: typeof is useful but not complete validation.
๐งฎOperators: Read operand types and precedence before predicting.
๐คStrings: + may concatenate; templates build clear messages.
๐Conversion: Convert deliberately and validate the required format.
โ๏ธComparison: Distinguish assignment, strict equality and coercion.
๐กTruthiness: Zero and missing input are not interchangeable.
๐งญControl flow: Trace branches and loop boundaries explicitly.
๐ ๏ธFunctions: Separate inputs, local logic and returned results.
23
๐Glossary โ Flip to Learn
TERM
Binding
Click to see meaning
DEFINITION
Binding
A name associated with a value in an applicable scope.
TERM
Expression
Click to see meaning
DEFINITION
Expression
Code evaluated to produce a value.
TERM
Statement
Click to see meaning
DEFINITION
Statement
A unit of code that performs an action or controls execution.
TERM
Primitive
Click to see meaning
DEFINITION
Primitive
A value in a primitive type category, such as string, number or boolean.
TERM
Coercion
Click to see meaning
DEFINITION
Coercion
An implicit type conversion performed according to an operationโs rules.
TERM
Validation
Click to see meaning
DEFINITION
Validation
Checking whether input meets the taskโs stated acceptance rules.
TERM
Truthy
Click to see meaning
DEFINITION
Truthy
A value that converts to true in a boolean context.
TERM
Scope
Click to see meaning
DEFINITION
Scope
The region of code in which a binding is available under its rules.
TERM
Parameter
Click to see meaning
DEFINITION
Parameter
A named input in a function definition.
TERM
Return value
Click to see meaning
DEFINITION
Return value
The result supplied by a function invocation to its caller.
24
๐Final Challenge โ Explain a Workshop Seat Check
Write a small program that accepts two text values under the lessonโs decimal-digit policy.
Return a clear error for blank or malformed input, values above 1000, or reserved seats exceeding capacity.
Otherwise calculate the remaining count and select either โWorkshop fullโ or a message with the available count.
Separate a readSeatCount helper from the arithmetic and reporting decisions.
Check null explicitly so the valid zero survives.
Use const where a binding is not reassigned, strict equality for the full check and a template literal for the available message.
Explain the rejection stage, not just the final printed word.
Success criterion: predict the value and type at each stage, demonstrate a meaningful return value, preserve zero correctly and explain a loop boundary.
Level 15 will extend these foundations to arrays, objects and practical data logic.
25
โ Level 14 Complete?
Before marking complete, explain one concatenation surprise, one strict comparison, one zero-versus-blank check, a bounded loop and a returned function value. Completion records a local learning milestone; it is not an assessment score.