diff --git a/Sprint-2/1-key-exercises/1-count.js b/Sprint-2/1-key-exercises/1-count.js index 117bcb2b6..68b926dc8 100644 --- a/Sprint-2/1-key-exercises/1-count.js +++ b/Sprint-2/1-key-exercises/1-count.js @@ -4,3 +4,9 @@ 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 +console.log(count); + +//Line 3 reads the current value of , which is <0>, and computes , which turns out to be 1. +//It also assigns the new value <1> to the variable , overwriting the initial value <0>. +//The assignment operator "=" means, take the value on the right, and store it in the variable on the left. +//Console.log(count) prints out the result of Line 3. \ No newline at end of file diff --git a/Sprint-2/1-key-exercises/2-initials.js b/Sprint-2/1-key-exercises/2-initials.js index 964c9563c..e9cf2a40e 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 = ``; +//Solution +const initials = `${firstName[0]} ${middleName[0]} ${lastName[0]} `; -// https://www.google.com/search?q=get+first+character+of+string+mdn +console.log(initials); diff --git a/Sprint-2/1-key-exercises/3-paths.js b/Sprint-2/1-key-exercises/3-paths.js index ab90ebb28..79b5b26de 100644 --- a/Sprint-2/1-key-exercises/3-paths.js +++ b/Sprint-2/1-key-exercises/3-paths.js @@ -17,7 +17,12 @@ 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 = ; +//Solution +const dir = filePath.slice(0, lastSlashIndex); +console.log(`The dir part of ${filePath} is ${dir}`); + +const lastDotIndex = base.lastIndexOf("."); +const ext = base.slice(lastDotIndex); +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-2/1-key-exercises/4-random.js b/Sprint-2/1-key-exercises/4-random.js index 292f83aab..b524e6443 100644 --- a/Sprint-2/1-key-exercises/4-random.js +++ b/Sprint-2/1-key-exercises/4-random.js @@ -2,8 +2,24 @@ 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? -// 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 + +//Solution +//- "num" represents a random whole number between 1 and 100. + +//Break down of expression +//-Math.random: This generates a random decimal number between 0 and 1. It can return 0, but never reaches 1. (Example: 0.876). + +//-(maximum - minimum + 1): +// This expression can be simplified as (100 - 1 + 1), which equals 100. This tells the program how many possible whole numbers there are. There are 100 possibilities. +// The +1 is important as without it, we would only reach 99 possibilities, that is 0 - 99. + +//-Math.random() * (maximum - minimum + 1): +// This function multiplies the random decimal by the range size. Since Math.random() represents numbers >=0 and <1, this expression produces value anywhere from 0 up to 100, excluding 100. +// Example to justify expression: 0.876 * 100 = 87.6 + +//-Math.floor: This static method rounds down to the nearest whole number, discarding the decimal. This turns the continuous range into whole numbers, from 0 - 99. +// That is 87.6 becomes 87. + +// + minimum: This shifts the whole range up by adding 1. So instead of landing on 0 - 99, we have 1 - 100. \ 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..78f92a707 100644 --- a/Sprint-2/2-mandatory-errors/0.js +++ b/Sprint-2/2-mandatory-errors/0.js @@ -1,2 +1,5 @@ -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?*/ + +//Solution +//This problem was solved by wrapping the statement in a multi-line comment tag. This way the lines are stopped from executing. \ 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..6ef2ea979 100644 --- a/Sprint-2/2-mandatory-errors/1.js +++ b/Sprint-2/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; + +console.log(age); diff --git a/Sprint-2/2-mandatory-errors/2.js b/Sprint-2/2-mandatory-errors/2.js index e09b89831..047143147 100644 --- a/Sprint-2/2-mandatory-errors/2.js +++ b/Sprint-2/2-mandatory-errors/2.js @@ -1,5 +1,9 @@ // 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}`); const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); + + +//ReferenceError: Cannot access 'cityOfBirth' before initialization. +//console.log tries to use cityOfBirth inside the template literal, but cityOfBirth has not been declared yet at that point in the code. diff --git a/Sprint-2/2-mandatory-errors/3.js b/Sprint-2/2-mandatory-errors/3.js index ec101884d..c7523234d 100644 --- a/Sprint-2/2-mandatory-errors/3.js +++ b/Sprint-2/2-mandatory-errors/3.js @@ -1,5 +1,5 @@ const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +const last4Digits = String(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 + + +//Solution +//Prediction - The code would not run because 'cardNumber' is declared as numbers instead of a string. +// The '.slice()' method belongs to strings and arrays, it could only work by treating it's subject as a sequence of characters. + +console.log(last4Digits); + +//Error message - TypeError: cardNumber.slice is not a function +//Reason for error +//The error thrown was considerably as predicted. +//'.slice()' is a method defined on 'String.prototype', and since 'cardNumber' was declared with a numeric literal, JavaScript treats it as the 'number' type. \ No newline at end of file diff --git a/Sprint-2/2-mandatory-errors/4.js b/Sprint-2/2-mandatory-errors/4.js index 5f86c730b..7d7f9e10b 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"; +const ClockTime12Hour = "8:53pm"; +const ClockTime24hour = "20:53"; + +console.log(ClockTime12Hour, ClockTime24hour); + +//There is a SyntaxError after running the code. +//This error occurred because the identifiers '12HourClockTime' and '24hourClockTime' both start with a digit. \ 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..2bfa87260 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; @@ -20,3 +20,33 @@ console.log(`The percentage change is ${percentageChange}`); // 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? + + +//Solution +// a) There are 5 function calls on lines 4, 5, and 9. +// Line 4: carPrice.replaceAll(",","") +// Line 4: Number() +// Line 5: priceAfterOneYear.replaceAll("," "") +// Line 5: Number() +// Line 9: console.log() + +// b) Line 5 seems to broken. +// Error message - SyntaxError: missing ) after argument list +// Reason for error: There is a missing comma between two arguments of replaceAll. +// To fix the error, we need to add the missing comma between the arguments of replaceAll. + +// c) Lines 4 and 5 contain variable reassignment statements +// Line 4: carPrice = Number() +// Line 5: priceAfterOneYear = Number() + +// d) Lines 1, 2, 7, and 8 contain variable declarations +// Line 1: let carPrice = "10,000"; +// Line 2: let priceAfterOneYear = "8,543"; +// Line 7: const priceDifference = carPrice - priceAfterOneYear; +// Line 8: const percentageChange = (priceDifference / carPrice) * 100; + +// e) Number(carPrice.replaceAll(",","")) is two steps combined, whereby: +// carPrice.replaceAll(",","") takes the string "10,000" and deletes every comma, making it 10000 +// and Number() converts the new string into an actual numeric value +// The purpose of the expression is to strip out the formatting comma first from the string +// so that JavaScript does not treat it as plain text, and then converts the result into real numbers for it to be used in math, similar to Line 7 \ No newline at end of file diff --git a/Sprint-2/3-mandatory-interpret/2-time-format.js b/Sprint-2/3-mandatory-interpret/2-time-format.js index 47d239558..685f7b52b 100644 --- a/Sprint-2/3-mandatory-interpret/2-time-format.js +++ b/Sprint-2/3-mandatory-interpret/2-time-format.js @@ -1,4 +1,5 @@ -const movieLength = 8784; // length of movie in seconds +//const movieLength = 8784; // length of movie in seconds +function convert(movieLength){ const remainingSeconds = movieLength % 60; const totalMinutes = (movieLength - remainingSeconds) / 60; @@ -6,8 +7,14 @@ const totalMinutes = (movieLength - remainingSeconds) / 60; const remainingMinutes = totalMinutes % 60; const totalHours = (totalMinutes - remainingMinutes) / 60; -const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; -console.log(result); +return `${totalHours}:${remainingMinutes}:${remainingSeconds}`; +//const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; +//console.log(result); +} + +[65, -100, 90.5, "8784"].forEach(v => { + console.log(v, "->", convert(v)); +}); // For the piece of code above, read the code and then answer the following questions @@ -23,3 +30,35 @@ console.log(result); // e) What do you think the variable result represents? Can you think of a better name for this variable? // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer + + + +//Solution +// a) There are 6 declared variables in this program, all declared with 'const' +// - const movieLength +// - const remainingSeconds +// - const totalMinutes +// - const remainingMinutes +// - const totalHours +// - const result + +// b) There is just 1 function call: console.log(result); + +// c) In the expression 'movieLength % 60', '%' represents the remainder operator. It returns the value that of what is left over after dividing the left operand by the right operand as many whole times as possible. +// Since movieLength = 8784, it means: 8784 % 60, which returns a result of 146 remainder 24. +// Therefore, movieLength % 60 (8784 % 60) returns the leftover value '24'. In this context, the leftover represents the loose seconds that add up to a full minute. + +// d) The expression assigned to totalMinutes simply means, we subtract the loose seconds, '24', from movieLength, '8784'. The result becomes a number easily divisible by 60 +// That is: totalMinutes = (8784 - 24); +// which gives 8760, and then divides it 60; +// the result, 146, is the total number of complete minutes contained in the movie + +// e) The variable 'result' is a template literal syntax which holds the movie's length formatted as a colon-separated time string: as in '2:26:24'. +// A better name for 'result' could have been 'movieLengthDisplay' + +// f) This program did not work for all values of movieLength +// Some problems discovered +// - for movieLength 65 there was an issue with zero-padding, '65' becomes '0:1:5' instead of the conventional '00:01:05'. Returning single-digit minutes/seconds look wrong in a real time display +// - negative integer, '-100', produced '0:-1:-40', which is inaccurate for a duration +// - non-integer input, 90.5, was not handled as it gives '0:1:30.5'. This implies that a fractional second had slipped through untouched, since nothing was truncated. +// - string input "8784" works here because operators '%', '-', and '/' automatically converts strings to numbers, but that is fragile and relies on the type conversion rather than actual input validation \ No newline at end of file diff --git a/Sprint-2/3-mandatory-interpret/3-to-pounds.js b/Sprint-2/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..13105bec1 100644 --- a/Sprint-2/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-2/3-mandatory-interpret/3-to-pounds.js @@ -25,3 +25,30 @@ console.log(`£${pounds}.${pence}`); // 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); +// substring(0, length - 1): is a method that is invoked in the paragraph above to take every character in the string provided except the last one, leaving out the 'p' +// That is -> '399p' becomes '399' +// const penceStringWithoutTrailingP: used to store the value from 'penceString.substring(...)' + +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +// penceStringWithoutTrailingP is now '399' +// padStart(3, "0") is a method used above which guarantees that the numeric string is at least 3 characters long, and if it is shorter add '0' to the front until it is 3 characters long. +// padding to 3 ensures there is always at least 3 digits, that is, one pounds digit and two pence digits. +// + +// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); +// since paddedPenceNumberString is '399' and it's '.length' is 3 +// this line is saying: '399.substring(0, 3 - 2)', which becomes '399.substring(0, 1)' +// 'substring' is a method used to grab characters from this string, starting from the left, from position '0' up to, but not including, position '1' +// 'const pounds' would be assigned the new value: '3' + +// 5. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0"); +// since paddedPenceNumberString.length is '3' +// then 'paddedPenceNumberString.substring(3 - 2)' becomes 'paddedPenceNumberString.substring(1)': this means grab everything from position '1' of the string to the end. +// That is -> '399.substring(1)' becomes '99' +// '.padEnd(2, "0") is another method that ensures the string is at least 2 characters long and adding '0' to the end if it's too short. +// 'const pence' would be assigned the new value: '99' + +// 6. console.log(`£${pounds}.${pence}`): This template string calls the result of two pieces, 'pounds' which is '3' and 'pence' which '99' +// Overall result: £3.99 \ No newline at end of file