diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..a734038ac 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -4,3 +4,8 @@ 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 incrementing the count variable by 1, effectively adding 1 to its current value +// The = operator is used to assign the new value (count + 1) back to the count variable +// The code is valid and will not throw an error +// because count is declared with let, allowing it to be reassigned. +console.log(count); // Output: 1 diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..15a000f58 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -8,4 +8,10 @@ let lastName = "Johnson"; let initials = ``; // https://www.google.com/search?q=get+first+character+of+string+mdn +initials += firstName[0]; +initials += middleName[0]; +initials += lastName[0]; +console.log(initials); // Output: "CKJ" + + diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..c2b347ea2 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -9,15 +9,28 @@ // (All spaces in the "" line should be ignored. They are purely for formatting.) +// const filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt"; +// const lastSlashIndex = filePath.lastIndexOf("/"); +// const base = filePath.slice(lastSlashIndex + 1); +// 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 filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt"; + +// Get base (file name) const lastSlashIndex = filePath.lastIndexOf("/"); const base = filePath.slice(lastSlashIndex + 1); -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 +// Get dir (directory path) +const dir = filePath.slice(0, lastSlashIndex); -const dir = ; -const ext = ; +// Get ext (file extension) +const lastDotIndex = base.lastIndexOf("."); +const ext = base.slice(lastDotIndex); + +console.log(`The base part of ${filePath} is ${base}`); +console.log(`The dir part of ${filePath} is ${dir}`); +console.log(`The ext part of ${filePath} is ${ext}`); // 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..2974a3315 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -7,3 +7,12 @@ const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; // 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 +console.log(`The random number is: ${num}`); +// The expression Math.random() generates a random floating-point number between 0 (inclusive) and 1 (exclusive). +// Multiplying this by (maximum - minimum + 1) scales the range to the desired range of numbers. +// Adding minimum shifts the range to start from the minimum value. +// Finally, Math.floor() rounds down the result to the nearest whole number, ensuring that num is an integer within the specified range. +// The final result is a random integer between minimum and maximum, inclusive. +// In this case, num will be a random integer between 1 and 100, inclusive. +// The program will output a different random number each time it is run, within the specified range + diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..4a9a46fd7 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? +// You can use a comment to prevent the computer from running these lines \ 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..ea5b39b1f 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,15 @@ // trying to create an age variable and then reassign the value by 1 -const age = 33; -age = age + 1; +// const age = 33; +// age = age + 1; +// The error occurs because the variable 'age' is declared as a constant using 'const'. +// Constants cannot be reassigned a new value after they are declared. +// To fix this error, you can change the declaration of 'age' to 'let' or 'var' if you want to reassign it later. +// For example: let + age = 33; + age = age + 1; +// Now, 'age' can be reassigned without any error. +// Alternatively, if you want to keep 'age' as a constant, you should not attempt to reassign it. +// In that case, you can simply remove the reassignment line: +console.log(age); // Output: 34 +// This will output the value of 'age' after the reassignment, which is now 34. diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831..19f37bdfa 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,12 @@ // Currently trying to print the string "I was born in Bolton" but it isn't working... // what's the error ? -console.log(`I was born in ${cityOfBirth}`); +// console.log(`I was born in ${cityOfBirth}`); +// const cityOfBirth = "Bolton"; + +// The error occurs because the variable 'cityOfBirth' is used before it is declared. +// In JavaScript, variables declared with 'const' or 'let' are not hoisted to the top of their scope. +// To fix this error, you should declare the variable 'cityOfBirth' before using it in the console.log statement. const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); +// This will correctly output "I was born in Bolton" without any errors. diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..27b374879 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -1,5 +1,5 @@ -const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +// const cardNumber = 4533787178994213; +// const last4Digits = cardNumber.slice(-4); // The last4Digits variable should store the last 4 digits of cardNumber // However, the code isn't working @@ -7,3 +7,15 @@ const last4Digits = cardNumber.slice(-4); // 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? // Then try updating the expression last4Digits is assigned to, in order to get the correct value + +// console.log(`The last 4 digits of the card number are: ${last4Digits}`); + +// The error occurs because the `slice` method is being called on a number, which is not a valid operation. +// The `slice` method is a string method, and it cannot be directly applied to a number. +// To fix this error, we need to convert the `cardNumber` to a string before using the `slice` method. +// We can do this by wrapping `cardNumber` in the `String()` function or using the `toString()` method. +// Here's the corrected code: +const cardNumber = 4533787178994213; +const last4Digits = String(cardNumber).slice(-4); +console.log(`The last 4 digits of the card number are: ${last4Digits}`); +// Now, the code will correctly output the last 4 digits of the card number, which are "4213". diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..bfc1469a6 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,13 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +// const 12HourClockTime = "20:53"; +// const 24hourClockTime = "08:53"; + +// The error occurs because the variable name '12HourClockTime' starts with a digit, which is not allowed in JavaScript. +// Variable names must begin with a letter, underscore (_), or dollar sign ($). +// To fix this error, we can rename the variable to start with a letter or an underscore. +// For example, we can rename it to 'hour12ClockTime' or '_12HourClockTime'. +const hour12ClockTime = "20:53"; +const hour24ClockTime = "08:53"; + +console.log(`The 12-hour clock time is: ${hour12ClockTime}`); +console.log(`The 24-hour clock time is: ${hour24ClockTime}`); +// This will correctly output the 12-hour and 24-hour clock times without any errors. diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..82b54a8dc 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -1,22 +1,60 @@ -let carPrice = "10,000"; -let priceAfterOneYear = "8,543"; +// let carPrice = "10,000"; +// let priceAfterOneYear = "8,543"; -carPrice = Number(carPrice.replaceAll(",", "")); -priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +// carPrice = Number(carPrice.replaceAll(",", "")); +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); -const priceDifference = carPrice - priceAfterOneYear; -const percentageChange = (priceDifference / carPrice) * 100; +// const priceDifference = carPrice - priceAfterOneYear; +// const percentageChange = (priceDifference / carPrice) * 100; -console.log(`The percentage change is ${percentageChange}`); +// 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 +//There are 5 function calls in total. +// 1. `carPrice.replaceAll(",", "")` on line 4. +// 2. numbeer(carPrice.replaceAll(",", ""))` on line 4. +// 3. `priceAfterOneYear.replaceAll("," "")` on line 5. +// 4. `Number(priceAfterOneYear.replaceAll("," ""))` on line 5. +// 5. `console.log(...)` on line 10. // 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 7: `priceAfterOneYear.replaceAll("," "")` +// The error is due to a syntax mistake in the `replaceAll` method call. There is a missing comma between the two arguments. +// To fix this, we need to add the missing comma, it should be `priceAfterOneYear.replaceAll(",", "")`. // c) Identify all the lines that are variable reassignment statements +// The variable reassignment statements are: +// 1. `carPrice = Number(carPrice.replaceAll(",", ""));` on line 4 +// 2. `priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," ""));` on line 5 // d) Identify all the lines that are variable declarations +// The variable declarations are: +// 1. `let carPrice = "10,000";` on line 1 +// 2. `let priceAfterOneYear = "8,543";` on line 2 +// 3. `const priceDifference = carPrice - priceAfterOneYear;` on line 7 +// 4. `const percentageChange = (priceDifference / carPrice) * 100;` on line 8 +// 5. `console.log(...)` on line 10 (though this is a function call, it also serves as a declaration in this context) // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +// The expression `Number(carPrice.replaceAll(",", ""))` is converting the string representation of the car price (which includes commas) into a number. +// It first removes all commas from the string using `replaceAll(",", "")`, and then converts the resulting string into a number using the `Number` function. +// This is necessary to perform arithmetic operations on the car price, as arithmetic operations cannot be performed directly on strings. + +//correct the code +let carPrice = "10,000"; +let priceAfterOneYear = "8,543"; + +// Remove commas and convert to numbers +carPrice = Number(carPrice.replaceAll(",", "")); +priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); + +// Calculate difference and percentage change +const priceDifference = carPrice - priceAfterOneYear; +const percentageChange = (priceDifference / carPrice) * 100; + +// Output the result +console.log(`The percentage change is ${percentageChange.toFixed(2)}%`); + +// The corrected line should be: \ 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..8ecd041cf 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -12,14 +12,25 @@ 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? +// There are 5 variable declarations in this program: +// 1. `movieLength` on line 1 +// 2. `remainingSeconds` on line 3 +// 3. `totalMinutes` on line 4 +// 4. `remainingMinutes` on line 6 +// 5. `totalHours` on line 7 // b) How many function calls are there? +// There are no function calls in this program. All operations are performed using arithmetic operators and string interpolation. // 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` calculates the remainder when `movieLength` (in seconds) is divided by 60. This gives the number of seconds that do not fit into complete minutes, effectively providing the remaining seconds after converting to minutes. // d) Interpret line 4, what does the expression assigned to totalMinutes mean? +// The expression `(movieLength - remainingSeconds) / 60` calculates the total number of minutes in the movie. It first subtracts the remaining seconds from the total movie length (to account for any leftover seconds), and then divides the result by 60 to convert seconds into minutes. // e) What do you think the variable result represents? Can you think of a better name for this variable? +// The variable `result` represents the formatted time of the movie in the format "hours:minutes:seconds". A better name for this variable could be `formattedMovieTime` or `movieDuration` to make it clearer that it holds the duration of the movie in a human-readable format. // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer +// Yes, this code will work for all non-negative integer values of `movieLength`. It will correctly convert any length of the movie given in seconds into the format "hours:minutes:seconds". However, if `movieLength` is negative, the output will not be meaningful, as negative time does not have a valid representation in this context. Therefore, it is advisable to ensure that `movieLength` is a non-negative integer before running the code. diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..47d6b0c07 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -1,20 +1,13 @@ -const penceString = "399p"; +const penceString = "399"; -const penceStringWithoutTrailingP = penceString.substring( - 0, - penceString.length - 1 -); +const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1); const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); -const pounds = paddedPenceNumberString.substring( - 0, - paddedPenceNumberString.length - 2 -); +const pounds = paddedPenceNumberString.substring( 0, paddedPenceNumberString.length - 2); const pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) .padEnd(2, "0"); - console.log(`£${pounds}.${pence}`); // This program takes a string representing a price in pence @@ -22,6 +15,12 @@ console.log(`£${pounds}.${pence}`); // You need to do a step-by-step breakdown of each line in this program // Try and describe the purpose / rationale behind each step +// The purpose of this program is to convert a string representing a price in pence (e.g., "399p") into a formatted string representing the price in pounds (e.g., "£3.99"). +// The program achieves this by manipulating the string to extract the numeric value and format it correctly. // To begin, we can start with // 1. const penceString = "399p": initialises a string variable with the value "399p" +// 2. const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1): removes the trailing 'p' from the string, resulting in "399". +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"): pads the string with leading zeros to ensure it has at least 3 characters, resulting in "399" (no change needed here since it already has 3 characters). +// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2): extracts the pounds part of the string by taking all characters except the last two, resulting in "3". +// 5. const pence = paddedPenceNumberString.substring(paddedPenceNumber