Skip to content

London | May 2025 | Houssam Lahlah | Coursework/sprint 1 #657

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Sprint-1/1-key-exercises/1-count.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ 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 is increases the value of count by 1 and saves the updated value back into count variable.
7 changes: 5 additions & 2 deletions Sprint-1/1-key-exercises/2-initials.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ 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 = ``;

// https://www.google.com/search?q=get+first+character+of+string+mdn
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
5 changes: 3 additions & 2 deletions Sprint-1/1-key-exercises/3-paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ 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 ext = base.slice(base.lastIndexOf(".") + 1);


// https://www.google.com/search?q=slice+mdn
75 changes: 71 additions & 4 deletions Sprint-1/1-key-exercises/4-random.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,74 @@ const maximum = 100;

const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

// 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
// 1- In this exercise, you will need to work out what num represents?

// the num gives a random whole number between 1 and 100 like 73, 12, or 100.

// 2- Try breaking down the expression and using documentation to explain what it means
/*
1. Math.random()
Returns a random decimal number between 0 and 1 but never gives 1.0.
Example: 0.24
2. (maximum - minimum + 1)
This gives number of possible values.
Without the +1, we'd only get the difference, not the full count.
for example:
5 - 1 = 4 → but there are actually 5 numbers: 1, 2, 3, 4, 5
So we add +1 to include both ends of the range.
3. Math.random() * (maximum - minimum + 1)
This gives a random decimal number between 0 and 100 (like 24, 65 ...)
Because we want the random decimal scaled to the size of the range of possible values.
For example, if we want a number between 1 and 100 (inclusive), there are 100 possible numbers (1, 2, ..., 100).
Multiplying by 100 means the decimal is scaled up to cover all those possibilities before rounding.
4. Math.floor(...)
This rounds the decimal down to the nearest whole number.
Example: Math.floor(78.43) → 78
5. + minimum
we add the minimum to shift the range correctly, and make sure the random number up to start from minimum.
5-1- for example if we remove the + minimum
5-1-1 Math.random() 0.9999 * 99 + 1 → only goes up to 99.999... → max = 99.999... → floor = 100 (but very unlikely)
now 100 becomes very hard to reach, and in many cases, you never get it.
5-1-2 Math.random() 0.00 * 99 + 1 → only goes up to 0... → max = 0... → floor = 0 (now the minimum is 0, and can appears)
conclusion : when we don’t add + minimum, there is a chance that 1 appears, but it’s not the guaranteed minimum anymore —
and the range starts at 0, not 1.
5-2- when we add +minimum
now we make sure the min and max can appear in the final results and make sure the minimum is 1 not 0.
Minimum appears when random = 0
Maximum appears when random is almost 1 (like 0.9999...).
example : Math.random() * 99 + 1 → up to 0.99 → max = 99 → floor = 99 → +1 = 100 (so more possibilities for 100 to appears)
*/

//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
16 changes: 15 additions & 1 deletion Sprint-1/2-mandatory-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,16 @@
// we can turn the lines into comments. we can use:

// for single-line comments, or

/* for multi-line comments. */

/*

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?
We don't want the computer to run these 2 lines - how can we solve this problem?

*/

// we can use comments to make sure the computer ignores the lines, comment them out using :

// // single line or /* multi-line */.
7 changes: 4 additions & 3 deletions Sprint-1/2-mandatory-errors/1.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// trying to create an age variable and then reassign the value by 1
// Trying to create an age variable and then reassign the value by 1

const age = 33;
age = age + 1;
let age = 33; // Declare a variable called age and assign it the value 33
age = age + 1; // Reassign age to be its current value plus 1
console.log(age); // Output: 34
6 changes: 4 additions & 2 deletions Sprint-1/2-mandatory-errors/2.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Currently trying to print the string "I was born in Bolton" but it isn't working...
// what's the error ?
// what's the error ? The error here is due to using a variable before it's declared.

console.log(`I was born in ${cityOfBirth}`);

// Fixed: Declare the variable before using it
const cityOfBirth = "Bolton";
console.log(`I was born in ${cityOfBirth}`);
29 changes: 21 additions & 8 deletions Sprint-1/2-mandatory-errors/3.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
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
// Before running the code, make and explain a prediction about why the code won't work
// 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

// We want last4Digits to store the last 4 digits of cardNumber

// Prediction before running:
// This will cause an error because cardNumber is a number,
// and numbers don't have the slice() method. slice() works only on strings or arrays.

// Running the code would give:
// TypeError: cardNumber.slice is not a function

// Why?
// Because slice() is not defined for numbers in JavaScript.

// Fix:
// Convert cardNumber to a string first, so we can use slice() on it.
// Then slice the last 4 characters to get the last 4 digits.

const last4Digits = String(cardNumber).slice(-4);

console.log(last4Digits); // Output: 4213

16 changes: 14 additions & 2 deletions Sprint-1/2-mandatory-errors/4.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,14 @@
const 12HourClockTime = "20:53";
const 24hourClockTime = "08:53";
// Original variable names are invalid because variable names cannot start with a number
// const 12HourClockTime = "20:53"; // This will cause a syntax error
// const 24hourClockTime = "08:53"; // Also invalid for the same reason

// Fix:
// Variable names must start with a letter, underscore (_), or dollar sign ($).
// So we rename the variables to valid names below:

const hour12ClockTime = "20:53"; // Valid variable name for 12-hour clock time
const hour24ClockTime = "08:53"; // Valid variable name for 24-hour clock time

// Explanation:
// Variable names cannot begin with a number in JavaScript,
// so prefixing them with a letter or underscore solves the problem.
29 changes: 29 additions & 0 deletions Sprint-1/3-mandatory-interpret/1-percentage-change.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,41 @@ console.log(`The percentage change is ${percentageChange}`);

// Read the code and then answer the questions below

// --- Answers to the questions ---

// a) How many function calls are there in this file? Write down all the lines where a function call is made

// Function calls:
// - Line 4: carPrice.replaceAll(",", "")
// - Line 4: Number(...)
// - Line 5: priceAfterOneYear.replaceAll("," "") --> syntax error here
// - Line 5: Number(...)
// - Line 10: console.log(...)

// 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?

// Error at line 5: SyntaxError due to missing comma in replaceAll arguments
// Fix: add the missing comma inside replaceAll:
// priceAfterOneYear.replaceAll(",", "")

// c) Identify all the lines that are variable reassignment statements

// Reassignments:
// - Line 4: carPrice = Number(...)
// - Line 5: priceAfterOneYear = Number(...)

// d) Identify all the lines that are variable declarations

// Declarations:
// - Line 1: let carPrice = "10,000";
// - Line 2: let priceAfterOneYear = "8,543";
// - Line 7: const priceDifference = ...
// - Line 10: const percentageChange = ...

// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?

// Explanation:
// - carPrice.replaceAll(",","") removes all commas from the string "10,000", turning it into "10000".
// - Number(...) converts the resulting string "10000" into the numeric value 10000.
// This allows mathematical operations on carPrice, which is originally a formatted string.

23 changes: 21 additions & 2 deletions Sprint-1/3-mandatory-interpret/2-time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,36 @@ 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
// --- Answers to the questions ---

// a) How many variable declarations are there in this program?
// There are 6 variable declarations:
// movieLength, remainingSeconds, totalMinutes, remainingMinutes, totalHours, and result

// b) How many function calls are there?
// There is 1 function call:
// 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
// The `%` operator is the modulo operator, which returns the remainder after division.
// So movieLength % 60 gives the remainder when movieLength is divided by 60.
// This means it calculates the leftover seconds after counting full minutes.

// d) Interpret line 4, what does the expression assigned to totalMinutes mean?
// Line 4: (movieLength - remainingSeconds) / 60
// This subtracts the leftover seconds from the total seconds,
// giving a multiple of 60 seconds (full minutes),
// then divides by 60 to convert seconds to total minutes.

// e) What do you think the variable result represents? Can you think of a better name for this variable?
// result holds the formatted string showing the movie length in "hours:minutes:seconds" format.
// A better name might be `formattedTime` or `movieDurationFormatted`.

// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer
// For positive integers, the code works correctly.
// For zero, it returns "0:0:0", which is fine.
// For negative numbers, the calculation may produce unexpected negative values.
// For very large values, it still works fine.
// The code assumes movieLength is an integer number of seconds.
// If movieLength is a non-integer or not a number, the code might not behave as expected.

22 changes: 13 additions & 9 deletions Sprint-1/3-mandatory-interpret/3-to-pounds.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
const penceString = "399p";
// 1. Initializes a string variable with the value "399p" representing the price in pence with a trailing 'p'.

const penceStringWithoutTrailingP = penceString.substring(
0,
penceString.length - 1
);
// 2. Removes the trailing 'p' by taking a substring from index 0 up to (but not including) the last character.
// Result: "399"

const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
// 3. Ensures the string is at least 3 characters long by padding with leading zeros if needed.
// In this case, "399" is already 3 characters, so it remains "399".

const pounds = paddedPenceNumberString.substring(
0,
paddedPenceNumberString.length - 2
);
// 4. Extracts the pounds part by taking all characters except the last two.
// For "399", this is "3" (the hundreds place).

const pence = paddedPenceNumberString
.substring(paddedPenceNumberString.length - 2)
.padEnd(2, "0");
// 5. Extracts the last two characters as the pence part.
// For "399", this is "99".
// Then pads the string on the right with zeros if it’s shorter than 2 characters (not needed here).
Comment on lines +25 to +27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When you mentioned "not needed here", do you mean we can delete .padEnd(2, "0") at line 24?
Could we expect this program to work as intended for any valid penceString if we deleted .padEnd(2, "0") from the code?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

heloo,
Yes, I meant that .padEnd(2, "0") isn’t needed in this case. If we remove it, the program should still work correctly for any valid penceString, as long as it’s properly formatted.
Thanks for checking!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you know why it is safe to delete .padEnd(2, "0") from this script?


console.log(${pounds}.${pence}`);

// This program takes a string representing a price in pence
// The program then builds up a string representing the price in pounds

// 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"
// 6. Prints the formatted price string with a £ sign, pounds, and pence separated by a dot.
// Output: "£3.99"
22 changes: 18 additions & 4 deletions Sprint-1/4-stretch-explore/chrome.md
Original file line number Diff line number Diff line change
Expand Up @@ -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?
1. What effect does calling the `alert` function have?

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`.
It opens a popup message box in the browser with the text:
You must click "OK" to dismiss it before you can do anything else on the page.

What effect does calling the `prompt` function have?
What is the return value of `prompt`?
2. 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`.

3. What effect does calling the `prompt` function have?

It opens a popup input box asking:
What is your name?
and I can enter a response, then click "OK" or "Cancel".

4. What is the return value of `prompt`? Return value:

If I enter a name (e.g., "Sami") and press OK, it returns the string: "Sami"

If I press Cancel, it returns: null
Loading