diff --git a/.gitignore b/.gitignore deleted file mode 100644 index bde36e530..000000000 --- a/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules -.DS_Store -.vscode -**/.DS_Store \ No newline at end of file diff --git a/Sprint-1/1-key-exercises/1-count.js b/Sprint-1/1-key-exercises/1-count.js index 117bcb2b6..9ad5bb24c 100644 --- a/Sprint-1/1-key-exercises/1-count.js +++ b/Sprint-1/1-key-exercises/1-count.js @@ -4,3 +4,11 @@ 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: the variable count in right end side increment by 1 and assign the result to left end side which hold the + * incremention + */ + +console.log('Value of count variable after incremented by 1: ', count) + diff --git a/Sprint-1/1-key-exercises/2-initials.js b/Sprint-1/1-key-exercises/2-initials.js index 47561f617..5a7c183c5 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.charAt(0)}${middleName.charAt(0)}${lastName.charAt(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..a70aa4f11 100644 --- a/Sprint-1/1-key-exercises/3-paths.js +++ b/Sprint-1/1-key-exercises/3-paths.js @@ -15,9 +15,14 @@ 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 +const dir = filePath.slice(0, lastSlashIndex); + // Create a variable to store the ext part of the variable +const lastDotIndex = filePath.lastIndexOf("."); +const ext = filePath.slice(lastDotIndex); + +console.log(`The dir part of ${filePath} is ${dir}`); +console.log(`The ext part of ${filePath} is ${ext}`); -const dir = ; -const ext = ; -// 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..c75b477cf 100644 --- a/Sprint-1/1-key-exercises/4-random.js +++ b/Sprint-1/1-key-exercises/4-random.js @@ -3,7 +3,45 @@ 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 + +/** + * Step 1: Math.random() + + * This generates a random decimal number between 0 (inclusive) and 1 (exclusive). + * Example: 0.3728, 0.9134, etc. + + * Step 2: (maximum - minimum + 1) + + * This calculates the range of possible numbers you want. + * Here: 100 - 1 + 1 = 100 + * So, we’re creating a range that includes both 1 and 100. + + * Step 3: Math.random() * (maximum - minimum + 1) + + * This augment the random decimal to fit the range. + * Example: If Math.random() it returns 0.3728, + * 0.3728 * 100 = 37.28 + + * Step 4: Math.floor(...) + + * Math.floor() rounds down to the nearest whole number. + * So 37.28 becomes 37. + + * Step 5: + minimum + + * Because the range started from 0, we add minimum (which is 1) to adjust to the correct range. + + * Example: 37 + 1 = 38. + + * So what does num represent? + * num is a random integer between 1 (inclusive) and 100 (exclusive). + * Every time the program runs, we get a different number in that range. + +*/ + diff --git a/Sprint-1/2-mandatory-errors/0.js b/Sprint-1/2-mandatory-errors/0.js index cf6c5039f..82e6e4189 100644 --- a/Sprint-1/2-mandatory-errors/0.js +++ b/Sprint-1/2-mandatory-errors/0.js @@ -1,2 +1,25 @@ -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? + +/** The lines that are just instructions or notes for humans and we don’t want the computer to execute them, we turn them into comments. + +In JavaScript, there are two ways to write comments: + +1. Single-line comment + +Use // at the start of a line. +Everything after // is ignored by the computer. + +Example: + +// This line explains what the code does +const num = 8; + +2. Multi-line comment + +Use slash asterisk at beginning and asterisk slash at end to wrap several lines. + +Example: +The comment wrapping this explanation +*/ + diff --git a/Sprint-1/2-mandatory-errors/1.js b/Sprint-1/2-mandatory-errors/1.js index 7a43cbea7..a3b598294 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; -age = age + 1; +// change keyword 'const' to 'let' +let age = 33; +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..7bd31e89d 100644 --- a/Sprint-1/2-mandatory-errors/2.js +++ b/Sprint-1/2-mandatory-errors/2.js @@ -1,5 +1,10 @@ // 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}`); +// This is related to variable hoisting. +// const keywork is a block scope and unlike var it's not hoisted automatically. +// The easiest solution is to declare the variable before to use it + 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..d1b0b9f67 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 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 +7,22 @@ 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 + +/** + *Prediction: Why won’t this code work? +const cardNumber = 4533787178994213; +const last4Digits = cardNumber.slice(-4); + +The issue is that .slice() is a string method, but cardNumber here is a number — not a string. +So when the code runs, JavaScript will say something like: +TypeError: cardNumber.slice is not a function +That’s because .slice() function only works on strings or arrays — and numbers don’t have that method. + +Fixing the problem: +To use .slice(), we need to convert the number into a string first: +*/ + +const cardNumber = 4533787178994213; +const last4Digits = cardNumber.toString().slice(-4); +console.log(last4Digits); // "4213" + diff --git a/Sprint-1/2-mandatory-errors/4.js b/Sprint-1/2-mandatory-errors/4.js index 21dad8c5d..1a5e5b596 100644 --- a/Sprint-1/2-mandatory-errors/4.js +++ b/Sprint-1/2-mandatory-errors/4.js @@ -1,2 +1,18 @@ -const 12HourClockTime = "20:53"; -const 24hourClockTime = "08:53"; \ No newline at end of file +// const 12HourClockTime = "20:53"; +// const 24hourClockTime = "08:53"; + +/** + * In javascript variable can't start with a number + * Can contain letters, digits (but not at the start), underscore _, and dollar signs $ + * + * const 12HourClockTime = "20:53"; will cause a SyntaxError because variable name can't begin with a number. + * + * To fix it need to chang the name to start with a letter. + */ + +const twelveHourClockTime = "08:53"; +const twentyFourClockTime = "20:53"; + +console.log(twelveHourClockTime); +console.log(twentyFourClockTime); + diff --git a/Sprint-1/3-mandatory-interpret/1-percentage-change.js b/Sprint-1/3-mandatory-interpret/1-percentage-change.js index e24ecb8e1..1b01ce7a2 100644 --- a/Sprint-1/3-mandatory-interpret/1-percentage-change.js +++ b/Sprint-1/3-mandatory-interpret/1-percentage-change.js @@ -2,21 +2,52 @@ 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}`); +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 +// Function calls and their line numbers +// line 3 - carPrice.replaceAll(",", "") - Callls replaceAll() on the string to remove commas +// line 3 - Number(...) - Converts the resulting string to a number +// line 4 - priceAfterOneYear.replaceAll("," "") - Syntax error here - Intendend to replaceAll() but missing a comma between arguments +// line 8 - console.log(...) - Prints to console +// // Total intended function calls: 5 + // 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? +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," "")); +// Error: SyntaxError: missiong ) after argument list +// Reason: +// There's a missing comma between the arguments of replaceAll. +// The correct syntax should be: +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); + // c) Identify all the lines that are variable reassignment statements +// These are the lines where variables that were already declared are assigned a new value: +// carPrice = Number(carPrice.replaceAll(",", ""); +// priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", "")); +// Reassignments: Lines 3 and 4 + // 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? +// These are the lines that are variables 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? + +// carPrice.replaceAll(",", "") - removes all commas from the string "10,000", then it becomes "10000" +// Number("10000") - Converts the string "10000" into a numeric value 10000. +// Purpose: To convert a formatted currency expression (with commas) into a number that is appropriate for mathematical calculations. +// + diff --git a/Sprint-1/3-mandatory-interpret/2-time-format.js b/Sprint-1/3-mandatory-interpret/2-time-format.js index 47d239558..4069d493b 100644 --- a/Sprint-1/3-mandatory-interpret/2-time-format.js +++ b/Sprint-1/3-mandatory-interpret/2-time-format.js @@ -12,14 +12,66 @@ 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? +// Each const introduces a new variable. +// +// movieLength +// remainingSeconds +// totalMinutes +// remainingMinutes +// totalHours +// result +// Total variable declarations: 6 // b) How many function calls are there? +// The only function call is: + +// Total function call is 1 +// console.log(result); + // c) Using documentation, explain what the expression movieLength % 60 represents // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators +// According to the MDN documentation on the remainder (%) operator +// The variable remainingSeconds stores the remainder left over when one movieLength operand is divided by 60 + +// Interpretation: +// It gives the remaining seconds that don’t make up a full minute. + // d) Interpret line 4, what does the expression assigned to totalMinutes mean? +// const totalMinutes = (movieLength - remainingSeconds) / 60; +// It subtracts the leftover seconds (that couldn’t form a full minute). +// Then divides the remaining seconds by 60. +// In doing so it converts the total movie length into minutes, ignoring any incomplete minute giving the total number of full minutes in the movie. + // e) What do you think the variable result represents? Can you think of a better name for this variable? +// const result = `${totalHours}:${remainingMinutes}:${remainingSeconds}`; + +// This combines hours, minutes, and seconds into a single string formatted like H:M:S. +// Example output: "2:26:24" +// +// Better variable names: +// actualTime +// timeAsUsual +// timeExpected + // f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer + +// It will work correctly for most positive integers, since it’s just converting seconds into hours, minutes, and seconds using division and remainders. +// However, there are some edge cases: +// If movieLength = 0: +// Output: 0:0:0 Works fine. +// If movieLength < 60 (less than a minute): +// Works fine (e.g., 45 → 0:0:45). +// If movieLength is not an integer (e.g., 87.5): +// Still works, but decimals might appear in remainingSeconds. +// If movieLength is negative: +// The time format breaks giving negative time components. + +// Formatting issue: +// The output isn’t padded. +// Example: 2 hours, 5 minutes, 9 seconds → "2:5:9" instead of "02:05:09". +// (Can fix that using function .padStart(2, '0') on each component.) +// diff --git a/Sprint-1/3-mandatory-interpret/3-to-pounds.js b/Sprint-1/3-mandatory-interpret/3-to-pounds.js index 60c9ace69..45e636f81 100644 --- a/Sprint-1/3-mandatory-interpret/3-to-pounds.js +++ b/Sprint-1/3-mandatory-interpret/3-to-pounds.js @@ -1,17 +1,17 @@ -const penceString = "399p"; +let penceString = "399p"; -const penceStringWithoutTrailingP = penceString.substring( +let penceStringWithoutTrailingP = penceString.substring( 0, penceString.length - 1 ); -const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); -const pounds = paddedPenceNumberString.substring( +let paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); +let pounds = paddedPenceNumberString.substring( 0, paddedPenceNumberString.length - 2 ); -const pence = paddedPenceNumberString +let pence = paddedPenceNumberString .substring(paddedPenceNumberString.length - 2) .padEnd(2, "0"); @@ -23,5 +23,50 @@ 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 start with +// const penceString = "399p"; +// +// Initialises a string variable with the value "399p". +// penceString variable now store the value: "399p" + +// const penceStringWithoutTrailingP = penceString.substring( +// 0, +// penceString.length - 1 +// ); + + +// What it does: takes a substring of penceString from index 0 up to (but not including) penceString.length - 1. +// And removes the last character (the trailing "p") so we are left with just the numeric part. + +// const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); + +// What it does: ensures the numeric string has at least 3 characters by adding leading "0" characters. +// The subsequent logic expects at least three digits so we can safely slice off "pounds" (all except the last two digits) and "pence" (last two digits). After that padding can handles small values like "5p" while maintaing correct indexing. +// Result stored: paddedPenceNumberString === "399" + +// const pounds = paddedPenceNumberString.substring( +// 0, +// paddedPenceNumberString.length - 2 +// ); + +// What it does: takes the substring from index 0 up to (but not including) the last two characters. Those leading characters represent whole pounds. +// Note: Because of padStart(3, "0"), this always returns at least one character (for values < 100 it returns "0" or more). + +// const pence = paddedPenceNumberString +// .substring(paddedPenceNumberString.length - 2) +// .padEnd(2, "0"); + +// What it does (first part): .substring(length - 2) returns the final two characters (the pence digits). +// What it does (second part): .padEnd(2, "0") ensures the result has at least two characters by adding trailing zeros if needed. +// Example: "399".substring(1) → "99". .padEnd(2,"0") → still "99". So pence === "99". + +// console.log(`£${pounds}.${pence}`); + +// What it does: prints a formatted pounds-and-pence string and symbol to the console, using template interpolation. +// Why: final result showing what user would expect the representation of the price. +// Example output: £3.99 + +let numericPence = parseInt(penceString.replace(/\D/g, ""), 10); +pounds = Math.floor(numericPence / 100); +pence = String(numericPence % 100).padStart(2, "0"); + diff --git a/Sprint-1/4-stretch-explore/chrome.md b/Sprint-1/4-stretch-explore/chrome.md index e7dd5feaf..c360c6d4e 100644 --- a/Sprint-1/4-stretch-explore/chrome.md +++ b/Sprint-1/4-stretch-explore/chrome.md @@ -16,3 +16,26 @@ 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`? + +Answers: + +1. The alert() function + +console.alert("Hello world!"); + +When calling the function alert("Hello world!") in the Chrome Console. +A window popup the the message displaying "Hello world!" on the screen. +That windows has an “OK” button that needs to click before continuing. + +2. The prompt() function + +let myName = prompt("What is your name?"); + +When calling that function the window display a message "What is your name?" and after the user input a response the value is stored in the variable "myName". + +That window dialog has two buttons: “OK” and “Cancel”. +The user can type something like "Carlos" and click “OK” or “Cancel”. +If the user types something like "Carlos" and clicks OK the prompt function returns the string "Carlos". + +The purpose of prompt() is to get text input from the user through a window dialog. + diff --git a/Sprint-1/4-stretch-explore/objects.md b/Sprint-1/4-stretch-explore/objects.md index 0216dee56..73cc2f928 100644 --- a/Sprint-1/4-stretch-explore/objects.md +++ b/Sprint-1/4-stretch-explore/objects.md @@ -14,3 +14,60 @@ Answer the following questions: What does `console` store? What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean? + +1. Answer (What does `console` store)? + +What is seen in Chrome’s Console is: + +ƒ log() { [native code] } + +This shows that console.log is a function, specifically a built-in function into the browser (that’s what “native code” means) + +2. Answer Step 2 (What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean?) + +Console {memory: MemoryInfo, debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, ...} + +This shows that console function is a built-in JavaScript object. +As it's expect because in Javascript, function is an object type. + +It contains many methods (functions) such as: + +log() → prints messages + +error() → prints error messages (in red) + +warn() → prints warnings (in yellow) + +assert(), table(), clear(), etc. + +We can think of console as a tool for for logging and debugging. + +3. typeof console + +"object" + +This confirms that console is an object in JavaScript. + +Going back to the question asked "What does console store?" + +It can be said console function stores an object that provides access to a collection of built-in methods and property used to displaying information to the browser’s developer console. + +4. What does the syntax console.log or console.assert mean? + +console.log means: + +Access the property named "log" that is part of the object named console. + +console.assert means: + +Access the property named "assert" inside the same object. + +5. What does the . (dot) mean? + +The dot (.) is the method or property access operator in JavaScript. + +It’s used to access a property or method that belongs to a said object. + +console.log // accesses the log property in the console object +Math.PI // accesses the value of PI (3,1415...) in the Math object +