diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index ae4e19774..6a3119530 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -17,15 +17,21 @@ If your PR is rejected, check the task list. Self checklist -- [ ] I have committed my files one by one, on purpose, and for a reason -- [ ] I have titled my PR with COHORT_NAME | FIRST_NAME LAST_NAME | REPO_NAME | WEEK -- [ ] I have tested my changes -- [ ] My changes follow the [style guide](https://curriculum.codeyourfuture.io/guides/contributing/) -- [ ] My changes meet the [requirements](./README.md) of this task +- [x] I have committed my files one by one, on purpose, and for a reason +- [x] I have titled my PR with COHORT_NAME | FIRST_NAME LAST_NAME | REPO_NAME | WEEK +- [x] I have tested my changes +- [x] My changes follow the [style guide](https://curriculum.codeyourfuture.io/guides/contributing/) +- [x] My changes meet the [requirements](./README.md) of this task ## Changelist -Briefly explain your PR. +This Pull Request includes JavaScript exercises where I learned about identifying and fixing errors. + +I improved my skills in creating new branches, committing individual files, and committing all changes at once. I also prefer using command-line commands rather than buttons for these tasks. + +I used String.prototype.padStart() for the first time and gained a good understanding of its usefulness. + +To view changes instantly, I used nodemon with a command (while true; do nodemon $(ls *.js | fzf); done) for interactive, real-time feedback. ## Questions diff --git a/Sprint-1/errors/0.js b/Sprint-1/errors/0.js index cf6c5039f..db8fc82c8 100644 --- a/Sprint-1/errors/0.js +++ b/Sprint-1/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 +// 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? + +// To make a multi-line comment in JavaScript, you can start with /* and end with */ . Any text +// in between will be considered a comment and will not be executed as code by the computer. diff --git a/Sprint-1/errors/1.js b/Sprint-1/errors/1.js index 7a43cbea7..6aeb04a6f 100644 --- a/Sprint-1/errors/1.js +++ b/Sprint-1/errors/1.js @@ -1,4 +1,15 @@ // trying to create an age variable and then reassign the value by 1 -const age = 33; +// to run this file we need to go in the root and once we are in the file run, node 1.js eg => cd /Sprint-1/errors => ~ node 1.js + + +// this line is not working because const does not allow you change the data so we can change to let. +// cost age. = 33; +// age = age + 1; +// console.log(age); + + +let age = 33; age = age + 1; +console.log(age); + diff --git a/Sprint-1/errors/2.js b/Sprint-1/errors/2.js index e09b89831..82b9be40f 100644 --- a/Sprint-1/errors/2.js +++ b/Sprint-1/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}`); + +// we just need to move the console.log() to avoid render and expression which was calling the data declared in the variable +//ReferenceError: Cannot access 'cityOfBirth' before initialization \ No newline at end of file diff --git a/Sprint-1/errors/3.js b/Sprint-1/errors/3.js index ec101884d..940972a74 100644 --- a/Sprint-1/errors/3.js +++ b/Sprint-1/errors/3.js @@ -1,5 +1,3 @@ -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 +5,25 @@ 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 + + +// const cardNumber = 4533787178994213; +// const last4Digits = cardNumber.(-4); + +// console.log(last4Digits); + + + +// String.prototype.slice() +// The slice() method of String values extracts a section of this string and returns it as a new string, +// without modifying the original string. but in this example we have number we can extract this. +// 1 slice work only with String +// 2 we have to convert the variable to String +// 3 Option we can just added a single quotation but this variable is saving number. + + +const cardNumber = 4533787178994213; +const last4Digits = cardNumber.toString().slice(-4); + +console.log(last4Digits); +console.log(typeof(last4Digits)); \ No newline at end of file diff --git a/Sprint-1/errors/4.js b/Sprint-1/errors/4.js index 21dad8c5d..7610012b0 100644 --- a/Sprint-1/errors/4.js +++ b/Sprint-1/errors/4.js @@ -1,2 +1,12 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +// const 12HourClockTime = "20:53"; +// const 24hourClockTime = "08:53"; + +// this is given an error because we can no start an variable starting naming with number, So we can fix moving the number +// in the middle or we can write the number instead declare the integer number + +const hour12ClockTime = "8:53"; +console.log(hour12ClockTime); + + +const hour24ClockTime = "20:53"; +console.log(hour24ClockTime); \ No newline at end of file diff --git a/Sprint-1/exercises/count.js b/Sprint-1/exercises/count.js index 117bcb2b6..770461c97 100644 --- a/Sprint-1/exercises/count.js +++ b/Sprint-1/exercises/count.js @@ -1,6 +1,10 @@ +// 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 updates the value of count by taking its current value, adding 1 to it, +// and then using the assignment operator (=) to store the new value back into count. + 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 diff --git a/Sprint-1/exercises/decimal.js b/Sprint-1/exercises/decimal.js index cc5947ce2..99de61fce 100644 --- a/Sprint-1/exercises/decimal.js +++ b/Sprint-1/exercises/decimal.js @@ -3,7 +3,26 @@ 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 ) + + const wholeNumberPart = (Math.floor(num)); + + // Create a variable called decimalPart and assign to it an expression that evaluates to 0.5678 ( the decimal part of num ) + +// parseFloat() picks the longest substring starting from the beginning that generates a valid +// number literal. If it encounters an invalid character, it returns the number represented up +// to that point, ignoring the invalid character and all characters following it. +// If the argument's first character can't start a legal number literal per the syntax above, +// parseFloat returns NaN. + + const decimalPart = parseFloat((num - wholeNumberPart).toFixed(4)); + + // Create a variable called roundedNum and assign to it an expression that evaluates to 57 ( num rounded to the nearest whole number ) + + const roundedNum = (Math.round(num)); + // Log your variables to the console to check your answers +console.log(wholeNumberPart, decimalPart, roundedNum); + diff --git a/Sprint-1/exercises/initials.js b/Sprint-1/exercises/initials.js index 6b80cd137..66a498593 100644 --- a/Sprint-1/exercises/initials.js +++ b/Sprint-1/exercises/initials.js @@ -4,3 +4,12 @@ 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 acronym = `${firstName[0]}${middleName[0]}${lastName[0]}` +let initials = firstName[0] + middleName[0] + lastName[0]; + + +console.log(`this option with interpolation ${acronym}`); +console.log(`This string concatenation ${initials}`); diff --git a/Sprint-1/exercises/paths.js b/Sprint-1/exercises/paths.js index c91cd2ab3..fa4743bb8 100644 --- a/Sprint-1/exercises/paths.js +++ b/Sprint-1/exercises/paths.js @@ -9,10 +9,31 @@ // (All spaces in the "" line should be ignored. They are purely for formatting.) + +/* ================ lastIndexOf() =================== + + -we use this to obtain the last position of / where is located the File.txt + -const base = filePath.slice(lastSlashIndex + 1); with + 1 we start to subtract after / + Index: 0 1 2 ... 37 38 39 40 41 42 + filePath: / U s ... / f i l e .txt + - +*/ + const filePath = "/Users/mitch/cyf/Module-JS1/week-1/interpret/file.txt"; const lastSlashIndex = filePath.lastIndexOf("/"); +console.log(lastSlashIndex); // 44 const base = filePath.slice(lastSlashIndex + 1); -console.log(`The base part of ${filePath} is ${base}`); +console.log(base); // file.txt +// 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 lastDotIndex = filePath.lastIndexOf("."); +console.log(lastDotIndex); // index position 49 +const extractDir = filePath.slice(0, lastDotIndex); +console.log(`Directory and filename (without extension) is: ${extractDir}`); + + +// Create a variable to store the ext part of the variable" +const extensionName = filePath.slice(lastDotIndex + 1); +console.log(`extension: ${extensionName}`); // txt diff --git a/Sprint-1/exercises/random.js b/Sprint-1/exercises/random.js index 292f83aab..38723850c 100644 --- a/Sprint-1/exercises/random.js +++ b/Sprint-1/exercises/random.js @@ -2,8 +2,44 @@ const minimum = 1; 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 +// Try logging the value of num and running the program several times to build an idea of +// what the program is doing + +/* + Math.floor() Math.floor() rounds down the decimal result from the previous step to the + nearest integer. This step ensures the random number is a whole number. + have a random integer between 0 and 99, inclusive. + + Math.random() will take a number between 0 (inclusive) and 1 (no inclusive) eg. this + will be decimal numbers (0.345, 0,123) + + Math.random() * (maximum - minimum + 1): is multiplied by 100, creating a new range. + Now, Math.random() * 100 generates a random decimal number between 0 and 100 + (not including 100). Example 0.0, 25.4, 99.99, etc. + + (maximum - minimum + 1) This part calculates the range of numbers you want to include, + which is from 1 to 100. Subtracting minimum from maximum gives 99, and adding 1 results + in 100. So, this range means we’re looking to generate a random number between 0 and 99 + and then shift it to between 1 and 100. + + + minimum: + Adding minimum (which is 1 in this case) shifts the entire range up by 1. + Now, instead of getting a range of 0–99, the range becomes 1–100. + so, num will now be a random integer between 1 and 100. + +*/ + +// in this example taken from mdn we see the same function being called and will generate a +//random number between the minimum and maximum + +function getRandomArbitrary(min, max) { + return Math.floor(Math.random() * (max - min) + min); + } + +console.log(getRandomArbitrary(minimum, maximum)); \ No newline at end of file diff --git a/Sprint-1/explore/chrome.md b/Sprint-1/explore/chrome.md index e7dd5feaf..73d6d4236 100644 --- a/Sprint-1/explore/chrome.md +++ b/Sprint-1/explore/chrome.md @@ -10,9 +10,23 @@ Let's try an example. In the Chrome console, invoke the function `alert` with an input string of `"Hello world!"`; -What effect does calling the `alert` function have? +---------- alert("hello Maria"); +---------------Hello Maria + +What effect does calling the `alert` function have? show a window with the alert at the top of the browser 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`. +--------- prompt("What is your name?"); //maria +--------- var myName = prompt("What is your name?"); +------------- Maria + What effect does calling the `prompt` function have? -What is the return value of `prompt`? + + //prompt will display a dialog text box to interact wit the user, this can be used to ask question and then stored in one variable. this can have two option "ok" and "cancel", if cancel is pressed nothing will run. and this will be "undefine". + + +What is the return value of `prompt`? + + //If the user enters a name and clicks "OK," the input text is stored in the variable myName. + diff --git a/Sprint-1/explore/objects.md b/Sprint-1/explore/objects.md index 0216dee56..990ee9ad5 100644 --- a/Sprint-1/explore/objects.md +++ b/Sprint-1/explore/objects.md @@ -3,14 +3,35 @@ In this activity, we'll explore some additional concepts that you'll encounter in more depth later on in the course. Open the Chrome devtools Console, type in `console.log` and then hit enter - + What output do you get? + ---------------- ƒ log() { [native code] } + Now enter just `console` in the Console, what output do you get back? + --------------- console + console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …} + methods properties built-in Js devtools which can be useful for debugging and tracking the code -Try also entering `typeof console` + +Try also entering `typeof console` + ------------- 'object' Answer the following questions: What does `console` store? + ------------ Is an object Js which contains methos and properties for logging information, displaying errors, warnings, debugging in the browser. + What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + ------------ the dot notation between `console.log` or `console.assert` is the access to method(function) store within the console object. + + ---------- eg. With the . operator, we can access the properties in each object within the students array, allowing us to check or modify what’s stored in each object. + +let students = [ + { nombre: "Ana", age: 21 }, + { nombre: "Luis", age: 22 }, + { nombre: "Marta", age: 20 } +]; + +console.table(students); + diff --git a/Sprint-1/interpret/percentage-change.js b/Sprint-1/interpret/percentage-change.js index e24ecb8e1..c079a6738 100644 --- a/Sprint-1/interpret/percentage-change.js +++ b/Sprint-1/interpret/percentage-change.js @@ -2,21 +2,55 @@ 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 -// a) How many function calls are there in this file? Write down all the lines where a function call is made +/* + 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 + + -------- Number(carPrice.replaceAll(",", "")); this convert string in numbers + -------- replaceAll(",", "") this function is removing the "," and returning just the numbers + -------- console.log(`The percentage change is ${percentageChange}`); this is a function to print what we call inside. + + + + 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? + + ------- In the line 5 we were missing the "," dividing the ("," "") this gave an error. + + + c) Identify all the lines that are variable reassignment statements + + ------- carPrice = Number(carPrice.replaceAll(",", "")); + ------- priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); + + + 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; + + e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression? -// 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 expression Number(carPrice.replaceAll(",", "")) performs two actions: + * carPrice.replaceAll(",", ""): + The replaceAll() method is used on the string carPrice. It removes all commas "," from the + string by replacing them with an empty string "". -// c) Identify all the lines that are variable reassignment statements + * Number(...); + this function is then called on the result of replaceAll(), + converting the string now without commas into a numeric value eg 10,000 => 10000 -// 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? +*/ \ No newline at end of file diff --git a/Sprint-1/interpret/time-format.js b/Sprint-1/interpret/time-format.js index 83232e43a..a33f6a193 100644 --- a/Sprint-1/interpret/time-format.js +++ b/Sprint-1/interpret/time-format.js @@ -1,24 +1,65 @@ -const movieLength = 8784; // length of movie in seconds +const movieLength = 8784; // length of movie in seconds 8784 const remainingSeconds = movieLength % 60; +console.log(remainingSeconds); + const totalMinutes = (movieLength - remainingSeconds) / 60; +console.log(totalMinutes); const remainingMinutes = totalMinutes % 60; +console.log(remainingMinutes); + + const totalHours = (totalMinutes - remainingMinutes) / 60; const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; console.log(result); -// For the piece of code above, read the code and then answer the following questions +/* + 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? + + -------- 6 in total + -------- movieLength - declared as const + -------- remainingSeconds - declared as const + -------- totalMinutes - declared as const + -------- remainingMinutes - declared as const + -------- totalHours - declared as const + -------- result - declared as const + + + b) How many function calls are there? + + -------- 4 function calls: + -------- console.log(remainingSeconds); + -------- console.log(totalMinutes); + -------- console.log(remainingMinutes); + -------- console.log(result); + + c) Using documentation, explain what the expression movieLength % 60 represents + + -------- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder + -------- Remainder: + -------- WITH % we can obtain the remainder between the var movieLength % 60; and stored in remainingMinutes + + d) Interpret line 4, what does the expression assigned to totalMinutes mean? -// a) How many variable declarations are there in this program? + -------- This line subtracts remainingSeconds from movieLength to remove the leftover seconds. + Then, it converts the difference into minutes by dividing the result by 60. + This gives the total number of whole minutes in movieLength. -// b) How many function calls are there? + e) What do you think the variable result represents? Can you think of a better name for this variable? -// c) Using documentation, explain what the expression movieLength % 60 represents + ------- Result var represents the total runtime of the movie. While "result" is fine, + a name like "movieRunTime", "timeMovie" or "formattedTime" would be more descriptive and improve readability. -// d) Interpret line 4, what does the expression assigned to totalMinutes mean? + f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer -// e) What do you think the variable result represents? Can you think of a better name for this variable? + ------- This code works as expected for the most of positive values of movieLength. + However, if a negative value is provided for movieLength, the result will show negative values, + which might not make sense in the context of time. For example: + const movieLength = -4258; + result: -1:-10:-58 -// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer +*/ \ No newline at end of file diff --git a/Sprint-1/interpret/to-pounds.js b/Sprint-1/interpret/to-pounds.js index 60c9ace69..de482f1f6 100644 --- a/Sprint-1/interpret/to-pounds.js +++ b/Sprint-1/interpret/to-pounds.js @@ -6,6 +6,7 @@ const penceStringWithoutTrailingP = penceString.substring( ); const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + const pounds = paddedPenceNumberString.substring( 0, paddedPenceNumberString.length - 2 @@ -14,6 +15,7 @@ const pounds = paddedPenceNumberString.substring( const pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) .padEnd(2, "0"); + console.log(pence) console.log(`£${pounds}.${pence}`); @@ -23,5 +25,35 @@ console.log(`£${pounds}.${pence}`); // You need to do a step-by-step breakdown of each line in this program // 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" +/* + To begin, we can start with + 1. const penceString = "399p": initialize a string variable with the value "399p" + + 2. const penceStringWithoutTrailingP = penceString.substring(0,penceString.length - 1); + ----- This is removing the last character from the string and because is negative argument + we should provide the starter point and end index to override the character. + + 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + ----- The padStart function modifies the string by adding a specified character at the + beginning if the string is shorter than the desired length. In this case, + padStart(3, "0") checks if the string has fewer than 3 characters. If it does, + it adds "0" at the beginning until the string reaches a length of 3. eg. + const penceString = "9p"; => £0.09 + const penceString = "44p"; => £0.44 + const penceString = "0p"; => £0.00 + + 4. const pounds = paddedPenceNumberString.substring(0,paddedPenceNumberString.length - 2); + ----- Here we are using again subtracting function to extract the integer number removing + the decimals given the argument(0, string.length -2). this means return the string + starting from position 0 and removing the last two characters. + + 5. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0"); + ----- Extracting the decimal numbers and gets the last two characters of the string, which + represent the pence part. + + 6. console.log(`£${pounds}.${pence}`); + ----- This line displays the formatted currency value by using template literals to interpolate + the pounds and pence variables into a single string. The £ symbol is added at the beginning + to indicate currency. eg. + const penceString = "399p"; => £3.99 +*/