Skip to content
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 updating the value of the count variable the original value + 1.
8 changes: 2 additions & 6 deletions Sprint-1/1-key-exercises/2-initials.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ let firstName = "Creola";
let middleName = "Katherine";
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[0] + middleName[0] + lastName[0];

Choose a reason for hiding this comment

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

this simple solution works, so well done! however, there might be a better way to do this. think about if you ever had a lot more name variables and you had to provide a solution that automatically populates the initials.


console.log(initials);
17 changes: 9 additions & 8 deletions Sprint-1/1-key-exercises/3-paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@
// (All spaces in the "" line should be ignored. They are purely for formatting.)

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 = ;
// +1 to not include the slash in the base
// lastSlashIndex finds position of the last / in the string
// slice extracts part of the string from that position to the end
const dir = filePath.slice(0, lastSlashIndex);

// https://www.google.com/search?q=slice+mdn
const dotIndex = base.lastIndexOf(".");
const ext = base.slice(dotIndex);
// dotIndex finds position of the last . in the base string and slice extracts after this
console.log(`The base part of the file path is ${base}, the dir part is ${dir}, and the ext part is ${ext}`);

Choose a reason for hiding this comment

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

solid solution. shows that you understand the slice() method and how to use it on strings.

5 changes: 5 additions & 0 deletions Sprint-1/1-key-exercises/4-random.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ const minimum = 1;
const maximum = 100;

const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
// num is an integer between minimum and maximum, between 1 and 100 inclusive
// math.random() produces a decimal between 0 (inclusive) and 1 (exclusive)
// math.floor() rounds down to the nearest integer
// (maximum - minimum + 1)) + minimum chooses a number between minimum and maximum and adds 1 so its inclusive of maximum

Choose a reason for hiding this comment

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

good explainer.

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
Expand Down
4 changes: 2 additions & 2 deletions Sprint-1/2-mandatory-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
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?
// 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?
6 changes: 6 additions & 0 deletions Sprint-1/2-mandatory-errors/1.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,9 @@

const age = 33;
age = age + 1;
// This will cause an error because age is a constant and cannot be reassigned
console.log("I am " + age + " years old");
// To fix the error, we can change const to let, which allows reassignment
let age = 33;
age = age + 1;
console.log("I am " + age + " years old");
7 changes: 6 additions & 1 deletion Sprint-1/2-mandatory-errors/2.js
Original file line number Diff line number Diff line change
@@ -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}`);
const cityOfBirth = "Bolton";
console.log(`I was born in ${cityOfBirth}`);

// The error is that cityOfBirth is used before it is declared.
// In JavaScript, variables declared with const or let cannot be accessed before their declaration due to the temporal dead zone.
// To fix the error, we need to declare and initialize cityOfBirth before using it in the console.log statement.

7 changes: 5 additions & 2 deletions Sprint-1/2-mandatory-errors/3.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
const cardNumber = 4533787178994213;
const last4Digits = cardNumber.slice(-4);

const last4Digits = cardNumber.toString().slice(-4);
console.log(last4Digits);
// 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

// slice is a method that works on strings, not numbers.
// To fix the error, we can convert cardNumber to a string using the toString() method before calling slice.

Choose a reason for hiding this comment

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

good catch. but if the variable is given as a number and you have converted toString(), you should make a conversion back, so you can return a number. when you begin to work with strongly-typed languages, cardNumber may not be of type string. this is where you must return the original variable type unless otherwise stated.

7 changes: 5 additions & 2 deletions Sprint-1/2-mandatory-errors/4.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
const 12HourClockTime = "20:53";
const 24hourClockTime = "08:53";
const ClockTime12Hour = "08:53";
const ClockTime24Hour = "20:53";
// Variables cannot start with a number
// Can only contain letters, numbers, underscores and $
// Variables wre written wrong way around
17 changes: 16 additions & 1 deletion Sprint-1/3-mandatory-interpret/1-percentage-change.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -12,11 +12,26 @@ 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 5 function calls in this file: lines 3, 4 and 7
// Line 4: carPrice,replaceAll(",", "") removes all commas from string
// Line 4: Number(...) converts string into number
// Line 5: priceAfterOneYear.replaceAll("," "") removes all commas from string
// Line 5: Number(...) converts string to number
// Line 10: console.log(`The percentage change is ${percentageChange}`) prints percentage change to output

// 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?
// Line 5 is missing a comma in the replaceAll function call. This is causing a syntax error because the function expects two arguments, but only one is provided.

Choose a reason for hiding this comment

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

good catch.


// c) Identify all the lines that are variable reassignment statements
// Variable reassignment means giving an existing variable a new value.
// Lines 4 and 5 reassign new values to carPrice and priceAfterOneYear respectively.

// d) Identify all the lines that are variable declarations
// Variable declaration means creating a new variable and assigning it a value for the first time.
// Line 1 declares carPrice with let
// Line 2 declares priceAfterOneYear with let
// Line 7 declares priceDifference with const
// Line 8 declares percentageChange with const

// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?
// It converts the string value of carPrice into a number value and removes the comma.
15 changes: 15 additions & 0 deletions Sprint-1/3-mandatory-interpret/2-time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,29 @@ 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?
// There are 6 variable declarations in this program on lines 1, 3, 4, 6, 7, 9.

// b) How many function calls are there?
// 1: console.log() on line 10.

// c) Using documentation, explain what the expression movieLength % 60 represents
// The remainder (%) operator returns the remainder left over when one operand (dividend) is divided by a second operand (divisor).
// It always takes the sign (+/-) of the dividend (the first number).
// So the movie length in seconds is divided by 60 (the number of seconds in a minute).
// The remainder is the number of seconds left over after all the full minutes have been accounted for.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

// d) Interpret line 4, what does the expression assigned to totalMinutes mean?
// It subtracts the remaining seconds from total movie length to get the total length in seconds that can be evenly divided by 60.
// Then divides by 60 to convert the length from seconds to minutes.
// So totalMinutes represents the total number of full 60-second minutes in the movie.

// e) What do you think the variable result represents? Can you think of a better name for this variable?
// The variable result represents the total length of the movie in hours, minutes and seconds.
// A better name for this variable could be movieDuration or movieFormattedLength.

Choose a reason for hiding this comment

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

movieDuration makes for better reading. ideally, we always want to keep our variable names as clear as possible so the meaning can be inferred at first glance.

having said that, movieFormattedLength also works because it piggybacks off the initial movieLength declaration. however, movieFormattedLengthToMinutes might be better, since we can easily tell what it's been formatted to.


// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer
// The code will work for all positive integer values of movieLength formatting to H:MM:SS
// It will also work for 0, returning 0:0:0
// It will incorrectly format negative numbers and very small number like < 60 seconds.
// Single digit minutes and seconds will not be zero-padded to two digits e.g. String(remainingMinutes).padStart(2, "0")
27 changes: 24 additions & 3 deletions Sprint-1/3-mandatory-interpret/3-to-pounds.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
const penceString = "399p";
// Declares constant variable named penceString and assigns the string 399p
// This indicates price in pence

const penceStringWithoutTrailingP = penceString.substring(
0,
penceString.length - 1
);
// Constant variable is declared to remove the trailing p in 399p to just keep the numeric part
// penceString.length is number of characters in 399p = 4 so -1 is 3
// substring(0, 3) returns the characters from index 0 up to index 3 exclusive, returning 399.

const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
// padStart ensures that the string has at least 3 characters by adding leading zeros if necessary
// This standardises the numeric string to simplify splitting into pounds and pence.
// In this case, 399 already has 3 characters, so no padding is added.

const pounds = paddedPenceNumberString.substring(
0,
paddedPenceNumberString.length - 2
);
// The last two characters represent pence
// Const pounds is declared as a variable consisting of a substring of previously declared variable and a newly calculated variable
// paddedPenceNumberString.length computes index where last two characters start, so that is after 1 character.
// substring(0, 1) extracts the pounds part, by returning the characters from index 0 up to index 1 exclusive.
// This is "3" in this case.

const pence = paddedPenceNumberString
.substring(paddedPenceNumberString.length - 2)
.padEnd(2, "0");
const pence = paddedPenceNumberString
// New variable to ensure two-digit pence component is formatted correctly.
.substring(paddedPenceNumberString.length - 2)
// returns substring from index to the end inclusive
// For 399, start index is character 1 (the first 9) so this returns 99.
.padEnd(2, "0");
// Ensures pence string has at least 2 characters by adding trailing zeros if needed
// So 5p would become 005 and this would return 05.

Choose a reason for hiding this comment

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

excellent explanation.


console.log(${pounds}.${pence}`);
// Template string that joins pounds and pence parts with a decimal point and logs it
// This displays the standard and prints it to the console.

// This program takes a string representing a price in pence
// The program then builds up a string representing the price in pounds
Expand Down
11 changes: 10 additions & 1 deletion Sprint-1/4-stretch-explore/objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@ 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?
What output do you get?
ƒ log() { [native code] }

Now enter just `console` in the Console, what output do you get back?
console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …}

Try also entering `typeof console`
Object

Answer the following questions:

What does `console` store?
Console is an object storing a collection of functions for logging, debugging and inspecting code.

What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean?
The dot is the property access operator in JavaScript
Console.log means : get the log property from the console object
log is a function so can be called using parentheses
console.assert can test for assumptions in the code, if the condition is true nothing happens but if its false it prints an error message.
12 changes: 12 additions & 0 deletions Sprint-2/1-key-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Predict and explain first...
// =============> write your prediction here
// The variable str is being declared twice within the same scope, which will cause a syntax error.

// call the function capitalise with a string input
// interpret the error message and figure out why an error is occurring
Expand All @@ -8,6 +9,17 @@ function capitalise(str) {
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
}
const result = capitalise('hello');
console.log(result);
// SyntaxError: Identifier 'str' has already been declared

// =============> write your explanation here
// // The first declaration is in the function parameter and the second one is inside the function body.
// In JavaScript, you cannot declare the same variable name in the same scope using let or const.
// To fix this, we can either rename the inner variable or assign the capitalised value to the parameter itself without redeclaring it.

// =============> write your new code here
function capitalise(str) {
str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
}