diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6e..3b32cc8fd0 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -1,6 +1,13 @@ let 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 + +//Line 3 is updating the value of the variable `count`. +//The `=` operator is an assignment operator, +//which means it takes the value on the right side (in this case, `count + 1`, +//which evaluates to 1) and assigns it to the variable on the left side (`count`). +//So after this line executes, the value of `count` will be updated from 0 to 1. diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f6175..ff06671d21 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -6,6 +6,6 @@ let lastName = "Johnson"; // 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 = ``; - +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 ab90ebb28e..76a7980930 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -17,7 +17,9 @@ 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); +const dotIndex = filePath.lastIndexOf("."); // const dotIndex = filePath.lastIndexOf("."); +// is a search-and-record operation. +const ext = filePath.slice(dotIndex + 1); -// 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 292f83aabb..1bb820558c 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -3,7 +3,31 @@ 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 + +// THE EXPLANATION: + +// num represents a random whole number (integer) between 1 and 100, inclusive. + +// By using this specific formula, we can generate a random number between any two limits just by changing the minimum and maximum values. + +// when i added console.log(num); at the bottom of our script and run it multiple times, +// i notice i get a different whole number every time, but it will never drop below 1 and never go above 100. + +// to be more specific, +// maximum - minimum + 1: This calculates the size of the range. Plugging in the numbers ($100 - 1 + 1$), it evaluates to 100. +// This ensures there are 100 possible outcomes.Math.random(): +// This built-in JavaScript function generates a random decimal number starting from 0 (inclusive) up to, but not including, 1 (exclusive). +// For example, it could be 0.0, 0.523, or 0.999.Math.random() * 100: Multiplying the random decimal by 100 shifts the decimal point, scaling the range. +// This results in a random decimal number between 0 and 99.999.... +// Math.floor(...): This function takes the decimal and rounds it down to the nearest whole number. +// This strips away the decimals, leaving us with a random whole number from 0 to 99.+ minimum: +// Finally, adding the minimum value (1) shifts the entire range upward. Instead of 0 to 99, the possible results become 1 to 100. +// Running the program (What happens when you log it): when i added console.log(num);Observation: Each time the code runs, the console outputs a single integer. +// For example, Run 1 might output 42, Run 2 might output 7, and Run 3 might output 100. +// The numbers change unpredictably because of Math.random(), but they will never be lower than 1 or higher than 100. diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f7..ce4e5cc773 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/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 +We don't want the computer to run these 2 lines - how can we solve this problem? + +//to answer this question, we can use comments in our code. +//In JavaScript, we can use `//` for single-line comments or `/* */` for multi-line comments. \ 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 7a43cbea76..f9de9e3cb7 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -2,3 +2,20 @@ const age = 33; age = age + 1; +// This code will throw an error because `age` is declared as a constant +// using `const`, which means its value cannot be reassigned. +// To fix this, we can declare `age` using `let` instead of `const`, which allows reassignment. +let age = 33; +age = age + 1; +console.log(age); +// Now the code will run without errors, and it will output 34 to the console. +//or we can us this to create an age variable and then reassign the value by 1 + +// The user object itself is locked, but its contents are flexible +const user = { + age: 33 +}; + +user.age = user.age + 1; + +console.log(user.age); // Outputs: 34 \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831d..ab4f2e2808 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -3,3 +3,11 @@ console.log(`I was born in ${cityOfBirth}`); const cityOfBirth = "Bolton"; + +// The error in the code is that the variable `cityOfBirth` is being used before it is declared and assigned a value. +// In JavaScript, variables declared with `const` (or `let`) are not hoisted in the same way as `var`, +// meaning they cannot be accessed before their declaration. +// To fix this error, we need to declare and assign a value to `cityOfBirth` before using it in the `console.log` statement. +// Here's the corrected code: +//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 ec101884db..bbd3cbaa25 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -7,3 +7,20 @@ 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 + +// the response to this question is that the code won't work because the `slice` method is being called on a number, +// but `slice` is a method that is only available for strings and arrays. Since `cardNumber` is a number, +// it does not have the `slice` method, which will result in a TypeError when the code is run. +// To fix this, we can convert `cardNumber` to a string before calling the `slice` method. +// Here's the corrected code: +const cardNumber = 4533787178994213; +const last4Digits = cardNumber.toString().slice(-4); +console.log(last4Digits); // Outputs: "4213" +//or we can use this to get the last 4 digits of cardNumber +// Put quotes around it to make it a string from day one +const cardNumber = "4533787178994213"; + +// Now .slice() works perfectly instantly +const last4Digits = cardNumber.slice(-4); + +console.log(last4Digits); // Outputs: "4213" \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 5f86c730bc..25b57f57bf 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,12 @@ const 12HourClockTime = "8:53pm"; const 24hourClockTime = "20:53"; + +// The error in the code is that the variable `12HourClockTime` starts with a number, +// which is not allowed in JavaScript variable names. +// Variable names must start with a letter, underscore (_), or dollar sign ($). +// To fix this error, we can rename the variable to start with a letter, +// such as `twelveHourClockTime` or `hour12ClockTime`. +const twelveHourClockTime = "8:53pm"; +const hour24ClockTime = "20:53"; +// you can ether put the number at thr end of the variable name or spell it out in words, +// but you cannot start a variable name with a number. \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e18..942671a8e6 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -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? + +// answers for the questions above: + +// a) There are 3 function calls in this file. The function calls are on the following lines: +// - Number(carPrice.replaceAll(",", "")) +// - Number(priceAfterOneYear.replaceAll(",", "")) +// - console.log(`The percentage change is ${percentageChange}`); + +// b) The error comes from Line 5 and line 1: +// - line 1: 1st carPrice = "10,000"; +// - JavaScript cannot perform accurate math operations on strings that contain commas +// - priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +// - Why is it occurring? It throws a SyntaxError: Unexpected string. This happens because a comma is missing between the two arguments passed into the .replaceAll() method. JavaScript sees "," "" and doesn't know how to interpret two strings jammed together without a separator. +// - How to fix it: Add a comma between the arguments just like you did on Line 4. + +// c) The variable reassignment statements are on the following lines: +// - Line 4: carPrice = Number(carPrice.replaceAll(",", "")); +// - Line 5: priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); + +// d) The variable declarations are on the following lines: +// - 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) The expression Number(carPrice.replaceAll(",","")) is doing the following: +// - carPrice.replaceAll(",", ""): It takes the original string "10,000", finds all the commas, and replaces them with an empty string (""). +// -This strips the formatting and turns the string into "10000". +// - Number(...): It takes that clean string "10000" and type-casts (converts) it into an actual primitive number data type: 10000. + diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d2395587..2c32cbfb95 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -23,3 +23,29 @@ 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 + +// the answers to the questions above: +// a) there are 6 variable declarations in this program. you can identify them by the const keyword. they are: +// - const movieLength = 8784; +// - const remainingSeconds = movieLength % 60; +// - const totalMinutes = (movieLength - remainingSeconds) / 60; +// - const remainingMinutes = totalMinutes % 60; +// - const totalHours = (totalMinutes - remainingMinutes) / 60; +// - const result = \${totalHours}:${remainingMinutes}:${remainingSeconds}`; +// +// b) there is only 1 function call in this program. it is +// - console.log(result); (Calling the log function of the console object). +// c) According to the MDN documentation, the % operator is the Remainder operator. +// In the expression movieLength % 60, it divides the total number of seconds (movieLength) by 60 and returns whatever is left over. +// Because there are 60 seconds in a minute, this expression isolates the leftover seconds that don't cleanly fit into a whole minute. +// For 8784, $8784 \div 60 = 146$ with a remainder of 24. +// d) This expression calculates the total, clean number of minutes in the movie. +// By subtracting remainingSeconds from movieLength, it rounds the total seconds down to a number perfectly divisible by 60. +// Dividing that result by 60 converts those seconds into minutes.For 8784 seconds: $(8784 - 24) / 60 = 8760 / 60 = 146$ minutes. +// e) The variable result represents the total length of the movie formatted as a string in the format "hours:minutes:seconds". +// A better name for this variable could be formattedMovieLength or movieDurationFormatted to make it more descriptive. +// f) No, it will not work perfectly for all values. Here is why: +// - Negative Numbers: If movieLength is negative (e.g., -500), the remainder operator in JavaScript retains the sign of the dividend. You would end up with negative strings like 0:-8:-20. +// - Formatting/Padding Issues: If any of the time units are less than 10, they won't have a leading zero. For example, if a movie is exactly 1 hour and 5 minutes long, this code will output 1:5:0 instead of a standard digital clock format like 01:05:00. +// - Non-Integers: If movieLength is a decimal (like 8784.5), the math will break down and pass decimals into your minutes and hours, resulting in a messy string. +// - Tip: To make this bulletproof for all positive integers, you would typically use String.prototype.padStart(2, '0') to ensure the minutes and seconds always show up as two digits (e.g., 05 instead of 5). \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69a..da9c57a7b1 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -24,4 +24,32 @@ 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" +// const penceString = "399p": initialises a string variable with the value "399p" +// Rationale: This serves as the raw input data for the program, +// simulating a price format you might get from a user input or a database. + +// const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1); +// // What it does: Extracts a portion of penceString starting from index 0 up to (but not including) the very last character. +// It stores "399" in penceStringWithoutTrailingP. +// Rationale: To do any math or structural formatting, +// the trailing "p" needs to be stripped away so the program is left with just the numeric characters. + +// const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +// What it does: Pads the start of the string with "0"s until the string reaches a total length of 3 characters. +// For "399", it stays "399". However, if the input was "5p", this step would turn "5" into "005". +// Rationale: This is a safety measure for small amounts (under £1.00). +// By forcing a minimum length of 3 characters, it ensures there are always enough digits to separate into at least one digit for pounds and two digits for pence. + +// const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); +// What it does: Grabs everything from the start of the padded string up to the final 2 characters. +// For "399", it extracts "3". For a padded string like "005", it would extract "0". +// Rationale: Since 100 pence equals 1 pound, the last two digits of any pence value will always represent the change, and everything before those last two digits represents the whole pounds. + +// const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0"); +// What it does: This does two things. First, .substring(...) extracts exactly the last 2 characters of the string (e.g., "99" from "399"). +// Then, .padEnd(2, "0") ensures it is 2 characters long by adding zeros to the right (though because of the previous steps, it's already 2 characters long here). +// Rationale: This isolates the final two digits to represent the pence column cleanly, ensuring it always displays as a standard two-digit currency format (like .05 or .99). + +// console.log(\£${pounds}.${pence}`);` +// What it does: Uses a template literal to combine the pound sign (£), the pounds variable, a decimal point (.), and the pence variable into one string, printing £3.99 to the console. +// Rationale: This is the final presentation layer, formatting the separated data pieces into a human-readable UK currency format. diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feafe..04ca89f043 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -12,7 +12,12 @@ invoke the function `alert` with an input string of `"Hello world!"`; What effect does calling the `alert` function have? +The Effect: Calling alert pauses the browser execution and triggers a modal pop-up dialog box at the top of the screen displaying the text "Hello world!". It includes an "OK" button that the user must click to dismiss the alert and resume interacting with the page. + Now try invoking the function `prompt` with a string input of `"What is your name?"` - store the return value of your call to `prompt` in an variable called `myName`. What effect does calling the `prompt` function have? + +The Effect: Calling prompt opens a different type of pop-up dialog box that displays the message "What is your name?", a text input field for the user to type into, and two buttons: "OK" and "Cancel". What is the return value of `prompt`? +The Return Value: * If you type a name (e.g., "Alex") and click OK, the function returns that exact text as a string (undefind). This string is what gets stored in your myName variable. diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56a..4cf0a21cf0 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -5,12 +5,21 @@ In this activity, we'll explore some additional concepts that you'll encounter i Open the Chrome devtools Console, type in `console.log` and then hit enter What output do you get? - +console.log + Enter: You will see something like ƒ log() { [native code] }. Now enter just `console` in the Console, what output do you get back? - +console + Enter: You will see an expandable drop-down list displaying a massive list of built-in features like clear, error, info, log, warn, etc. Try also entering `typeof console` - +typeof console + Enter: The console will return the string "object". Answer the following questions: What does `console` store? +The console object stores a collection of properties and methods (functions) that allow you to interact with the browser's debugging console. Instead of storing just a single value (like a number or string), it acts as a container for tools that let you log text, display errors, format data into tables, and run assertions. + What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? +The . (Dot): This is known as the dot notation operator. In JavaScript, it is used to access the properties or methods stored inside an object. You can think of it like an address or a path: Object.Property. + +The Syntax: * console.log means: "Go to the console object, and find the log method inside it." + +console.assert means: "Go to the console object, and find the assert method inside it." + +Analogy: Think of console as a literal toolbox, and the dot (.) as the act of reaching inside it. console.log means you are reaching into the console toolbox to grab the log tool.