diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..48b6bd64f 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -4,3 +4,5 @@ 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 adds 1 to the value of count. It does this with a simple mathematical expression (count + 1) and using the = operator to reassign the result of the expression to the variable. diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..9f5dbcc82 100644 --- a/Sprint-1/1-key-exercises/2-initials.js +++ b/Sprint-1/1-key-exercises/2-initials.js @@ -5,7 +5,6 @@ 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]}`; // 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..fdf8ff7ed 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -1,11 +1,11 @@ // The diagram below shows the different names for parts of a file path on a Unix operating system -// ┌─────────────────────┬────────────┐ -// │ dir │ base │ -// ├──────┬ ├──────┬─────┤ -// │ root │ │ name │ ext │ +// ???????????????????????????????????? +// ? dir ? base ? +// ???????? ?????????????? +// ? root ? ? name ? ext ? // " / home/user/dir / file .txt " -// └──────┴──────────────┴──────┴─────┘ +// ???????????????????????????????????? // (All spaces in the "" line should be ignored. They are purely for formatting.) @@ -17,7 +17,7 @@ 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(filePath.indexOf("/") + 1, lastSlashIndex); +const ext = base.slice(base.lastIndexOf(".")); -// 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..22ea623bb 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -3,7 +3,19 @@ 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 + +// Maths operations are solved using the PEMDAS order: parentheses, exponents, multiplication & division and addition & subtraction. Javascript does the same +// The program starts by executing Math.random(), which is a method that returns a float number (decimal, not integer) that is greater or equal to 0 and smaller than 1. This number is random and will always be different, but for my explanation I will use 0.123456 +// Next the program executes the other parenthesis, by first adding 1 to minimum and then subtracting the result from maximum. In this case it would be -1 + 1 = 0 and then 100 - 0 = 100 +// The program will then move on to multiply 0.123456 x 100 = 12.3456 +// The next step is Math.floor(), which is a method that rounds a number down to it's closest integer. In our case 12.3456 becomes 12 +// Lastly the program executes the last addition, Math.floor() + minimum, and assigns the result to num: num = 12 + 1 = 13 +// The value of num is therefore a random number between 1 and 100 +// Additional note: +// Adding minimum at the end is necessary to avoid the final result being 0, which could happen if, our Math.random() result was something like 0.000123 +// 0.000123 x 100 = 0.0123, which would then be round down by Math.floor() to 0 diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..67e75296f 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/2-mandatory-errors/0.js @@ -1,2 +1,6 @@ -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? + +// Explanation +// The computer will try to run anything that is not a comment. To make comments we can add // at the beginning of a line (ctrl + /) +// for multiple line comments we use /* text */ diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..556af6f0f 100644 --- a/Sprint-1/2-mandatory-errors/1.js +++ b/Sprint-1/2-mandatory-errors/1.js @@ -1,4 +1,8 @@ // trying to create an age variable and then reassign the value by 1 -const age = 33; +let age = 33; age = age + 1; + +// const are variables which value cannot change +// let is a variable which value can be updated +// to fix the error I modified the variable declaration and used let instead of const diff --git a/Sprint-1/2-mandatory-errors/2.js b/Sprint-1/2-mandatory-errors/2.js index e09b89831..7474e640e 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}`); + +// ReferenceError: Cannot access 'cityOfBirth' before initialization +// This error appears because the variable cityOfBirth is created after the console.log, so the computer cannot access it. +// To fix the error I just moved the console.log below the variable declaration diff --git a/Sprint-1/2-mandatory-errors/3.js b/Sprint-1/2-mandatory-errors/3.js index ec101884d..807518d6d 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 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,6 @@ 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 + +// slice() is a String method, but cardNumber is a data of type Number, so we cannot use String methods on it. +// A simple solution is to transform cardNumber into a string using the string constructor String() diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..86336031d 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,9 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +// const 12HourClockTime = "20:53"; +// const 24hourClockTime = "08:53"; + +const clockTime12Hour = "08:53"; +const clockTime24Hour = "20:53"; + +// I see two errors here: +// 1 - In Javascript, variable names cannot start with numbers. +// 2 - The variable names are both descriptive, which is correct, but their values seem to have been swapped with each other: the 24h clock should be 20:53 and the 12h clock 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..1d14e61ef 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; @@ -12,11 +12,18 @@ 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 3 function calls in this file. The Number() constructor is called twice on lines 4 and 5. On line 10 console.log() is also called // 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? +// /home/kris/Code/CYF/ITP/Module-Structuring-and-Testing-Data/Sprint-1/3-mandatory-interpret/1-percentage-change.js:5 <-- this indicates the error is on line 5 +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +// ^^^ <-- This highlights where the error is in the line. In this case the computer stops reading the code at the highlighted part because we are missing a comma after that // c) Identify all the lines that are variable reassignment statements +// carPrice is reassigned at line 4 and priceAfterOneYear is reassigned at line 5 // d) Identify all the lines that are variable declarations +// Line 1 (carPrice), line 2 (priceAfterOneYear), line 7 (priceDifference) and line 8 (percentageChange) // e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? +// The replaceAll() method replaces one or more characters of a string with something different. In this case, the method just removes the comma, because the replacement value is an empty string diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..80f8964fa 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -1,4 +1,4 @@ -const movieLength = 8784; // length of movie in seconds +const movieLength = 98686; // length of movie in seconds const remainingSeconds = movieLength % 60; const totalMinutes = (movieLength - remainingSeconds) / 60; @@ -6,20 +6,26 @@ const totalMinutes = (movieLength - remainingSeconds) / 60; const remainingMinutes = totalMinutes % 60; const totalHours = (totalMinutes - remainingMinutes) / 60; -const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; -console.log(result); +const formattedMovieLength = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; +console.log(formattedMovieLength); // 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 6 variable declarations, on lines 1, 3, 4, 6, 7 and 9 // b) How many function calls are there? +// There is only 1 function call on line 10 (console.log()) // c) Using documentation, explain what the expression movieLength % 60 represents // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators +// The % is called modulo operator. This operator divides a number by a chosen value (in this case 60) and returns the leftover amount: i.e.: 130 % 60 = 10 // d) Interpret line 4, what does the expression assigned to totalMinutes mean? +// remainingSeconds is the leftover of movieLength divided by 60, meaning it's a number of seconds smaller than 1 minute. In line 4, these seconds are first subtracted from the total length of the movie, leaving a number of seconds that, when divided by 60, will result in an integer number, giving us the number of full minutes in the movie (totalMinutes) // e) What do you think the variable result represents? Can you think of a better name for this variable? +// result is a string with the movie length in H:M:S format. A possible better name could be formattedMovieLength // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer +// The code technically works. It always return the movie length with a H:M:S format, but with room for improvement. In cases where the number of seconds or minutes are less than 10, they are displayed as only 1 digit. But conventional time formatting would require 2 digits. For example, a time of 2 hours, 7 minutes and 3 seconds, should be displayed as 03:02:07, but the code would print 2:7:3, making difficult to identify the result as a length of time. To improve the code, we could add logic that would account for cases in which the hour, minutes or seconds are less than 10 by adding a 0 before them. diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..3bf2dc82d 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -24,4 +24,14 @@ 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" +// 1. const penceString = "399p" <-- initialises a string variable with the value "399p" + +// 3. const penceStringWithoutTrailingP = penceString.substring( 0, penceString.length - 1) <-- removes the last character from penceString (p) and assign the resulting value to a new variable penceStringWithoutTrailingP + +// 8. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0") <-- using padStart, ensures the string is at least 3 characters. In case of the string being less than 3 characters, padStart will add "0" at the beginning until it reaches the required length. The resulting string is assigned to a new variable paddedPenceNumberString + +// 9. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2) <-- uses the substring() method to create a new string from paddedPenceNumberString without the last 2 characters. This new string is then assigned to the new variable pounds + +// 14. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0") <-- takes the last two characters of paddedPenceNumberString and creates a new string that is then assigned to the variable pence. The padEnd() method, which ensures a length of 2 characters by adding a "0" at the end, seems to be redundant, as substring is already returning 2 characters, so the 0 will never be added. + +// 18. console.log(`£${pounds}.${pence}`) <-- uses template literals to create a string by putting together "£", the pound amount, "." and the pence amount. Then string is then printed in the terminal with console.log() diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feaf..df4f31dd8 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -12,7 +12,11 @@ invoke the function `alert` with an input string of `"Hello world!"`; What effect does calling the `alert` function have? +An alert box pops up in the browser window displaying my Hello World! message. + 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? +A prompt box pops up, displaying my question and an input field for me to answer. What is the return value of `prompt`? +My answer as a string. diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..316aed8fd 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -5,12 +5,44 @@ 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? +ƒ log() { [native code] } <-- tells me log() is a native function of Javascript Now enter just `console` in the Console, what output do you get back? +console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …} +assert: ƒ assert() +clear: ƒ clear() +context: ƒ context() +count: ƒ count() +countReset: ƒ countReset() +createTask: ƒ createTask() +debug: ƒ debug() +dir: ƒ dir() +dirxml: ƒ dirxml() +error: ƒ error() +group: ƒ group() +groupCollapsed: ƒ groupCollapsed() +groupEnd: ƒ groupEnd() +info: ƒ info() +log: ƒ log() +memory: MemoryInfo {totalJSHeapSize: 48746582, usedJSHeapSize: 43721570, jsHeapSizeLimit: 4395630592} +profile: ƒ profile() +profileEnd: ƒ profileEnd() +table: ƒ table() +time: ƒ time() +timeEnd: ƒ timeEnd() +timeLog: ƒ timeLog() +timeStamp: ƒ timeStamp() +trace: ƒ trace() +warn: ƒ warn() +Symbol(Symbol.toStringTag): "console" +[[Prototype]]: Object <-- prints out the console object with all its properties Try also entering `typeof console` +'object' <-- data type of console Answer the following questions: What does `console` store? +The console object stores a series of functions that help with debugging code. What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? +The syntax console.log, called dot notation, is the simplest method to access the properties of an object. The "." identifies log as a property of console. Without it we would not be able to access the function, nor use it.