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
21 changes: 11 additions & 10 deletions Sprint-2/1-key-exercises/2-initials.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
const firstName = "Creola";
const middleName = "Katherine";
const 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.

const initials = ``;

// https://www.google.com/search?q=get+first+character+of+string+mdn
const firstName = "Creola";
const middleName = "Katherine";
const 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.

const 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
47 changes: 25 additions & 22 deletions Sprint-2/1-key-exercises/3-paths.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
// The diagram below shows the different names for parts of a file path on a Unix operating system

// ┌─────────────────────┬────────────┐
// │ dir │ base │
// ├──────┬ ├──────┬─────┤
// │ root │ │ name │ ext │
// " / home/user/dir / file .txt "
// └──────┴──────────────┴──────┴─────┘

// (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 = ;

// The diagram below shows the different names for parts of a file path on a Unix operating system

// ┌─────────────────────┬────────────┐
// │ dir │ base │
// ├──────┬ ├──────┬─────┤
// │ root │ │ name │ ext │
// " / home/user/dir / file .txt "
// └──────┴──────────────┴──────┴─────┘

// (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 = filePath.slice(0,lastSlashIndex);
const ext = filePath.slice(filePath.lastIndexOf("."));

console.log(dir);
console.log(ext);

// https://www.google.com/search?q=slice+mdn
28 changes: 19 additions & 9 deletions Sprint-2/1-key-exercises/4-random.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
const minimum = 1;
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
const minimum = 1;
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

// num represents a variable. The expression assign a value to this variable.
// Math.floor () and Math.random () are methods.
// The value inside Math.floor() is its argument. The return value of this argument is expression within the yellow parenthesis.
// The whole expression of variable "num" is that a float generated by method Math.random() is multiplied by return value of the range specified by value between declared variable by key word constant.
// The method Math.floor() then return greatest integer of the value of this product.
// And finally plus the value of minimum variable declared.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your steps are in the right order. Now finish with what num is. What is the smallest value it can be? What is the largest? Run the file a few times to check.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

num is a random integer between maximum and minimum inclusive.
The smallest value of 'num' can be 1



console.log(num)
5 changes: 3 additions & 2 deletions Sprint-2/2-mandatory-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
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?
//By adding two slashes at the begining of each line.
16 changes: 12 additions & 4 deletions Sprint-2/2-mandatory-errors/1.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
// trying to create an age variable and then reassign the value by 1

const age = 33;
age = age + 1;
// trying to create an age variable and then reassign the value by 1

let age = 33;
age = age + 1;

//const age = 33;
//age == age + 1;

console.log(age)

//This is a type error. For the expected result of 34, age should not be declared as a constant.
//let should be used instead of const because const is a constant variable and cannot be reassigned.
15 changes: 10 additions & 5 deletions Sprint-2/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";
// Currently trying to print the string "I was born in Bolton" but it isn't working...
// what's the error ?

const cityOfBirth = "Bolton";
console.log(`I was born in ${cityOfBirth}`);


//console.log(`I was born in ${cityOfBirth}`);
//const cityOfBirth = "Bolton";
//The error is that the variable should be declared as a constant before it is used in the console.log statement.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The order is the problem, you are right. Does it need to be a constant, though? Would line 4 still work with let instead of const?

The prep shows three error names: SyntaxError, TypeError and ReferenceError. Which one is this?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

This is a ReferenceError.

In this code, the key word does not need to be constant, it can be let - if this is the case the variable city0fBirth can be reassigned in other lines - instead of constant (which cannot reassign variable).

23 changes: 14 additions & 9 deletions Sprint-2/2-mandatory-errors/3.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
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


// 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
// Expectation about the error : cardNumber is assigned a number value, a .slice function does not work on number
// The constant last4Digits should be assigned to a String (cardNumber) to perform .slice function.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your prediction is clear. What happened when you ran it? Did it match your prediction?

The prep shows three error names: SyntaxError, TypeError and ReferenceError. Which one did you get?

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

console.log(last4Digits);
11 changes: 9 additions & 2 deletions Sprint-2/2-mandatory-errors/4.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
const 12HourClockTime = "8:53pm";
const 24hourClockTime = "20:53";
// const 12HourClockTime = "8:53pm";
// const 24hourClockTime = "20:53";
// An identifier cannot start with a numberical value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Right reason. The prep shows three error names: SyntaxError, TypeError and ReferenceError. Which one is this?


const TweleveHourClockTime = "8:53pm";
const TwentyFourhourClockTime = "20:53";

console.log(TweleveHourClockTime)
console.log(TwentyFourhourClockTime)
57 changes: 35 additions & 22 deletions Sprint-2/3-mandatory-interpret/1-percentage-change.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,35 @@
let carPrice = "10,000";
let priceAfterOneYear = "8,543";

carPrice = Number(carPrice.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

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

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

// 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?
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
// There are five function calls in this code in lines 4, 5, and 10

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Your answers use the line numbers of the original file. Your file has two extra lines now. The fixed line is on line 7, and console.log is on line 12. Delete line 5 and the empty line after it. Then check your line numbers in a) to d) again.

// These function calls are Number, replaceAll, and 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?
// The error is from line 5:
// priceAfterOneYear = Number(priceAfterOneYear.replaceAll("," ""));
// There should be a comma to separate arguments

// c) Identify all the lines that are variable reassignment statements
// Variable reassignment statements on lines 4 and 5.
// Variables carPrice and priceAfterOnYear are originally declared on lines 1 and 2, and reassigned on lines 4 and 5.

// d) Identify all the lines that are variable declarations
// They are lines 1,2,7 and 8.
// On lines 1 and 2, variables carPrice and priceAfterOneYear are declared by let.
// On lines 7 and 8, variables priceDifference and percentageChange are declared by const.

// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?
// To remove comma as a punctuation and space such that the string is ready turn into a number by method Number.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Does this remove spaces too? Look at the first argument of replaceAll.

58 changes: 33 additions & 25 deletions Sprint-2/3-mandatory-interpret/2-time-format.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
const movieLength = 8784; // length of movie in seconds

const remainingSeconds = movieLength % 60;
const totalMinutes = (movieLength - remainingSeconds) / 60;

const remainingMinutes = totalMinutes % 60;
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

// a) How many variable declarations are there in this program?

// b) How many function calls are there?

// c) Using documentation, explain what the expression movieLength % 60 represents
// 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?

// e) What do you think the variable result represents? Can you think of a better name for this variable?

// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer
const movieLength = 8784; // length of movie in seconds

const remainingSeconds = movieLength % 60;
const totalMinutes = (movieLength - remainingSeconds) / 60;

const remainingMinutes = totalMinutes % 60;
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

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

// b) How many function calls are there?
// One function call console.log() in code above.
// The others are declared variables.

// c) Using documentation, explain what the expression movieLength % 60 represents
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
// % is remainder operator. This operator returns the remainder after left operand is divided by 60.

// d) Interpret line 4, what does the expression assigned to totalMinutes mean?
// The expression means first exclude odd seconds, then convert the movie length in number of complete minutes.

// e) What do you think the variable result represents? Can you think of a better name for this variable?
// The variable result represents length of movie in H:M:S format. A better variable name can be movieLength_HMS

// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer
// A value of movieLength 3661 will return a result of 1:1:1 where the place value for second does not conforms with leading zero time format.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Good, the missing zeros are one problem. Now try -90 and 90.5. What does each one print? Would you show a time that way?

63 changes: 36 additions & 27 deletions Sprint-2/3-mandatory-interpret/3-to-pounds.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,36 @@
const penceString = "399p";

const penceStringWithoutTrailingP = penceString.substring(
0,
penceString.length - 1
);

const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
const pounds = paddedPenceNumberString.substring(
0,
paddedPenceNumberString.length - 2
);

const pence = paddedPenceNumberString
.substring(paddedPenceNumberString.length - 2)
.padEnd(2, "0");

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"
const penceString = "399p"; // initialises a string variable with the value "399p"

const penceStringWithoutTrailingP = penceString.substring(
0,
penceString.length - 1
); // use .substring method to extract characters of numerical string, with zero indexing starting from first place of penceString, ending at one digit less than the length of penceString by method .length. Expecting value "399".

const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
//declares paddedPenceNumberString variable. To target the length of pence number string in three characters. If not, "0" will be added at the beginning of the string. Expecting value "399".
const pounds = paddedPenceNumberString.substring(
0,
paddedPenceNumberString.length - 2
); //declares variable for pound. .substring method starting from first character, ending by trimming last two characters by method .length. Expecting value "3"

const pence = paddedPenceNumberString
.substring(paddedPenceNumberString.length - 2)
.padEnd(2, "0"); // declares variable for pence. Argument -2 of .substring method returns the last two characters.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The argument here is paddedPenceNumberString.length - 2, not -2. What number is that for "399"?

// .padEnd method returns character length of two, if not, "0" will be added at the end of string, for examples "90". Here, expecting "99".

console.log(`£${pounds}.${pence}`); // Prints the return value by Template Literal with '£X.yz" format in console pane.


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

// Five Variables declared:
// penceString, penceStringWithoutTrailingP, paddedPenceNumberString,pound, pence
// Three methods used:
//.substring(), .padStart(), .padEnd() .log()
// One property used: .length
33 changes: 18 additions & 15 deletions Sprint-2/4-stretch-explore/chrome.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
Open a new window in Chrome, right click an empty space on the page, select **Inspect** from the dropdown, then locate the **Console** tab.

Voila! You now have access to the [Chrome V8 Engine](https://www.cloudflare.com/en-gb/learning/serverless/glossary/what-is-chrome-v8/).
Just like the Node REPL, you can input JavaScript code into the Console tab and the V8 engine will execute it.

Let's try an example.

In the Chrome console, invoke the function `alert` with one argument, the string `"Hello world!"`;

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`.

What effect does calling the `prompt` function have?
What is the return value of `prompt`?
Open a new window in Chrome, right click an empty space on the page, select **Inspect** from the dropdown, then locate the **Console** tab.

Voila! You now have access to the [Chrome V8 Engine](https://www.cloudflare.com/en-gb/learning/serverless/glossary/what-is-chrome-v8/).
Just like the Node REPL, you can input JavaScript code into the Console tab and the V8 engine will execute it.

Let's try an example.

In the Chrome console, invoke the function `alert` with one argument, the string `"Hello world!"`;

What effect does calling the `alert` function have?
(The function prompts an alert when pressing enter to run)

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?
(The'prompt'function opens a caveat dialog box, allows user to key in response. )
What is the return value of `prompt`?
(prompt(myName) will return value entered by user)
Loading
Loading