JavaScript Fundamentals — Values, Variables and Control Flow
How JavaScript runs in the browser and Node.js, let and const, types and coercion, operators, conditionals, and loops.
JavaScript Gives a Page Behaviour
HTML describes content, CSS describes its appearance, and JavaScript describes behaviour. A product listing can be marked up as HTML and styled with CSS; JavaScript can respond when a learner filters courses, checks a form, or adds an item to a basket. Browsers run JavaScript directly. Node.js also runs JavaScript outside the browser, which lets teams write command-line tools and server applications with the same language.
A JavaScript engine reads source code, evaluates expressions, and executes statements. You can experiment in a browser developer console or a Node.js REPL. The same basic language rules apply in both places, but browser features such as document are not available in Node.js. Do not confuse the language with its host environment.
Start with a value and an expression. An expression produces a value; a statement performs an action such as storing a value or choosing which code to run.
const course = 'JavaScript & TypeScript'
const lessonNumber = 1
const welcome = 'Welcome to ' + course
console.log(welcome)
console.log(lessonNumber + 1)console.log is a built-in function that prints information to a developer console. It is useful while learning and debugging, but production applications usually send useful diagnostics through an intentional logging system rather than leaving temporary messages everywhere.
Use const by Default, and let When Reassignment Is Required
A variable is a named reference to a value. Declare it with const when you will not assign a different value to that name. Choose let when a later step must reassign it. Avoid var in new code: its older function-scoped behaviour is less predictable than block-scoped let and const.
const platformName = 'Chaduvuko'
let completedLessons = 0
completedLessons = completedLessons + 1
console.log(platformName, completedLessons)const prevents reassignment of the variable, not mutation of an object it refers to. This distinction matters: a constant object can still have a property changed. Prefer to create updated copies when application state should be treated as immutable; it makes changes easier to reason about and test.
const learner = { name: 'Asha', city: 'Visakhapatnam' }
learner.city = 'Vijayawada' // property changes; the binding is still the same
// learner = { name: 'Asha' } // TypeError: cannot reassign a const bindingJavaScript distinguishes uppercase and lowercase letters. total and Total are different names. Use descriptive lower camel case for variables and functions, and use consistent naming within a project.
Understand Types Before Doing Work with Them
JavaScript has primitive values such as strings, numbers, booleans, undefined, null, and symbols. Objects—including arrays and functions—are reference values. A value's type influences what operations make sense. For example, adding two numbers performs arithmetic, while adding strings joins text.
| Value | Example | Notes |
|---|---|---|
| String | 'JavaScript' | Text; quote style is a team convention |
| Number | 42 or 19.5 | One number type includes whole and fractional values |
| Boolean | true or false | Useful for decisions and flags |
| Undefined | let result | A declared binding without an assigned value |
| Null | const selected = null | An intentional absence of a value |
| Object / array | { city: 'Guntur' } / [1, 2] | Structured collections of related data |
A declaration without an initial value starts as undefined. Use null when your program deliberately represents an empty or not-yet-selected value. JavaScript has a historical quirk: typeof nullreturns object. Check for null directly with value === null.
const studentName = 'Ravi'
const credits = 3
const isEnrolled = true
let selectedMentor
const selectedTrack = null
console.log(typeof studentName) // 'string'
console.log(typeof credits) // 'number'
console.log(typeof isEnrolled) // 'boolean'
console.log(selectedMentor) // undefined
console.log(selectedTrack === null) // trueBe careful with automatic type conversion, called coercion. In loose expressions JavaScript may convert a string to a number or combine values in surprising ways. For example, '5' + 1 becomes '51', while'5' - 1 becomes 4. Prefer explicit conversion and strict equality so the intention is visible to the next reader.
const rawCount = '5'
const count = Number(rawCount)
if (Number.isNaN(count)) {
console.log('Enter a valid number')
} else {
console.log(count + 1) // 6
}
console.log(5 === '5') // falseCombine Values Without Hiding Your Intent
Arithmetic operators include +, -, *, /, and remainder%. Comparison operators such as >, <=, and === produce booleans. Logical operators combine boolean conditions. Parentheses make a complex expression easier to read and remove uncertainty about which operation runs first.
const priceRupees = 499
const quantity = 2
const subtotal = priceRupees * quantity
const hasCoupon = true
const eligibleForDiscount = subtotal >= 500 && hasCoupon
const total = eligibleForDiscount ? subtotal - 50 : subtotal
console.log({ subtotal, eligibleForDiscount, total })The conditional (ternary) operator is useful for a small choice that returns one of two values. Use anif statement when branches require multiple steps. Avoid deeply nested ternaries; simple, named intermediate values are easier to debug.
Falsy values include false, 0, an empty string, null, andundefined. A truthy check is concise, but can accidentally treat a meaningful zero as missing. Use an explicit comparison when zero is valid data.
const seatsAvailable = 0
if (seatsAvailable > 0) {
console.log('Seats are available')
} else {
console.log('The class is full')
}Use Conditions to Describe Business Rules
An if / else if / else chain runs the first matching branch. Write the most specific or most restrictive case first when order matters. A switch can make a fixed set of possible values clear; remember to return or break from each case so execution does not fall through unintentionally.
const score = 82
let result
if (score >= 90) {
result = 'Excellent'
} else if (score >= 70) {
result = 'Ready for the next module'
} else if (score >= 0) {
result = 'Review the practice and try again'
} else {
result = 'Score must not be negative'
}
console.log(result)Validate input at boundaries. A value read from a form, URL, or API should not be assumed valid just because it has the expected shape in your local test. Check its type, range, and allowed values before using it.
- Identify the input and what values are valid.
- Convert text to the type you need explicitly.
- Reject invalid values before applying business rules.
- Handle each valid branch and provide a useful fallback.
Choose a Loop That Matches the Job
A for loop is helpful when you need an index or a known range. A while loop repeats while a condition stays true, so make sure its body can eventually change that condition. For processing each item in a collection, for...of is often the clearest option. Avoid modifying a loop counter in several places.
const lessonNames = ['Values', 'Functions', 'The DOM']
for (const lessonName of lessonNames) {
console.log('Next up:', lessonName)
}
let attemptsRemaining = 3
while (attemptsRemaining > 0) {
console.log('Attempts left:', attemptsRemaining)
attemptsRemaining -= 1
}Loops are not only for printing. They can total values, build a lookup, or validate each record. Later you will learn array methods such as map and filter, which express common transformations declaratively. First, understand the basic repeated operation and its stopping condition.
const lessonMinutes = [12, 18, 15]
let totalMinutes = 0
for (const minutes of lessonMinutes) {
totalMinutes += minutes
}
console.log('Total:', totalMinutes)For large or untrusted collections, also consider the amount of work and memory your code uses. Avoid accidental infinite loops, and do not assume every API response contains a small, well-formed list.
Make Errors Useful Instead of Mysterious
Read the first error message and its line number, inspect nearby values, and reduce the problem to a small example. The browser console and Node.js both show runtime errors. A syntax error prevents parsing; a runtime error occurs while the program runs; a logic error runs successfully but gives the wrong result. The fix depends on which kind you have.
const rawPrice = 'not-a-price'
const price = Number(rawPrice)
if (Number.isNaN(price)) {
console.error('Price input is not a number:', rawPrice)
} else {
console.log(price * 2)
}Temporary logs are fine while learning. Before shipping, remove noisy debug output and avoid logging passwords, payment details, access tokens, or other sensitive values. In a shared team, formatters and linters help catch inconsistent code before it becomes a runtime problem.
Common Mistakes
Using var in a new example
Why: Its function scope and redeclaration rules differ from modern block-scoped declarations.
Fix: Use const for stable bindings and let when reassignment is needed.
Comparing with == by habit
Why: Loose equality converts values and can make unrelated types compare equal.
Fix: Prefer === and convert input explicitly when conversion is intentional.
Treating zero as missing
Why: A truthiness check considers 0 falsy even when it is a valid count or amount.
Fix: Compare explicitly, such as seatsAvailable > 0 or value !== null.
Adding a numeric string without converting it
Why: The + operator also concatenates strings, so "5" + 1 becomes "51".
Fix: Convert at the input boundary with Number and validate using Number.isNaN.
Model a Course Signup Decision
Practice
Write small rules and verify their edge cases
- Declare a learner name, course title, and completed lesson count with const; use let for a value you deliberately update.
- Convert a form-like string such as "4" to a number, then reject an empty or invalid value.
- Write an if / else chain that classifies a practice score into three useful feedback messages.
- Loop through an array of lesson durations and calculate the total time.
- Test your logic with zero, a negative number, and an unexpected string; explain the output in each case.
Hint: Keep input validation separate from the rule that decides the learner's next step.
🎯 Key Takeaways
- ✓JavaScript runs in browsers and Node.js; host APIs differ even though the language is shared.
- ✓Use const by default and let only when a binding must be reassigned; avoid var in modern code.
- ✓Know whether a value is a string, number, boolean, null, undefined, or object before using it.
- ✓Use strict equality and explicit conversions to avoid surprising coercion.
- ✓Conditions express decisions, and loops repeat work until a clear stopping condition is met.
- ✓Validate input and keep browser-side checks separate from authoritative server-side rules.
- Prerequisite: HTML & CSS.
Next
What comes next
You can express values and control flow. Next, package behaviour into reusable functions and model related data with objects and arrays.
Lesson 02 · Functions, Objects and Arrays →HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
