diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..503e5ae63 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -3,4 +3,13 @@ let count = 0; 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 +// Describe what line 3 is doing, in particular, focus on what = is doing + + +//The answers: +// In line 1, the variable `count` is declared and initialised with the value `0`. +// In line 3, the value of `count` is updated by assigning it the result of `count + 1`. Since the initial value was `0`, the new value becomes `0 + 1`, which is `1`. + +// In programming terms, this means the variable `count` is incremented by `1`. + +// The equals sign (`=`) is the assignment operator. It assigns the value on the right side of the `=` to the variable on the left side. diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..737e39bd7 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -5,7 +5,8 @@ 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[0] + middleName[0] + lastName[0]; +console.log(initials); // https://www.google.com/search?q=get+first+character+of+string+mdn diff --git a/Sprint-1/1-key-exercises/3-paths.js b/Sprint-1/1-key-exercises/3-paths.js index ab90ebb28..2aa8fe491 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -17,7 +17,10 @@ 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); +console.log(`The dir part of ${filePath} is: ${dir}`); -// https://www.google.com/search?q=slice+mdn \ No newline at end of file +const ext = base.slice(base.lastIndexOf(".") + 1); +console.log(`The ext part of ${filePath} is: ${ext}`); + +// 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..a8621a405 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -7,3 +7,21 @@ 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 + + +// Answers: + +// num is a variable that stores a random integer between 1 and 100, inclusive. +// • Math.floor() rounds a number down to the nearest integer. +// • Math.random() generates a decimal number between 0 (inclusive) and 1 (exclusive). +// • (maximum - minimum + 1) calculates the size of the range of possible numbers. Here, it is 100 - 1 + 1 = 100. +// • minimum is added at the end to shift the result so that it falls within the desired range starting from the minimum value. + +// How the formula works: +// 1. Calculate the size of the range using (maximum - minimum + 1). In this example, with maximum = 100 and minimum = 1, the range size is 100 - 1 + 1 = 100. +// 2. Math.random() generates a decimal number between 0 (inclusive) and 1 (exclusive), such as 0.0001 or 0.9999. +// 3. Multiply the result of Math.random() by the range size to scale the number. For example: 0.9999 * 100 = 99.99. +// 4. Use Math.floor() to round the scaled number down to the nearest whole number. For example: Math.floor(99.99) = 99. +// 5. Add the minimum value to shift the number into the correct range. For example: 99 + 1 = 100. + +// This ensures that num will always be an integer between 1 and 100, inclusive. diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..6ef2ea979 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; + +console.log(age); diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831..2865eb8a4 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,5 @@ // 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}`); diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..732710fdf 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -7,3 +7,17 @@ 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 + + + +// Answers: + +// The code isn’t working because the variable cardNumber is a number, not a string or an array. +// The slice method only works on strings or arrays. +// Therefore, calling const last4Digits = cardNumber.slice(-4); causes an error because .slice is not a function available for numbers. + +// I predicted this error because the variable cardNumber was not assigned as a string. + +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..8a5dda1ab 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,8 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +const hour24ClockTime = "20:53"; +console.log(hour24ClockTime); + +const hour12ClockTime = "08:53"; +console.log(hour12ClockTime); + +// The variables were renamed because JavaScript does not allow variables to start with numbers +// camelCase format used for variable names diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..cf353dbd9 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -11,12 +11,49 @@ 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: + +// • Line 4 — carPrice = Number(carPrice.replaceAll(",", "")); +// • carPrice.replaceAll() +// • Number() + +// • Line 5 — priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); +// • priceAfterOneYear.replaceAll() +// • 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? +// There is a syntax error on line 5. +// The two strings inside the replaceAll method are missing a comma separator, causing them to be concatenated incorrectly. +// Adding the missing comma between the two arguments will fix the problem. + +//----------------------------------------------------------------------------------------------- + // c) Identify all the lines that are variable reassignment statements +// • Line 4 — reassignment of carPrice +// • Line 5 — reassignment of priceAfterOneYear + +//----------------------------------------------------------------------------------------------- + // d) Identify all the lines that are variable declarations + // Line 1 - let (let carPrice = "10,000";) + // Line 2 - let (let priceAfterOneYear = "8,543";) + // Line 7 - const (const priceDifference = carPrice - priceAfterOneYear;) + // Line 8 - const (const percentageChange = (priceDifference / carPrice) * 100;) + +//----------------------------------------------------------------------------------------------- // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? + +// The value of carPrice is initially a string that includes commas, for example "10,000". +// JavaScript cannot perform numerical calculations on strings containing commas, as it does not recognise them as valid numbers. +// The method .replaceAll(",", "") removes all commas from the string, turning "10,000" into "10000". +// Finally, the Number() function converts the resulting string "10000" into the numeric value 10000, which allows mathematical operations to be performed on it. diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..95249c13c 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -11,15 +11,105 @@ 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 six variable declarations in the code: + + // Line 1 – const movieLength: + // Stores the total duration of the movie in seconds. + + // Line 3 – const remainingSeconds: + // Calculates the number of seconds remaining after converting to full minutes. + + // Line 4 – const totalMinutes: + // Stores the total number of full minutes, excluding the leftover seconds. + + // Line 6 – const remainingMinutes: + // Calculates the remaining minutes after converting to full hours. + + // Line 7 – const totalHours: + // Stores the total number of full hours in the movie duration. + + // Line 9 – const result: + // Constructs the final time in "HH:MM:SS" format as a string. + +//----------------------------------------------------------------------------------------------- // b) How many function calls are there? + // There is one function call in the code: + + // console.log(result): + // This function outputs the final formatted time (in "HH:MM:SS" format) 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 + // The expression "movieLength % 60" uses the modulo operator, + // which is an arithmetic operation that returns the remainder + // after division. + + // In this context, it helps determine how many seconds are left + // after converting the total movie length into full minutes. + + // For example: + // movieLength = 8784 seconds + // 8784 ÷ 60 = 146 full minutes with a remainder of 24 seconds + // So, movieLength % 60 = 24 + + // These 24 seconds are what remain after dividing the movie length + // into whole minutes. + + // If we subtract the 24 seconds from the total: + // 8784 - 24 = 8760 seconds + // Then: 8760 ÷ 60 = 146 full minutes + +//----------------------------------------------------------------------------------------------- // d) Interpret line 4, what does the expression assigned to totalMinutes mean? + // (movieLength - remainingSeconds): + // This subtracts the "remainingSeconds" (24) from the total "movieLength" (8784 seconds). + // The purpose is to remove the leftover seconds, leaving only the number of seconds + // that make up complete minutes. + + // / 60: + // This divides the result by 60 (since there are 60 seconds in a minute) + // to convert the remaining seconds into full minutes. + + // totalMinutes: + // This represents the total number of whole minutes in the movie, + // which in this example is 146. + +//----------------------------------------------------------------------------------------------- // e) What do you think the variable result represents? Can you think of a better name for this variable? + // The variable `const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`;` + // represents the length of the movie formatted as hours:minutes:seconds (HH:MM:SS). + + // A more descriptive name for this variable could be "movieDurationTime", + // as it clearly indicates that the value represents the movie's duration + // in a time format. + +//----------------------------------------------------------------------------------------------- // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer + + // This code will not display properly for movies with a duration of 0 seconds, + // as the output would appear as "0:0:0", which is not well-formatted. + + // We can fix this by applying the .padStart() method to each time unit + // (hours, minutes, and seconds) to ensure they are always displayed + // with two digits — for example, "00:00:00". + + // We use .padStart() on string values because all the time units + // are integers, and this method works on strings. + + + + + + + + + + diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..fd2ec75a9 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -25,3 +25,31 @@ 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); +// This line removes the last character from the input string, which is the letter "p" (representing pence). +// The reason we remove "p" is that we can't perform calculations on a string that includes non-numeric characters. + + +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +// This line ensures the string is at least three characters long by padding it with leading zeros if necessary. +// This formatting allows us to easily separate the value into pounds and pence — where the last two digits represent pence and the remaining digits represent pounds. + + +// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); +// This line extracts the pound portion of the value by taking all characters except the last two. +// For example, if the input is "399p", it becomes "399", and this line extracts "3" as the pound value. + + +// 5. const pence = paddedPenceNumberString +// .substring(paddedPenceNumberString.length - 2) +// .padEnd(2, "0"); +// This line extracts the last two digits, which represent the pence. +// The `.padEnd(2, "0")` ensures that even if the pence value is only one digit (e.g., "5"), it becomes two digits (e.g., "05"). +// So "5p" would correctly display as "£0.05" instead of "£0.5". + + +// 6. console.log(`£${pounds}.${pence}`); +// This line prints the final result in the correct British currency format. +// If the input is "399p", the output will be "£3.99". +// This step is important for presenting the value in a user-friendly and readable format. diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feaf..86cc2bf2d 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -16,3 +16,33 @@ Now try invoking the function `prompt` with a string input of `"What is your nam What effect does calling the `prompt` function have? What is the return value of `prompt`? + + +## What I Did in the Chrome Console + +1. I opened a new page in Google Chrome. +2. I right-clicked on the page and selected **Inspect**. +3. In the Developer Tools window, I clicked on the **Console** tab. +4. I typed the function `alert("Hello world!");` and pressed **Enter**. +5. A pop-up appeared displaying the message **"Hello world!"**. I clicked **OK** to close it. +6. Next, I typed `const myName = prompt("What is your name?");` and pressed **Enter**. +7. A dialog box appeared with the message **"What is your name?"** and a text input field. +8. I entered my name, **Sed**, into the input box and clicked **OK**. +9. The browser stored my input in the variable `myName`. +10. Then, I typed `console.log("You entered:", myName);` and pressed **Enter**. +11. The console displayed: `You entered: Sed` + +--- + +## What Effect Does Calling the `prompt()` Function Have? + +It displays a dialog box that prompts the user to enter information. +If the result is assigned (e.g., `const myName = prompt("What is your name?");`), +the user's input is stored in the variable (in this case, `myName`). + +--- + +## What Is the Return Value of `prompt()`? + +The value entered by the user is returned as a **string**. +If the user clicks **Cancel**, the return value is **`null`**. diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..8e9a794ac 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -14,3 +14,42 @@ Answer the following questions: What does `console` store? What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + +Answers: + +# Exploring the Chrome DevTools Console + +**Open the Chrome DevTools Console, type `console.log` and then hit Enter** +Done. + +**What output do you get?** +I got: +ƒ log() { [native code] } + +**Now enter just `console` in the Console, what output do you get back?** +I got: +console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …} + +**Try also entering `typeof console`** +I got: +"object" + +--- + +## What does `console` store? + +`console` is a JavaScript object that provides access to the browser's debugging console. +It stores functions such as `log`, `error`, `warn`, etc., which are used to track or print information while the code runs. + +--- + +## What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + +It means to access the `log` function that belongs to the `console` object. + +--- + +## What does the `.` mean? + +The dot (`.`) is a notation in JavaScript used to access a property or function on an object. +So, `console.log()` means: call the `log` method that belongs to the `console` object.