diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..fb5b4c654 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -4,3 +4,6 @@ count = count + 1; // Line 1 is a variable declaration, creating the count variable with an initial value of 0 // Describe what line 3 is doing, in particular focus on what = is doing +//Line 3 is doing: - count = count + 1; is incrementing the value of the count variable. +//This operation reads the current value of count, adds 1 to it, and then reassigns the new value back to count. +// The = symbol is the assignment operator, Take the value on the right side, and store it into the variable on the left side. \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..b85c0b24c 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -9,3 +9,5 @@ let initials = ``; // https://www.google.com/search?q=get+first+character+of+string+mdn +let initials = firstName[0] + middleName[0] + lastName[0]; +console.log(initials); \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..0d1fe566a 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -17,7 +17,7 @@ console.log(`The base part of ${filePath} is ${base}`); // Create a variable to store the dir part of the filePath variable // Create a variable to store the ext part of the variable -const dir = ; -const ext = ; - +const dir = filePath.slice(0, lastSlashIndex); +const dotIndex = base.lastIndexOf("."); +const ext = base.slice(dotIndex); // https://www.google.com/search?q=slice+mdn \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/4-random.js b/Sprint-1/1-key-exercises/4-random.js index 292f83aab..ce37dbe0f 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -2,8 +2,29 @@ const minimum = 1; const maximum = 100; const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; +console.log(num); -// In this exercise, you will need to work out what num represents? +/// In this exercise, you will need to work out what num represents? // Try breaking down the expression and using documentation to explain what it means +//num stores a random whole number in the range from the minimum value (1) to the maximum value (100), including both ends. +// Try breaking down the expression and using documentation to explain what it means? // It will help to think about the order in which expressions are evaluated // Try logging the value of num and running the program several times to build an idea of what the program is doing +//const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; +//This line generates a random integer between minimum and maximum, inclusive. Here's a breakdown: +//Math.random() returns a decimal in the interval [0, 1), meaning it's 0 (inclusive) up to, but not including, 1 (exclusive). +//→ MDN: Math.random() + +//(maximum - minimum + 1) defines the size of the range, including the maximum. + +//Multiplying the two scales the random number to a desired range. + +//Math.floor(...) rounds down to ensure a whole number. +//→ MDN: Math.floor() + +//+ minimum shifts the range so it starts at the minimum value. + +// Result: num is a random integer from minimum to maximum, inclusive. + +//Example: If minimum = 1 and maximum = 100, num will be a random whole number between 1 and 100. +//I added console.log(num) and ran the program multiple times. I observed that num always gives a different whole number between 1 and 100. This helped me understand that the expression creates a random integer by multiplying a random decimal by the range size, rounding down, and then shifting it by the minimum value. \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..0ec76b334 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/2-mandatory-errors/0.js @@ -1,2 +1,3 @@ -This is just an instruction for the first activity - but it is just for human consumption -We don't want the computer to run these 2 lines - how can we solve this problem? \ No newline at end of file +//This is just an instruction for the first activity - but it is just for human consumption +//We don't want the computer to run these 2 lines - how can we solve this problem? +//To make sure the computer doesn't run them, I turned them into comments using // so they’re ignored by the JavaScript engine. \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..4974e576b 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,6 @@ // trying to create an age variable and then reassign the value by 1 - -const age = 33; +let age = 33; age = age + 1; +//Or we can use like this +age += 1; +console.log(age); diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831..ecd972032 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,26 @@ -// Currently trying to print the string "I was born in Bolton" but it isn't working... -// what's the error ? +/* + QUESTION: + The following code fails to print "I was born in Bolton". What's the error? -console.log(`I was born in ${cityOfBirth}`); + console.log(`I was born in ${cityOfBirth}`); + const cityOfBirth = "Bolton"; + + ANSWER: + The error occurs because: + 1. We're trying to use 'cityOfBirth' before it's declared + 2. const/let variables can't be accessed before declaration (Temporal Dead Zone) + + SOLUTION: + const cityOfBirth = "Bolton"; // Declare first + console.log(`I was born in ${cityOfBirth}`); // Now works + + EXPLANATION: + - Order matters in JavaScript for const/let variables + - The fixed version follows proper variable declaration order + - This avoids the Temporal Dead Zone reference error + - Output will now correctly show: "I was born in Bolton" +*/ + +// Corrected implementation: const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..08a11a622 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -3,7 +3,21 @@ const last4Digits = cardNumber.slice(-4); // The last4Digits variable should store the last 4 digits of cardNumber // However, the code isn't working + // Before running the code, make and explain a prediction about why the code won't work +// 1. Why does it give this error? +// The error occurs because cardNumber is a number, and numbers don't have the .slice() method. The .slice() method works on strings or arrays. + // Then run the code and see what error it gives. // Consider: Why does it give this error? Is this what I predicted? If not, what's different? +// 2. Is this what I predicted? +// Not exactly. I initially thought the problem was with the argument -4 inside .slice(), maybe it should have been just 4. I did not predict that the issue was with using .slice() on a number instead of a string. + +// 3. What's different? +// The actual issue is that .slice() is not a method for numbers at all, so we must convert the number to a string before slicing. + // Then try updating the expression last4Digits is assigned to, in order to get the correct value +// 4. How did I update the expression to get the correct value? +// I fixed it by converting the number to a string using .toString(), then applying .slice(-4) on the string: +const correctedLast4Digits = cardNumber.toString().slice(-4); +console.log(`The last 4 digits of the card number are ${correctedLast4Digits}`); \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..e1a3e6952 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,22 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +// Problem Case (invalid syntax): +// const 12HourClockTime = "20:53"; // ❌ SyntaxError: Invalid variable name +// const 24hourClockTime = "08:53"; // ❌ Also invalid (starts with number) + +// Solution: +const twelveHourClockTime = "08:53"; // ✅ Valid (starts with letter) +const twentyFourHourClockTime = "20:53"; // ✅ Valid + +/* Explanation: +1. JavaScript variable naming rules: + - Cannot start with a digit (0-9) + - Must start with letter, underscore (_), or dollar sign ($) + +2. Fix approach: + - Changed numeric prefixes to words ("twelve" instead of 12) + - Maintained clear, descriptive names + - Kept the same time values as strings + +3. Why strings are appropriate: + - Time formats with colons are best represented as strings + - No arithmetic operations needed on these values +*/ \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..ad3917477 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -2,7 +2,8 @@ let carPrice = "10,000"; let priceAfterOneYear = "8,543"; carPrice = Number(carPrice.replaceAll(",", "")); -priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); // This line has the error +priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); // This line was added in your example const priceDifference = carPrice - priceAfterOneYear; const percentageChange = (priceDifference / carPrice) * 100; @@ -11,12 +12,52 @@ console.log(`The percentage change is ${percentageChange}`); // Read the code and then answer the questions below -// a) How many function calls are there in this file? Write down all the lines where a function call is made - -// b) Run the code and identify the line where the error is coming from - why is this error occurring? How can you fix this problem? - -// c) Identify all the lines that are variable reassignment statements - -// d) Identify all the lines that are variable declarations - -// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +/* +a) How many function calls are there in this file? Write down all the lines where a function call is made +*/ +// There are 5 function calls in this file. They are: +// Line 4: +// carPrice.replaceAll(",", "") → Calls the replaceAll() method on the carPrice string. +// Number(...) → Converts the result to a number using the Number() function. +// Line 6: +// priceAfterOneYear.replaceAll(",", "") → Calls the replaceAll() method on priceAfterOneYear. +// Number(...) → Converts the result to a number using the Number() function. +// Line 11: +// console.log(...) → Calls the log() function to print to the console. + +/* +b) Run the code and identify the line where the error is coming from - why is this error occurring? How can you fix this problem? +*/ +// The error occurs on Line 5: +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +// because the replaceAll() method is missing a comma between its two arguments. It should be: +// priceAfterOneYear.replaceAll(",", "") +// The fix is to add the comma between the arguments to make it syntactically correct. + +/* +c) Identify all the lines that are variable reassignment statements +*/ +// The variables carPrice and priceAfterOneYear are reassigned on lines 4, 5, and 6: +// carPrice = Number(carPrice.replaceAll(",", "")); // Line 4 +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); // Line 5 (assuming fixed) +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); // Line 6 +// These lines update the existing variables by converting their string values (with commas) into numbers without commas. + +/* +d) Identify all the lines that are variable declarations +*/ +// The variable declarations happen on the following lines: +// Line 1: let carPrice = "10,000"; +// Line 2: let priceAfterOneYear = "8,543"; +// Line 8: const priceDifference = carPrice - priceAfterOneYear; +// Line 9: const percentageChange = (priceDifference / carPrice) * 100; +// So, there are 4 variable declarations in total. + +/* +e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +*/ +// The expression Number(carPrice.replaceAll(",", "")) performs two tasks: +// 1. carPrice.replaceAll(",", ""): This removes all commas from the carPrice string. +// For example, if carPrice = "10,000", this part of the expression turns it into "10000". +// 2. Number(...): This then converts the cleaned string "10000" into a number: 10000. +// This expression is used to convert a string that looks like a number with commas (like "10,000") into an actual number (10000) so that it can be used in mathematical calculations. \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..b42ed1ec2 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -11,15 +11,54 @@ console.log(result); // For the piece of code above, read the code and then answer the following questions -// a) How many variable declarations are there in this program? +/* +a) How many variable declarations are there in this program? +*/ +// There are 6 variable declarations in the program. Each is declared using the const keyword: +// 1. const movieLength = 8784; +// 2. const remainingSeconds = movieLength % 60; +// 3. const totalMinutes = (movieLength - remainingSeconds) / 60; +// 4. const remainingMinutes = totalMinutes % 60; +// 5. const totalHours = (totalMinutes - remainingMinutes) / 60; +// 6. const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; -// b) How many function calls are there? +/* +b) How many function calls are there? +*/ +// There is 1 function call in this program: +// console.log(result); → This is a call to the console.log() function, which outputs the value of result to the console. -// c) Using documentation, explain what the expression movieLength % 60 represents -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators +/* +c) Using documentation, explain what the expression movieLength % 60 represents +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators +*/ +// The expression movieLength % 60 uses the modulus operator %, which returns the remainder after dividing one number by another. +// It calculates how many seconds are left over after converting the total movieLength (in seconds) into whole minutes. +// So, if movieLength is 8784 seconds, 8784 % 60 gives 24, meaning 24 seconds remain after making as many full minutes as possible. +// Reference: MDN Docs - Modulus operator -// d) Interpret line 4, what does the expression assigned to totalMinutes mean? +/* +d) Interpret line 4, what does the expression assigned to totalMinutes mean? +*/ +// Line 4 calculates the total number of full minutes in the movie length by subtracting the remaining seconds from the total seconds and then dividing by 60. +// const totalMinutes = (movieLength - remainingSeconds) / 60; +// This ensures that only complete minutes are counted, ignoring the leftover seconds. +// For example, if movieLength is 8784 seconds and remainingSeconds is 24, then: +// totalMinutes = (8784 - 24) / 60 = 8760 / 60 = 146 minutes. -// e) What do you think the variable result represents? Can you think of a better name for this variable? +/* +e) What do you think the variable result represents? Can you think of a better name for this variable? +*/ +// The variable result represents the movie length formatted as a string in hh:mm:ss (hours, minutes, seconds) format. +// A better name for this variable could be: +// formattedMovieDuration (or formattedMovieTime). +// This would make the purpose of the variable more clear when reading the code. -// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer +/* +f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer +*/ +// Yes, the code works for various non-negative integer values of movieLength. For example: +// When movieLength = 59, the result is 0:0:59, which is correct. +// When movieLength = 732, the result is 0:12:12, which is also accurate. +// The code handles the conversion from seconds to hours, minutes, and seconds properly for different input values. +// (Note: The code assumes movieLength is a non-negative integer. It would produce decimal results or unexpected formats for negative or non-integer inputs, but for typical movie lengths, it works.) \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..2d1fe42ee 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -12,8 +12,7 @@ const pounds = paddedPenceNumberString.substring( ); const pence = paddedPenceNumberString - .substring(paddedPenceNumberString.length - 2) - .padEnd(2, "0"); + .substring(paddedPenceNumberString.length - 2); console.log(`£${pounds}.${pence}`); @@ -25,3 +24,21 @@ console.log(`£${pounds}.${pence}`); // To begin, we can start with // 1. const penceString = "399p": initialises a string variable with the value "399p" +// This value represents a monetary amount in pence, with a trailing "p" to indicate "pence" (e.g., 399 pence). +// 2. const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1); +// This line removes the last character ("p") from the penceString. +// It uses .substring() to extract all characters from index 0 up to (but not including) the final character. +// Purpose: To isolate the numeric portion of the string so that calculations can be performed. +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +// This line ensures the string has at least 3 characters by adding "0" to the start if it's too short. +// Rationale: This guarantees that the number has enough digits to split correctly into pounds and pence, even if the original number is small (e.g., "5p" becomes "005"). +// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); +// This line extracts the pounds part by slicing the string from the beginning up to the last 2 characters. +// Rationale: In UK currency, the last two digits represent pence, and the digits before that represent pounds. +// 5. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2); +// This line extracts the last 2 characters as the pence part. +// If for any reason it's shorter than 2 digits, it adds a "0" to the end to ensure the format is correct. +// Purpose: Guarantees a consistent two-digit pence value. +// 6. console.log(`£${pounds}.${pence}`); +// This line constructs and prints the final price string in pounds and pence format, using template literals. +// Rationale: This is the output the user will see, displaying the price in standard British currency format (e.g., £3.99). \ No newline at end of file diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feaf..d06e946fd 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -7,12 +7,27 @@ Just like the Node REPL, you can input JavaScript code into the Console tab and Let's try an example. -In the Chrome console, -invoke the function `alert` with an input string of `"Hello world!"`; +I// invoke the function alert with an input string of "Hello world!"; -What effect does calling the `alert` function have? +// What effect does calling the alert function have? +// When the alert("Hello world!") function is called in the Chrome console, +// a popup dialog box appears in the browser window with the message: +// Hello world! +// The user must click “OK” to close the alert and continue using the page. +// It pauses interaction with the page until it is dismissed. -Now try invoking the function `prompt` with a string input of `"What is your name?"` - store the return value of your call to `prompt` in an variable called `myName`. -What effect does calling the `prompt` function have? -What is the return value of `prompt`? +// Now try invoking the function prompt with a string input of "What is your name?" - store the return value of your call to prompt in an variable called myName. +// let myName = prompt("What is your name?"); + +// What effect does calling the prompt function have? +// A dialog box appears asking the user to enter some text. +// The user sees the message: +// What is your name? +// and there is a text input field and buttons OK and Cancel. + +// What is the return value of prompt? +// The function returns a string containing whatever the user typed. +// For example, if the user typed Sisay and presses OK: +// myName // is now equal to "Sisay" +// (Also, if the user clicks "Cancel" or presses Escape, the function returns null.) \ No newline at end of file diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..3502a043f 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -1,16 +1,40 @@ ## Objects In this activity, we'll explore some additional concepts that you'll encounter in more depth later on in the course. +// Open the Chrome devtools Console, type in `console.log` and then hit enter -Open the Chrome devtools Console, type in `console.log` and then hit enter +// What output do you get? +// ƒ log() { [native code] } +// Explanation: +// This output tells us that console.log is a function (specifically a native function provided by the JavaScript engine). +// It is used to display messages in the browser console. -What output do you get? -Now enter just `console` in the Console, what output do you get back? +// Now enter just `console` in the Console, what output do you get back? +// console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …} +// Explanation: +// Typing console by itself shows that it's an object. +// This object contains several built-in functions (also called methods) like: +// log() – logs a message +// error() – logs an error +// warn() – logs a warning +// debug(), info(), etc. -Try also entering `typeof console` -Answer the following questions: +// Try also entering `typeof console` +// "object" +// Explanation: +// The typeof operator confirms that console is of type object, meaning it can store properties and functions. -What does `console` store? -What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + +// Answer the following questions: + +// What does `console` store? +// The `console` stores a collection of built-in functions (also known as methods) that are primarily used for debugging and displaying output in the browser's developer console. These methods include `log`, `error`, `warn`, `info`, `debug`, and others. + +// What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? +// The dot (.) in syntax like `console.log` or `console.assert` is called "dot notation". +// It is used to access a property or a method (which is a function stored as a property) of an object. +// So, `console.log` means: +// → "Access the `log` method (function) that belongs to the `console` object." +// Similarly, `console.assert` means "Access the `assert` method that belongs to the `console` object." \ No newline at end of file