diff --git a/Sprint-2/1-key-exercises/1-count.js b/Sprint-2/1-key-exercises/1-count.js index 117bcb2b6..06a6d79ac 100644 --- a/Sprint-2/1-key-exercises/1-count.js +++ b/Sprint-2/1-key-exercises/1-count.js @@ -2,5 +2,15 @@ let count = 0; count = count + 1; + +//const count = 0; +// count = count + 1; +// console.log(count) + // 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 + +//ANSWER: + +// Line 3 is reassigning the value of count. This is because we are using "let" and not "const" which allows us to reassign values. The value of count is being evaluated first (count + 1), which sums up to (0 + 1 = 1) and then it is updated using the assignment operator (=), which takes the result and stores it back into the count variable. + diff --git a/Sprint-2/1-key-exercises/2-initials.js b/Sprint-2/1-key-exercises/2-initials.js index 964c9563c..94b16fba1 100644 --- a/Sprint-2/1-key-exercises/2-initials.js +++ b/Sprint-2/1-key-exercises/2-initials.js @@ -5,6 +5,7 @@ const lastName = "Johnson"; // Declare a variable called initials that stores the first character of each string. // This should produce the string "CKJ", but you must not write the characters C, K, or J in the code of your solution. -const initials = ``; +const initials = `${firstName.charAt(0)}${middleName.charAt(0)}${lastName.charAt(0)}`; +console.log(initials); // https://www.google.com/search?q=get+first+character+of+string+mdn diff --git a/Sprint-2/1-key-exercises/3-paths.js b/Sprint-2/1-key-exercises/3-paths.js index ab90ebb28..eaa905762 100644 --- a/Sprint-2/1-key-exercises/3-paths.js +++ b/Sprint-2/1-key-exercises/3-paths.js @@ -15,9 +15,13 @@ 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 +const dir = filePath.slice(0, lastSlashIndex); + // Create a variable to store the ext part of the variable +const lastDotIndex = filePath.lastIndexOf("."); +const ext = filePath.slice(lastDotIndex); -const dir = ; -const ext = ; +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 +// https://www.google.com/search?q=slice+mdn diff --git a/Sprint-2/1-key-exercises/4-random.js b/Sprint-2/1-key-exercises/4-random.js index 292f83aab..cab87b170 100644 --- a/Sprint-2/1-key-exercises/4-random.js +++ b/Sprint-2/1-key-exercises/4-random.js @@ -1,9 +1,31 @@ -const minimum = 1; -const maximum = 100; - -const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; +const minimum = 1; // Sets the lowest possible number that can be generated +const maximum = 100; // Sets the highest possible number that can be generated // 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 // It will help to think about the order in which expressions are evaluated + +const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; + +/* +EXPLANATION IN ORDER OF EXECUTION (OPERATOR PRECEDENCE): + +1. (maximum - minimum + 1) — Grouping Parentheses (Highest Precedence): + Calculates the total number of possible whole values between minimum and maximum, inclusive (e.g., 100 - 1 + 1 = 100 possible values). + +2. Math.random() — Function Call: + Generates a random floating-point decimal from 0 up to (but not including) 1. + +3. Math.random() * (maximum - minimum + 1) — Multiplication: + calculates the total number of possible values between minimum and maximum, (but not including) 100 (e.g., 0 to 99.999...). + +4. Math.floor(...) — Function Call: + Rounds the decimal down to the nearest whole integer, converting the range from [0, 99.999...] to an integer from 0 to 99. + +5. + minimum — Addition (Lowest Precedence): + Shifts the whole set of numbers up so that the lowest outcome becomes `minimum` (1) instead of 0, resulting in a whole number between 1 and 100 inclusive. +*/ + // Try logging the value of num and running the program several times to build an idea of what the program is doing + +console.log(num); // num represents a random whole number between 1 and 100 inclusive \ No newline at end of file diff --git a/Sprint-2/2-mandatory-errors/0.js b/Sprint-2/2-mandatory-errors/0.js index cf6c5039f..600e67118 100644 --- a/Sprint-2/2-mandatory-errors/0.js +++ b/Sprint-2/2-mandatory-errors/0.js @@ -1,2 +1,7 @@ -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?*/ + + +//ANSWER: + +// We comment them out \ No newline at end of file diff --git a/Sprint-2/2-mandatory-errors/1.js b/Sprint-2/2-mandatory-errors/1.js index 7a43cbea7..f59b0d742 100644 --- a/Sprint-2/2-mandatory-errors/1.js +++ b/Sprint-2/2-mandatory-errors/1.js @@ -1,4 +1,11 @@ // trying to create an age variable and then reassign the value by 1 -const age = 33; +// The problem here is that 'const' creates a constant variable which cannot be reassigned, attempting to reassign (age = age + 1) throws a TypeError: Assignment to constant variable. + + +//change 'const' to 'let' so the value can be updated +// const age = 33; +let age = 33; age = age + 1; + +// console.log(age); diff --git a/Sprint-2/2-mandatory-errors/2.js b/Sprint-2/2-mandatory-errors/2.js index e09b89831..57c4d31a2 100644 --- a/Sprint-2/2-mandatory-errors/2.js +++ b/Sprint-2/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}`); +// The error is a ReferenceError: Cannot access 'cityOfBirth' before initialization +// In JavaScript variables declared with 'const' or 'let' cannot be accessed before they are declared or initialized + + +//SOLUTION +// move the variable declaration above the 'console.log()' const cityOfBirth = "Bolton"; + +console.log(`I was born in ${cityOfBirth}`); diff --git a/Sprint-2/2-mandatory-errors/3.js b/Sprint-2/2-mandatory-errors/3.js index ec101884d..40f11866e 100644 --- a/Sprint-2/2-mandatory-errors/3.js +++ b/Sprint-2/2-mandatory-errors/3.js @@ -1,9 +1,22 @@ -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 // Before running the code, make and explain a prediction about why the code won't work + +//Prediction: The code won't work because cardNumber is stored as a Number and not a string, this is because '.slice()' is a string method +// Numbers in JavaScript don't work with '.slice()' + + // Then run the code and see what error it gives. +//This is the error it gives: TypeError: cardNumber.slice is not a function + + // Consider: Why does it give this error? Is this what I predicted? If not, what's different? + +//Explanation: Yes, my prediction was accurate. JavaScript threw a TypeError because '.slice()' is a string method // Then try updating the expression last4Digits is assigned to, in order to get the correct value +// Keep the original number value untouched +const cardNumber = 4533787178994213; +// Convert to string dynamically before slicing +const last4Digits = cardNumber.toString().slice(-4); + +console.log(last4Digits); // output 4213 diff --git a/Sprint-2/2-mandatory-errors/4.js b/Sprint-2/2-mandatory-errors/4.js index 5f86c730b..51e061b7c 100644 --- a/Sprint-2/2-mandatory-errors/4.js +++ b/Sprint-2/2-mandatory-errors/4.js @@ -1,2 +1,7 @@ -const 12HourClockTime = "8:53pm"; -const 24hourClockTime = "20:53"; +// JavaScript variable names cannot start with a number. They must start with an alphabet(A-Z), an underscore(_), or a dollar sign($). JavaScript is also case sensitive so they have to use camelCase, PascalCase, among others. + +const twelveHourClockTime = "8:53pm"; +const twentyFourHourClockTime = "20:53"; + +// console.log(HourClockTime); +// console.log(hourClockTime); \ No newline at end of file diff --git a/Sprint-2/3-mandatory-interpret/1-percentage-change.js b/Sprint-2/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..326631b02 100644 --- a/Sprint-2/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-2/3-mandatory-interpret/1-percentage-change.js @@ -2,7 +2,7 @@ let carPrice = "10,000"; let priceAfterOneYear = "8,543"; carPrice = Number(carPrice.replaceAll(",", "")); -priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); const priceDifference = carPrice - priceAfterOneYear; const percentageChange = (priceDifference / carPrice) * 100; @@ -12,11 +12,22 @@ 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 +// ANSWER: There are 5 function calls along 3 lines +// Line 4: replaceAll() and Number() +// Line 5: replaceAll() and Number() +// Line 10: console.log() // 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? +// ANSWER: The error comes from Line 5 because a comma is missing between the two string arguments in replaceAll("," ""). +// FIX: Add the missing comma to replaceAll(",", "") // c) Identify all the lines that are variable reassignment statements +// ANSWER: Lines 4 and 5 (carPrice and priceAfterOneYear) // d) Identify all the lines that are variable declarations +// ANSWER: Lines 1, 2, 7, and 8 (using let and const) // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +// ANSWER: The expression Number(carPrice.replaceAll(",","")) removes the comma from the carPrice = "10,000" and converts it to "10000". +// Then, JavaScript can now convert the string into a number so it can be calculated. + diff --git a/Sprint-2/3-mandatory-interpret/2-time-format.js b/Sprint-2/3-mandatory-interpret/2-time-format.js index 47d239558..bc9b1b21c 100644 --- a/Sprint-2/3-mandatory-interpret/2-time-format.js +++ b/Sprint-2/3-mandatory-interpret/2-time-format.js @@ -12,14 +12,27 @@ 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? +// ANSWER: There are 6 variable declarations. +// (movieLength, remainingSeconds, totalMinutes, remainingMinutes, totalHours, and result — all declared using const) // b) How many function calls are there? +// ANSWER: There is only function call +// console.log(result) // c) Using documentation, explain what the expression movieLength % 60 represents // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators +//ANSWER: The expression movieLength % 60 uses the remainder (%) operator to calculate the number of seconds remaining that can't form a full seconds (8784 % 60 = 24 seconds) + // d) Interpret line 4, what does the expression assigned to totalMinutes mean? +// ANSWER: The expression `(movieLength - remainingSeconds) / 60` calculates the exact number of full minutes. +// First, `(movieLength - remainingSeconds)` subtracts the remaining seconds from the total seconds to leave a clean multiple of 60. +// Then, dividing that result by 60 converts those remaining seconds into whole minutes (8760 / 60 = 146 minutes). // e) What do you think the variable result represents? Can you think of a better name for this variable? +// ANSWER: A better name for the variable would be 'formattedDuration' because it clearly describes that the variable stores the movie duration in a formatted hours, minutes, and seconds format. // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer + +// ANSWER: No. It breaks if movieLength is negative (giving negative time) or a string. +// Additionally, single-digit minutes or seconds (e.g., 4 minutes, 8 seconds) output as "2:4:8" instead of standard "02:04:08" formatting. diff --git a/Sprint-2/3-mandatory-interpret/3-to-pounds.js b/Sprint-2/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..bffa869f7 100644 --- a/Sprint-2/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-2/3-mandatory-interpret/3-to-pounds.js @@ -24,4 +24,9 @@ console.log(`£${pounds}.${pence}`); // Try and describe the purpose / rationale behind each step // To begin, we can start with -// 1. const penceString = "399p": initialises a string variable with the value "399p" +// 1. const penceString = "399p": Initialises a string variable with the value "399p". +// 2. const penceStringWithoutTrailingP: Uses substring() to remove the trailing "p" from "399p", leaving "399". +// 3. const paddedPenceNumberString: Uses padStart() to ensure the string is at least 3 digits long by adding leading "0"s if needed (e.g., "5" becomes "005"), ensuring there are enough digits to extract both pounds and pence. +// 4. const pounds: Uses substring() to remove/discard the final two digits (which represent the pence) and keep everything before them, extracting the whole pounds value ("3"). +// 5. const pence: Uses substring() to extract only the final two digits ("99") for the pence value, using padEnd() as a safeguard to keep it at two digits. +// 6. console.log(`£${pounds}.${pence}`): Uses template literals to format and display the final price string ("£3.99").