Workbook Day 1 - JavaScript Fundamentals
Workbook Day 1 - JavaScript Fundamentals
Guide
Estimated reading time: 45 minutes
Introduction
User: Hi there! I'm completely new to JavaScript and want to learn the fundamentals. Can you help me
understand the basics?
Expert: Absolutely! I'd be happy to guide you through JavaScript fundamentals. JavaScript is one of the
most popular programming languages in the world, powering nearly every modern website. We'll cover
everything from basic syntax to more advanced concepts like loops and operators.
1. Code structure
4. Comparisons
6. Logical operators
Code Structure
User: So what's the basic structure of JavaScript code? How do I even write a simple program?
Expert: Great question! JavaScript code is made up of statements - these are commands that perform
actions. Let's start with the simplest example - showing an alert:
alert('Hello, World!');
User: That seems simple enough. Do I need to add anything special at the end of statements?
Expert: JavaScript statements are usually separated with a semicolon ( ; ). For example:
alert('Hello'); alert('World');
But for readability, we typically write each statement on its own line:
alert('Hello');
alert('World');
Expert: In many cases, JavaScript allows you to omit semicolons when you have a line break. For example:
alert('Hello')
alert('World')
This works because JavaScript uses something called "automatic semicolon insertion." However...
Best Practice: Always use semicolons to end your statements, even when they're optional! This
prevents unexpected errors and makes your code more reliable, especially as you write more complex
programs.
User: Are there any special characters or syntax I should know about for commenting code?
Expert: Yes! Comments are crucial for explaining your code. JavaScript supports two types:
/* This is
a multi-line comment
that spans multiple lines */
alert('Hello');
/*
alert('This code won't run');
alert('This also won't run');
*/
Fun Fact: The /* */ comment style comes from the C programming language, created in the
early 1970s. JavaScript borrowed many syntax elements from C and its descendants!
Variables
Variables
User: How do I store and use data in JavaScript?
Expert: For that, we use variables - they're like labeled boxes that store data. In modern JavaScript, we
declare variables using the let keyword:
User: What if I just want to declare a variable without giving it a value yet?
Convention Alert: For constants that are known before execution (like colors, fixed values), use
uppercase naming with underscores:
4. You can't use reserved words like let , class , return , etc.
Good variable names are descriptive and tell you what they contain:
Expert: Yes! JavaScript commonly uses "camelCase" for variable names - start with lowercase and capitalize
each new word:
Data Types
User: What kind of data can I store in JavaScript variables?
Expert: JavaScript has eight basic data types. Let me walk you through them:
let n = 123;
n = 12.345;
4. Boolean - true/false:
typeof 0 // "number"
typeof "Hello" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof alert // "function"
Quirky Detail: typeof null returns "object" , which is actually a known bug in JavaScript! Null is
not an object; it's a primitive value, but this behavior has been kept for backward compatibility.
Expert: Yes, JavaScript allows type conversion. Here are some common conversions:
String conversion:
Numeric conversion:
Boolean conversion:
Boolean(1); // true
Boolean(0); // false
Boolean(""); // false
Boolean("hello") // true
let a = 5;
let b = 2;
1. Adds numbers: 5 + 2 = 7
User: That's a bit confusing. How can I make sure something is treated as a number?
Expert: You can use the unary + operator to convert values to numbers:
// Without conversion
alert(apples + oranges); // "23" (string concatenation)
// With conversion
alert(+apples + +oranges); // 5 (numeric addition)
1. Parentheses ()
3. Multiplication/division
4. Addition/subtraction
5. Assignment =
Clarity Tip: When in doubt, use parentheses to make your intentions clear! Even when not strictly
necessary, they can make your code more readable and prevent mistakes.
let counter = 1;
counter++; // Same as counter = counter + 1
++counter; // Same as counter = counter + 1
let a = 1;
let b = ++a; // a = 2, b = 2
let c = 1;
let d = c++; // c = 2, d = 1
Comparisons
User: How do I compare values in JavaScript?
Expert: We use comparison operators that return boolean values (true or false):
Expert: Strings are compared letter-by-letter, using the Unicode value of each character:
alert('Z' > 'A'); // true
alert('Glow' > 'Glee'); // true
alert('Bee' > 'Be'); // true
The comparison works alphabetically, but remember it's case-sensitive - capital letters are "less than"
lowercase:
Expert: When comparing different types, JavaScript converts the values to numbers:
Equality Quirk: null == undefined is true in JavaScript, but null or undefined are not equal to
any other value. This is a special case in the language!
Expert: Yes! Use the strict equality operator === and strict non-equality operator !== :
Best Practice: Use strict equality ( === ) and strict inequality ( !== ) whenever possible to avoid
unexpected type conversions. This makes your code more predictable and reduces bugs!
Conditional Branching
User: How can I make my code do different things based on conditions?
if (year == 1995) {
alert('You are right!');
}
if (year == 1995) {
alert('You are right!');
} else {
alert('Wrong answer!');
}
Expert: Yes! For simple conditional assignments, you can use the ternary operator ? :
// Instead of:
let accessAllowed;
if (age > 18) {
accessAllowed = true;
} else {
accessAllowed = false;
}
// Or even simpler:
let accessAllowed = age > 18;
Expert: Yes, you can chain them, but it gets harder to read:
Logical Operators
User: How do I combine multiple conditions?
// OR examples
alert(true || false); // true
alert(false || false); // false
// AND examples
alert(true && true); // true
alert(true && false); // false
// NOT examples
alert(!true); // false
alert(!false); // true
User: I've heard that OR can also return values, not just true or false?
Expert: Very observant! Both || and && have an interesting behavior in JavaScript - they actually return
one of their operand values, not just true or false .
OR ( || ) returns the first truthy value it finds, or the last value if all are falsy:
alert(null || 0 || "" || undefined); // all falsy, returns the last value: undefined
alert(null || 0 || "Hello" || undefined); // returns "Hello" (first truthy value)
Expert: Yes! AND ( && ) returns the first falsy value it finds, or the last value if all are truthy:
alert(1 && 2 && null && 3); // returns null (first falsy value)
alert(1 && 2 && 3); // all truthy, returns the last value: 3
Shortcut Evaluation: These behaviors of && and || are called "short-circuit evaluation" - the
operators stop evaluating as soon as they can determine the result. This can be used to execute code
conditionally!
User: What is the nullish coalescing operator? I've seen it in some code.
Expert: The nullish coalescing operator ( ?? ) is a newer addition to JavaScript. It's similar to || but with an
important difference:
let height = 0;
This is incredibly useful when you want to provide default values only for null/undefined, but treat 0, empty
strings, and false as valid values!
Loops
User: How can I repeat code multiple times?
Expert: Loops are perfect for that! JavaScript has several types of loops, but let's start with the most
common ones:
let i = 0;
while (i < 3) {
alert(i);
i++;
}
// Shows 0, then 1, then 2
2. Condition: Checked before every iteration - if false, the loop stops ( i < 3 )
Loop Tip: You can omit any part of the for loop, but don't forget the semicolons! For example, an
infinite loop: for(;;) { ... }
Expert: You can use the break statement to exit a loop immediately:
Expert: The switch statement isn't a loop, but it's a way to replace multiple if checks. It's especially useful
when you need to compare a value against multiple variants:
let day = 2;
let dayName;
switch (day) {
case 0:
dayName = 'Sunday';
break;
case 1:
dayName = 'Monday';
break;
case 2:
dayName = 'Tuesday';
break;
// ... and so on
default:
dayName = 'Unknown';
}
alert(dayName); // 'Tuesday'
Loop History: The for loop syntax in JavaScript was inherited from the C programming language,
which was developed in the early 1970s. Many modern programming languages use this same loop
structure!
Practice Exercises
User: This is a lot to take in! Do you have some exercises I could try to practice these concepts?
User: These are great! I think I'm starting to understand JavaScript better now. Any final advice before I start
coding?
Success Tips:
2. Read others' code - Looking at well-written JavaScript helps you learn patterns and best
practices.
3. Use the console - The browser console (F12) is your best friend for testing and debugging.
4. Be patient with yourself - Programming is a skill that takes time to develop.
5. Build real projects - Apply what you learn by building small projects that interest you.
Remember that every expert was once a beginner. The JavaScript journey is rewarding, and I'm excited to
see what you'll build! Happy coding!
JavaScript in Action: Building a Shopping
Cart Calculator
User: Hey! I'm trying to build a simple shopping cart for an online bookstore. I need to calculate the total
price with discounts and shipping. Can you help me work through this using the JavaScript concepts we just
learned?
Expert: Absolutely! This is a perfect project to practice variables, operators, and conditional statements.
Let's break it down step by step.
User: Great! So I need to track the book prices, quantities, maybe apply discounts if the total is over a
certain amount, and add shipping costs unless they order enough for free shipping.
Expert: That's a perfect scenario! Let's start by defining our variables. What variables do you think we'll
need?
User: Hmm, I guess we need variables for the prices, quantities, and then some for the calculations?
// Book information
let bookPrice1 = 12.99;
let bookPrice2 = 9.99;
let bookPrice3 = 15.50;
// Quantities
let quantity1 = 2;
let quantity2 = 1;
let quantity3 = 3;
// For calculations
let subtotal = 0;
let discount = 0;
let shipping = 4.99;
let finalTotal = 0;
Now let's calculate the subtotal. How would you use operators to do this?
User: I think I would multiply each book price by its quantity and then add them all together?
// Calculate subtotal
subtotal = (bookPrice1 * quantity1) + (bookPrice2 * quantity2) + (bookPrice3 * quantity3);
User: What value would this give us? Let me try to calculate... that's $12.99 × 2 + $9.99 × 1 + $15.50 × 3 =
$25.98 + $9.99 + $46.50 = $82.47, right?
Expert: That's correct! Now let's add some conditional logic for discounts:
User: I think I'd use if and else if statements to check the subtotal amount:
Expert: Excellent! That's exactly right. Next, let's handle the shipping cost. If the subtotal (before discount) is
over $50, shipping should be free. How would you write this condition?
Expert: Yes, that's perfect! Now let's calculate the final total by putting it all together:
User: Great! Can we put everything together and test some different scenarios?
Expert: Absolutely! Here's the complete code, and we'll test it with our current values:
// Book information
let bookPrice1 = 12.99;
let bookPrice2 = 9.99;
let bookPrice3 = 15.50;
// Quantities
let quantity1 = 2;
let quantity2 = 1;
let quantity3 = 3;
// For calculations
let subtotal = 0;
let discount = 0;
let shipping = 4.99;
let finalTotal = 0;
// Calculate subtotal
subtotal = (bookPrice1 * quantity1) + (bookPrice2 * quantity2) + (bookPrice3 * quantity3);
1. Subtotal = $82.47
User: That makes sense! What if I wanted to add a coupon code discount that would apply after the regular
discount?
Expert: Great idea! Let's add that. We'll need a new variable for the coupon code and its discount:
let couponCode = "BOOKS10";
let couponDiscount = 0;
User: What if I want to check if the customer is a member, and if they are, give an additional 5% off?
User: This is getting complex! Could we use the ternary operator anywhere to simplify our code?
Expert: Yes! The ternary operator would be perfect for the shipping calculation:
// Instead of:
if (subtotal > 50) {
shipping = 0;
}
// We could write:
shipping = (subtotal > 50) ? 0 : 4.99;
Tip: When building e-commerce calculations, always round monetary values appropriately and be
careful with floating-point arithmetic. JavaScript's math with decimals can sometimes produce tiny
rounding errors. For critical financial applications, consider using libraries designed for precise money
calculations!
User: Thanks! I feel much more confident now about using variables, operators, and conditional statements
in a practical scenario. Can you suggest how I might extend this for a full shopping cart with any number of
items?
Expert: For a full shopping cart with variable items, you'd want to use arrays and loops, which we'll cover
next! But your foundation with variables, operators, and conditionals is exactly what you needed to
understand first. Great job working through this problem!