diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..576707c48 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -2,5 +2,9 @@ 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 reassigning the value of count by adding 1 to its current value. \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..58ae6f12f 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -4,8 +4,13 @@ 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. +// https://www.google.com/search?q=get+first+character+of+string+mdn + +const initials = firstName.charAt(0) + middleName.charAt(0) + lastName.charAt(0); +console.log( `acronym = ${initials}`); + + + -let 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..44bb20874 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -12,12 +12,23 @@ const filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt"; const lastSlashIndex = filePath.lastIndexOf("/"); 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 // Create a variable to store the ext part of the variable -const dir = ; -const ext = ; +const lastDot = filePath.lastIndexOf("."); +console.log(`The indexDot is ${lastDot}`); + +const ext = filePath.slice(lastDot); + +const fileName = filePath.slice(lastSlashIndex + 1, lastDot); +const dir = filePath.slice(1, lastSlashIndex + 1); + + + +console.log(`The dir is πŸ‘‰ ${dir}`); +console.log(`The nameFile is πŸ‘‰ ${fileName}`); +console.log(`The extension is πŸ‘‰ ${ext}`); + + -// https://www.google.com/search?q=slice+mdn \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/4-random.js b/Sprint-1/1-key-exercises/4-random.js index 292f83aab..2724fd39b 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -1,9 +1,17 @@ +// 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 + const minimum = 1; const maximum = 100; const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; +//this line will generate a random number between minimum and maximum (inclusive) +// and math.floor will remove decimal part -// 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 +Math.floor() //removes decimal part and returns whole number +Math.random() //needs to values between minimum and maximum to generate a random number + +console.log(maximum - minimum + 1 ) + minimum; // this is same as 100 - 1 + 1 = 100 +console.log(`The random number is ${num}`); \ No newline at end of file diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..fdd0243ec 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/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 +//to write comments in JavaScript, we use two forward slashes like this so, for this exercise, +// we can comment out the two lines above to prevent them from being executed. \ 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 7a43cbea7..fe1fe52ce 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,7 @@ // trying to create an age variable and then reassign the value by 1 -const age = 33; -age = age + 1; +let age = 33; +age += 1; +console.log(age); + +// We need to use 'let' to reassign a variable; 'const' does not allow reassignment. \ 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 e09b89831..58d49db31 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/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}`); + +// explanation: the error was that the variable cityOfBirth was not defined before it was used in the console.log statement. + diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..3939ee223 100644 --- a/Sprint-1/2-mandatory-errors/3.js +++ b/Sprint-1/2-mandatory-errors/3.js @@ -1,5 +1,9 @@ const cardNumber = 4533787178994213; -const last4Digits = cardNumber.slice(-4); +const numberString = cardNumber.toString(); +const last4Digits = numberString.slice(-4); +const num = Number(last4Digits); + +console.log(num); // The last4Digits variable should store the last 4 digits of cardNumber // However, the code isn't working @@ -7,3 +11,10 @@ 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 + + + +// explanation: to see the numbers correctly we need to convert the cardNumber to a string +// first before slicing the last 4 digits. The original code was trying to use slice +// a number, which is not valid. By converting it to a string first, +// we can then slice the last 4 characters correctly. Then we convert it back to a number. \ 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 21dad8c5d..aeb4f50fb 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,11 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file + +// explanation: the first lines will throw an error because js detect a number instead of a variable name, +// so we move the number to the end and now it works fine. +// const 24hourClockTime = "08:53; +// const 12HourClockTime = "20:53"; + + +const clock12h = "20:53"; +const clock24h = "08:53"; +console.log(clock12h); +console.log(clock24h); \ 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 e24ecb8e1..301d297a5 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/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; @@ -13,10 +13,51 @@ console.log(`The percentage change is ${percentageChange}`); // a) How many function calls are there in this file? Write down all the lines where a function call is made + // There are 6 function calls in this file: + // Line 5: carPrice.replaceAll(",", "") + // Line 5: Number(carPrice.replaceAll(",", "")) + // Line 6: priceAfterOneYear.replaceAll(",", "") + // Line 6: Number(priceAfterOneYear.replaceAll(",", "")) + // Line 10: console.log(`The percentage change is ${percentageChange}`) this is also + // a function call to log the output as string to the console, then call the var percentageChange + + // 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 was line 5, carPrice.replaceAll("," ""); missing the comma between the arguments // c) Identify all the lines that are variable reassignment statements + //line 4, line 5, + // d) Identify all the lines that are variable declarations + // line 1, line 2, line 7 and line 8 + + // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? + + // This expression will work in the parenthesis first, replacing all commas in the string carPrice + // with an empty string, so basically returning the string 10000 instead of "10,000". + // Then the Number() function will convert that string "10000" into a number 10000. + // secondly, js can not treat strings with commas as numbers, so we need to remove the commas + // now with the number cleaned we can convert this string in number with the method Number(). + + + +// ---------- console.log each step to see the results ---------- + + // let carPrice = "10,000"; + // let priceAfterOneYear = "8,543"; + + // carPrice = Number(carPrice.replaceAll(",", "")); + // console.log(carPrice); // the commas are removed and the string is converted to a number + + // priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); + // console.log(priceAfterOneYear); // the commas are removed and the string is converted to a number + + // const priceDifference = carPrice - priceAfterOneYear; + // console.log(`The price difference is ${priceDifference}`); + + // const percentageChange = (priceDifference / carPrice) * 100; + // console.log(`The percentage change is ${percentageChange}`); \ No newline at end of file diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..02fc3aaa3 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -1,7 +1,8 @@ -const movieLength = 8784; // length of movie in seconds +const movieLength = 5; // length of movie in seconds -const remainingSeconds = movieLength % 60; +const remainingSeconds = movieLength % 60; console.log(remainingSeconds);//24 const totalMinutes = (movieLength - remainingSeconds) / 60; +console.log(totalMinutes);//146 const remainingMinutes = totalMinutes % 60; const totalHours = (totalMinutes - remainingMinutes) / 60; @@ -13,13 +14,36 @@ console.log(result); // a) How many variable declarations are there in this program? + // There are six variable declarations in this program: + // movieLength, remainingSeconds, totalMinutes, remainingMinutes, totalHours, and result. + // b) How many function calls are there? + //There is one function call in this program: console.log(result); + //In JavaScript, a function call almost always involves parentheses () immediately following a name. + // 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 calculates the remainder when movieLength is divided by 60. + //this means this calculation 8784/60 = 146.4 but we are looking for the seconds + //we take the integer part 146 * 60 = 8760 - 8784 = 24 seconds remaining + + // d) Interpret line 4, what does the expression assigned to totalMinutes mean? + // Line 4 calculates the total number of whole minutes in the movie length. + // It subtracts the remaining seconds from the total movie length to get a value that is a multiple of 60, + // and then divides that value by 60 to convert it from seconds to minutes. + // So, it gives us the total number of complete minutes in the movie length. + // e) What do you think the variable result represents? Can you think of a better name for this variable? + //result stores the variables of totalHours, remainingMinutes and remainingSeconds in a string format readable time clock "H:M:S" + //A better name for this variable could be MovieDuration + // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer + + + //Yes, this code will work for all values of movieLength as it correctly calculates hours, minutes, and seconds + //but if the movieLength is less than 5 seconds, will be 0:0:5, we need to use the padStart method to add leading zeros for better formatting. \ 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 60c9ace69..d281f6769 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -1,3 +1,4 @@ +//declare a constant variable named penceString and assign it the string value "399p" const penceString = "399p"; const penceStringWithoutTrailingP = penceString.substring( @@ -5,16 +6,25 @@ const penceStringWithoutTrailingP = penceString.substring( penceString.length - 1 ); -const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); -const pounds = paddedPenceNumberString.substring( - 0, - paddedPenceNumberString.length - 2 -); +// here we remove the trailing 'p' from the string using the method substring() -1 of the total length +console.log(penceStringWithoutTrailingP); + + +//this line pads will contain a length of at least 3 characters, adding leading zeros if necessary +const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");//399 or diff value -> 001 + +// here we extract the pounds part of the string by taking all characters except the last two eg. 399 -> 3 +const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2); //3 + +console.log(` this is the padStart adding 0 if its necessary ${paddedPenceNumberString}, and this here we just take the integer part ${pounds}`); + +// here we extract the pence part of the string by taking the last two characters eg. 399 -> 99 const pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) .padEnd(2, "0"); + console.log(` this is the pence part we take the last two digits ${pence}`); console.log(`Β£${pounds}.${pence}`); // This program takes a string representing a price in pence diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feaf..61754ac33 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -10,9 +10,41 @@ Let's try an example. In the Chrome console, invoke the function `alert` with an input string of `"Hello world!"`; + To invoke an alert that lives in the engine v8; we need to + run `alert("Hi there!")` + + What effect does calling the `alert` function have? + In short: alert() interrupts the page to show a message and waits for the user to acknowledge it. + + πŸ“’ The message you pass to alert() is displayed to the user. + + ⏸️ JavaScript execution pauses until the user clicks OK. + + 🚫 The user can’t interact with the page while the alert is open (it blocks the UI). + + + 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`. + + let myName = prompt("hello what is your name") + alert("hi " + myName) + + The prompt function displays a modal dialog that captures user input. The value entered is stored in myName, and alert then displays a greeting that includes that value. + + What effect does calling the `prompt` function have? What is the return value of `prompt`? + + Calling the prompt() function displays a modal pop-up dialog that: + + * Shows a message to the user + + * Includes a text input field + + * Has OK and Cancel buttons + + * Blocks interaction with the page until the user responds + diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..246db53a7 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -4,13 +4,50 @@ 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 + console.log + Ζ’ log() { [native code] } + Explanation: + This output indicates that console.log is a function provided by the browser (native code). You are seeing the function itself, not executing it. + + What output do you get? Now enter just `console` in the Console, what output do you get back? + console + and press Enter, the Console shows something like: + + console {debug: Ζ’, error: Ζ’, info: Ζ’, log: Ζ’, warn: Ζ’, …} + Explanation: + This output shows that console is an object containing multiple methods, such as: + + * log + * error + * warn + * info + * debug + + Each of these properties is a function that can be used to output messages to the Console in different ways. + Try also entering `typeof console` + typeof console + 'object' + Answer the following questions: What does `console` store? What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + + console is an object + + It stores methods (functions) + + . is used to access properties or methods on an object + + log / assert β†’ a property of console (in this case, a function) + + console stores an object. + This object contains properties and methods (mostly functions) provided by the browser for debugging, such as log, error, warn, info, and assert. + + diff --git a/Sprint-1/exercises/decimal.js b/Sprint-1/exercises/decimal.js new file mode 100644 index 000000000..7d0095435 --- /dev/null +++ b/Sprint-1/exercises/decimal.js @@ -0,0 +1,21 @@ +const num = 56.5678; + +// You should look up Math functions for this exercise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math + +// Create a variable called wholeNumberPart and assign to it an expression that evaluates to 56 ( the whole number part of num ) +// Create a variable called decimalPart and assign to it an expression that evaluates to 0.5678 ( the decimal part of num ) +// Create a variable called roundedNum and assign to it an expression that evaluates to 57 ( num rounded to the nearest whole number ) + +// Log your variables to the console to check your answers + + +const wholeNumberPart = Math.floor(num); +console.log(` Whole number = ${wholeNumberPart}`); + +const decimalPart = num - wholeNumberPart; +console.log(` Decimal part = ${decimalPart.toFixed(4)}`); // toFixed(4) to show 4 decimal places instead of whole number + +console.log(`type of parameter = ${typeof(wholeNumberPart)}`); //confirm that decimalPart is a number + +const roundedNum = Math.round(num); // rounds to nearest whole number +console.log(` Rounded number = ${roundedNum}`); \ No newline at end of file