diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..4e4b2b7d4 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 reassigning variable count with a new value, in this case we're saying add 1 to whatever we already have in count, +and so by using the console.log before and after the reassignment the we can tell new value of count is 1 +The "one-word" description of the programming operation in line 3 is INCREMENT +*/ diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..84f39df4f 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -5,7 +5,34 @@ let 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. -let initials = ``; +// let initials = `${firstName.slice(0,1)}${middleName.slice(0,1)}${lastName.slice(0,1)}`; using slice on template literals + +//let initials = `${firstName.charAt(0)}${middleName.charAt(0)}${lastName.charAt(0)}`; using charAt on template literals + +//let initials = (firstName[0] || '') + (middleName[0] || '') + (lastName[0] || ''); using concatenation + +// let initials = `${firstName[0] || ''}${middleName[0] || ''}${lastName[0] || ''}` //template literals + +//let initials = [firstName, middleName, lastName].map(name => name.slice(0,1)).join('') + +let initials = [firstName, middleName, lastName] + .map((name) => name.charAt(0)) + .join(""); + +/* +There are more efficient ways of implementing the solution, however these concepts haven't been covered yet +In these scenarios the slice and charAt have been implemented through an array and map + +let initials = [firstName, middleName, lastName].map(name => name.slice(0,1)).join('') +let initials = [firstName, middleName, lastName].map(name => name.charAt(0)).join('') + + +Direct use of `charAt`, `slice`, or indexing is simple and readable for a fixed number of names but becomes repetitive and less scalable. +Using an array with `map` is concise, scalable, and handles missing names well, making it best for variable-length inputs. +Template literals or concatenation with `||` are concise and handle missing names, but are still repetitive for many name parts. +For flexibility, the array + map approach is generally preferred. +*/ // https://www.google.com/search?q=get+first+character+of+string+mdn +console.log(initials); // display the output of initials to verify if successfuly executed diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..3fe69a5f8 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/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); // Extract the directory part (everything before the last slash) + // Create a variable to store the ext part of the variable +const lastDotIndex = base.lastIndexOf("."); // Find the index of the last dot in the base to get the extension +const ext = lastDotIndex !== -1 ? base.slice(lastDotIndex) : ""; // Extract the extension (including the dot), or empty string if none -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-1/1-key-exercises/4-random.js b/Sprint-1/1-key-exercises/4-random.js index 292f83aab..ad512fada 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -1,3 +1,14 @@ +/** + * Generates a random integer between the specified minimum and maximum values, inclusive. + * + * The expression `Math.floor(Math.random() * (maximum - minimum + 1)) + minimum` works as follows: + * 1. `Math.random()` generates a floating-point number in the range [0, 1). + * 2. Multiplying by `(maximum - minimum + 1)` scales this to the range [0, maximum - minimum + 1). + * 3. `Math.floor()` rounds the result down to the nearest integer, giving a value in [0, maximum - minimum]. + * 4. Adding `minimum` shifts the range to [minimum, maximum]. + * + * As a result, `num` will be a random integer between `minimum` and `maximum`, inclusive. + */ const minimum = 1; const maximum = 100; @@ -7,3 +18,5 @@ 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(num); diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..95172e41e 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? +*/ diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..6c2584208 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/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; +//const age = 33; // redeclaring with a let or var solves this error +/* variables declared with `const` in JavaScript cannot be reassigned. +However, if the `const` variable is an object or array, +its contents can still be changed (the reference is immutable, not the value). +*/ +let age = 33; age = 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..ffaf92561 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}`); +/* +This happens because in JavaScript, variables declared with `let` or `const` are not accessible before their declaration +due to a behavior called the **temporal dead zone**. +If you try to use such a variable before it’s initialized, you get a `ReferenceError`. +To avoid this, always declare and assign your variables before using them. + +*/ const cityOfBirth = "Bolton"; +console.log(`I was born in ${cityOfBirth}`); diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..ad61366f6 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,19 @@ 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 + +/* This code throws an error because `cardNumber` is a **number**, and numbers do not have a `.slice()` method—`.slice()` is a method for strings and arrays. + +**How to fix:** +Convert `cardNumber` to a string before using `.slice()`: + +````javascript +const cardNumber = 4533787178994213; +const last4Digits = cardNumber.toString().slice(-4); +```` + +Now, `last4Digits` will correctly contain the last 4 digits as a string.*/ + +const cardNumber = 4533787178994213; +const last4Digits = cardNumber.toString().slice(-4); +console.log(last4Digits); diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..1e35ff91b 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,6 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +// const 12HourClockTime = "20:53"; +// const 24hourClockTime = "08:53"; + +// variables in js can't begin with numbers +const twelveHourClockTime = "20:53"; +const twenty24hourClockTime = "08:53"; diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..3e04bea95 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -2,21 +2,54 @@ 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; console.log(`The percentage change is ${percentageChange}`); -// Read the code and then answer the questions below +/* SOLUTION + + +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**: +1. `carPrice.replaceAll(",", "")` +2. `Number(carPrice.replaceAll(",", ""))` +3. `priceAfterOneYear.replaceAll("," "")` (should be `replaceAll(",", "")`) +4. `Number(priceAfterOneYear.replaceAll("," ""))` (should be `replaceAll(",", "")`) +5. `console.log(...)` + +**Lines with function calls:** +- `carPrice = Number(carPrice.replaceAll(",", ""));` +- `priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," ""));` +- `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?** +The error is on this line: +```javascript +priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +``` +There is a syntax error: `replaceAll("," "")` is missing a comma between the arguments. +**Fix:** +```javascript +priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); +``` + +c) **Identify all the lines that are variable reassignment statements** +- `carPrice = Number(carPrice.replaceAll(",", ""));` +- `priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));` -// a) How many function calls are there in this file? Write down all the lines where a function call is made +d) **Identify all the lines that are variable declarations** +- `let carPrice = "10,000";` +- `let priceAfterOneYear = "8,543";` +- `const priceDifference = carPrice - priceAfterOneYear;` +- `const percentageChange = (priceDifference / carPrice) * 100;` -// 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? +e) **Describe what the expression `Number(carPrice.replaceAll(",", ""))` is doing - what is the purpose of this expression?** +It removes all commas from the `carPrice` string (e.g., turns `"10,000"` into `"10000"`), then converts the result to a number (`10000`). +This allows for mathematical operations on the price. -// 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? +*/ diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..6e7bfe76e 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -23,3 +23,47 @@ 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) **How many variable declarations are there in this program?** +There are **6** variable declarations: `movieLength`, `remainingSeconds`, `totalMinutes`, `remainingMinutes`, `totalHours`, and `result`. + +b) **How many function calls are there?** +- The template literal uses `${...}` expressions, but these are not function calls. +- The only function call is `console.log(result);`. +So, there is **1** function call. + +c) **Using documentation, explain what the expression `movieLength % 60` represents** +The `%` operator returns the remainder after dividing `movieLength` by `60`. In this context, it gives the number of seconds left after converting as many full minutes +as possible from the total seconds. + +d) **Interpret line 4, what does the expression assigned to `totalMinutes` mean?** +`(movieLength - remainingSeconds) / 60` subtracts the leftover seconds from the total, then divides by 60 to get the total number of complete minutes in the movie. + +e) **What do you think the variable `result` represents? Can you think of a better name for this variable?** +`result` represents the movie length formatted as `hours:minutes:seconds`. A better name could be `formattedTime` or `movieLengthHMS`. + +f) **Try experimenting with different values of `movieLength`. Will this code work for all values of `movieLength`? Explain your answer** +The code works for positive integer values of `movieLength`. However, for values less than 60, `totalHours` and `remainingMinutes` will be `0`, which is correct. +For negative or non-integer values, the output may not make sense. Also, the output does not pad single-digit minutes or seconds with a leading zero (e.g., `1:2:3` instead of `01:02:03`). + + + + + + + + + + + + + + + + + + + +*/ diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..e3608a280 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -25,3 +25,23 @@ 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); +Removes the trailing "p" character from the string, leaving only the numeric part (e.g., "399"). + +3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +Pads the numeric string on the left with zeros so it is at least 3 characters long (e.g., "399" stays "399", but "9" would become "009"). This ensures consistent formatting for the next steps. + +4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); +Extracts all but the last two characters to represent the pounds part (e.g., from "399", it takes "3"). + +5. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0"); +Extracts the last two characters for the pence part (e.g., from "399", it takes "99"). If there are fewer than two characters, it pads the result on the right with zeros. + +c6. onsole.log(£${pounds}.${pence}); +Outputs the formatted price in pounds and pence (e.g., "£3.99"). + + +*/ diff --git a/prep/example.js b/prep/example.js new file mode 100644 index 000000000..5fb4293a2 --- /dev/null +++ b/prep/example.js @@ -0,0 +1,15 @@ +// function decimalTopercent(num){ +// let percent = num * 100; +// return percent +// } +// console.log(decimalTopercent(0.5) + "%"); + +function convertToPercentage(decimalNumber) { + const percentage = `${decimalNumber * 100}%`; + return percentage; +} + +const result = convertToPercentage(0.5); +const result1 = convertToPercentage(0.231); +console.log(result); +console.log(result1);