Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
// The = sign means assignment. It takes whatever is on the right side, works it out, and then stores that result into a variable on the left. So count = count + 1 means take the current value of count, add 1, and then save that back into count.
4 changes: 3 additions & 1 deletion Sprint-1/1-key-exercises/2-initials.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ 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

7 changes: 5 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,10 @@ 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(lastDotIndex);

console.log(`The dir part of ${filePath} is ${dir}`);
console.log(`The ext part of ${filePath} is ${ext}`);

// https://www.google.com/search?q=slice+mdn
8 changes: 8 additions & 0 deletions Sprint-1/1-key-exercises/4-random.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@ 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

// Math.random() returns a random decimal number between 0 and 1
// (maximum - minimum + 1) represents the size of range of numbers we want to include. We add +1 because both minim and maximum are included in the range
// Math.random() * (maximum - minimum + 1) gives us a random decimal between 0 and 100, but still decimal
// Math.floor() rounds down to the nearest whole number. So this. turns decimals like 99.9 into 99
// + minimum since minimum = 1, this shifts the entire random range up by 1. so instead of 0-100, the range becomes 1-100
// num should return a random integer between 1 and 100
3 changes: 2 additions & 1 deletion Sprint-1/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?
We don't want the computer to run these 2 lines - how can we solve this problem?
// Using // to make them comments should resolve the problem. The // tells JavaScript to skip that line completely
10 changes: 9 additions & 1 deletion Sprint-1/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;
const { cityOfBirth } = require("./2");

let age = 33;
age = age + 1;
console.log(age);
// 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}`);

// Changed const to let because the variables value need to change during the program. const creates a fixed reference that cannot be reassigned. but let allows updating the variable which is required when incrementing or modifying values.
1 change: 1 addition & 0 deletions Sprint-1/2-mandatory-errors/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@

console.log(`I was born in ${cityOfBirth}`);
const cityOfBirth = "Bolton";
// Error: Cannot access 'cityOfBirth' before instialization - the error means: you tried to use a let or const variable before its declaration line ran.
6 changes: 5 additions & 1 deletion Sprint-1/2-mandatory-errors/3.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
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

// I predict that the code will fail because .slice() is not valid on a number - The variable is a number, but .slice() only works on strings and arrays.
// The error that I got is similar to what I had predicted.
13 changes: 12 additions & 1 deletion Sprint-1/2-mandatory-errors/4.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,13 @@
const 12HourClockTime = "20:53";
const 24hourClockTime = "08:53";
// This line of code attempts to declare a constant variable named 12HourClockTime, but it results in a syntax error
const 24hourClockTime = "08:53";

// While testing the code, the following error appeared in console:
// SyntaxError: Invalid or unexpected token

// Why did this error occur? according to the MDN Web Docs: https://developer.mozilla.org/en-US/docs , a "SyntaxError: Invalid or unexpected token" occurs when JavaScript encounters code that doesn't follow proper syntax rules
// In this case, the error happens because JavaScript does not allow variable names to start with numbers. Variable names (also called identifiers) must begin with a letter, underscore (_), or dollar sign ($)

// How to fix the error:
const hour12ClockTime = "20:53";
// These version follow JavaScript naming rules and will execute without errors
15 changes: 15 additions & 0 deletions Sprint-1/3-mandatory-interpret/1-percentage-change.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,25 @@ console.log(`The percentage change is ${percentageChange}`);

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

// Line 4 contains two function calls: replaceAll(",", "") & Number(...)
// Line 5 also contains two function calls: replaceAll(",","") & Number(...)
// Line 10 contains one function call: 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 originates from line 5: SyntaxError: missing ) after argument list. According to MDN Web Docs, this occurs when there is a problem with how a function is called - typically caused by a typo, a missing separator (such as a comma), or an incorrectly formatted string within the argument list

// c) Identify all the lines that are variable reassignment statements
// Line 4: Reassignment (not a declaration)
// Line 5: Reassignment (not a declaration)

// d) Identify all the lines that are variable declarations
// Line 1: Variable declaration using 'let'
// Line 2: Variable declaration using 'let'
// Line 7: Variable declaration using 'const'
// Line 8: Variable declaration using 'const'

// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?
/* The expression Number(carPrice.replaceAll(",","")) first uses the String.prototype.replaceAll() method to remove all commas from the string stored in carPrice
It then passes the resulting string to the Number() function, which converts it into a numeric value. According to MDN, replaceALL() returns a new string with all occurrences of a
specified substring replaced, and Number() converts its argument to a number or return NaN if the conversion fails */
14 changes: 14 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,28 @@ 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: movieLength, remainingSeconds, totalMinutes, remainingMinutes, totalHours, and result

// b) How many function calls are there?
// There is only one function call in this program: console.log(results);

// c) Using documentation, explain what the expression movieLength % 60 represents
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
// The expression movieLength % 60 uses the remainder operator ( % ) to work out how many seconds are left over after dividing the total movie length by 60.
// So if movieLength is 8784 seconds, dividing by 60 gives 146 full minutes with 24 seconds left - that leftover part (24) is what this expression returns.
// According to MDN Docs, the remainder operator gives the value that's left after one number is divided by another

// d) Interpret line 4, what does the expression assigned to totalMinutes mean?
// The expression totalMinutes is a variable that stores the result of the calculation (movieLength - remainingSeconds) / 60. It represents the total number of full minutes in the movie after converting the total seconds into minutes.
// According to MDN Docs, a variable is a named container used to store data values. In this cause, totalMinutes holds a numeric value that JavaScript can use later in other calculations, like finding the number of hours or remaining minutes.

// e) What do you think the variable result represents? Can you think of a better name for this variable?
// The variable result stores a formatted string that combines the total hours, remaining minutes, and remaining seconds into one readable time format.
// It uses template literals (the backtick syntax `...`) to insert each variable's value directly into the string using ${} placeholders.
// so, for example, if totalHours = 2, remainingMinutes = 26, and remainingSeconds = 24, the value of result becomes the string "2 : 26 : 24".
// According to MDN Docs, template literals allow embedded expressions inside strings, making it easier to create dynamic text
// A better name for the variable result would be formattedTime because it makes it clearer what the value actually represents. Moreover, using a name like formattedTime makes the code easier to read and understand

// f) Try experimenting with different values of movieLength. Will this code work for all values of movieLength? Explain your answer
// This code works properly for positive whole numbers because the reminder ( % ) and division ( / ) operators correctly split the total number of seconds into hours, minutes, and seconds.
// However, it might not give the right results if movieLength is negative, a decimal, or not a number at all. As explained on MDN Docs, the remainder operator keeps the same sign as the left number, so if the input is negative, you would get negative remainders - which wouldn't make sense when showing time
7 changes: 7 additions & 0 deletions Sprint-1/3-mandatory-interpret/3-to-pounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,10 @@ console.log(`£${pounds}.${pence}`);

// To begin, we can start with
// 1. const penceString = "399p": initialises a string variable with the value "399p"
// 3. const penceStringWithoutTrailingP = penceString.substring(0, penceString.length -1);
// creates a new string that removes the last character ("p") from penceString, leaving just the number part
// 8. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
// Adds zero to the start of thr string if it's shorter than three digits, ensuring values like "9" become "009"
// 14. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length -2)
//.padEnd(2, "0") - Takes the last two digits as the pence portion of the price and adds a zero if it's missing a digit
// 18. console.log(`£${pounds}.${pence}`) - Displays the formatted price in pounds and pence, such as £3.99
8 changes: 8 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
// It will show an error message

// 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,13 @@ function capitalise(str) {
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
}
capitalise("Hello");

// =============> write your explanation here
// SyntaxError: Identifier 'str' has already been declared - This error means that the variable 'str' was declared more than once in the same scope.
// JavaScrip doesn't allow that - once a variable name is declared with let or const, you can't declare it again.
// =============> write your new code here
function capitalise(str) {
return str[0].toUpperCase() + str.slice(1);
}

20 changes: 18 additions & 2 deletions Sprint-2/1-key-errors/1.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,35 @@

// Why will an error occur when this program runs?
// =============> write your prediction here
// I predict that this program will throw a error - due to the variable decimalNumber being redeclared.

// Try playing computer with the example to work out what is going on

function convertToPercentage(decimalNumber) {
/* function convertToPercentage(decimalNumber) {
const decimalNumber = 0.5;
const percentage = `${decimalNumber * 100}%`;

return percentage;
}

console.log(decimalNumber);
console.log(decimalNumber); */

// =============> write your explanation here
// Function covertToPercentage(decimalNumber) - it has a parameter named decimalNumber
// Inside the function: const decimalNumber =0.5; - this redeclares the same variable name that's already used for the parameter.
// That causes an error: SyntaxError: Identifier 'decimalNumber' has already been declared - because you can't declare a const (or let) with the same name as a parameter inside the same function scope.
// JavaScript doesn't allow us to declare a new variable with the same name in the same scope, so it caused an error.

// Finally, correct the code to fix the problem
// =============> write your new code here
function convertToPercentage(decimalNumber) {
const percentage = `${decimalNumber * 100}%`;
return percentage;
}

console.log(convertToPercentage(0.5));

// Function decimalNumber = 0.5
// It calculates 0.5 * 100 = 50
// it returns "50%"
// console logs 50%
18 changes: 10 additions & 8 deletions Sprint-2/1-key-errors/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@
// this function should square any number but instead we're going to get an error

// =============> write your prediction of the error here

function square(3) {
return num * num;
}
// It throw a error - because of invalid parameter (can't use a number as a parameter name)
//function square(3) {
// return num * num;
//}

// =============> write the error message here

// SyntaxError: Unexpected number
// =============> explain this error message here

// The "Unexpected number" error arises when a numeral is improperly positioned or used within JavaScript code.
// Finally, correct the code to fix the problem

// =============> write your new code here
function square(num){
return num * num;
}


console.log(square);
10 changes: 8 additions & 2 deletions Sprint-2/2-mandatory-debug/0.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
// Predict and explain first...

// =============> write your prediction here

// It will throw a undefined error
function multiply(a, b) {
console.log(a * b);
}

console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);
//console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);

// =============> write your explanation here
// The function printed the answer but didn't return it, so when it was used in the template string, it came out as "undefined."

// Finally, correct the code to fix the problem
// =============> write your new code here
function multiply(a, b) {
return a * b;
}

console.log(`The result of multiplying 10 and 32 is ${multiply(10, 32)}`);
11 changes: 9 additions & 2 deletions Sprint-2/2-mandatory-debug/1.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
// Predict and explain first...
// =============> write your prediction here
// I predict it will throw a undefined error

function sum(a, b) {
/* function sum(a, b) {
return;
a + b;
}

console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);
console.log(`The sum of 10 and 32 is ${sum(10, 32)}`); */

// =============> write your explanation here
// The problem was that the semicolon after return, which made the function stop before adding the numbers.
// Finally, correct the code to fix the problem
// =============> write your new code here
function sum(a, b) {
return a + b; // Once I put a + b on the same line as return, it worked
}

console.log(`The sum of 10 and 32 is ${sum(10, 32)}`);
16 changes: 16 additions & 0 deletions Sprint-2/2-mandatory-debug/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

// Predict the output of the following code:
// =============> Write your prediction here
// Since getLastDigit() does not declare any parameters, the arguments passed when calling it are going to be ignored

const num = 103;

Expand All @@ -15,10 +16,25 @@ console.log(`The last digit of 806 is ${getLastDigit(806)}`);

// Now run the code and compare the output to your prediction
// =============> write the output here
// The last digit of 42 is 3
// The last digit of 105 is 3
// The last digit of 806 is 3
// Explain why the output is the way it is
// =============> write your explanation here
// The function getLastDigit() does not any parameters, but it is being called with argument:
// getLastDigit(42), getLastDigit(105), and getLastDigit(806). Inside the function, it always uses the global const num, which is set to 103.
// That means every call ignores the arguments and always returns the last digit of 103, which is "3"
// Finally, correct the code to fix the problem
// =============> write your new code here
function getLastDigit(num){
return num.toString().slice(-1);

}

console.log(`The last digit of 42 is ${getLastDigit(42)}`);
console.log(`The last digit of 105 is ${getLastDigit(105)}`);
console.log(`The last digit of 806 is ${getLastDigit(806)}`);


// This program should tell the user the last digit of each number.
// Explain why getLastDigit is not working properly - correct the problem
10 changes: 9 additions & 1 deletion Sprint-2/3-mandatory-implement/1-bmi.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,12 @@

function calculateBMI(weight, height) {
// return the BMI of someone based off their weight and height
}
const bmi = weight / (height * height);
return bmi.toFixed(1);
}

console.log(`Your BMI is ${calculateBMI(68, 1.75)}`);
// How it works: function calculateBMI(weight, height)
// Parameters: weight - number, person's weight in kilograms height - number, person's height in meters
// Returns: The Body Mass Index (BMI), rounded to one decimal place

3 changes: 3 additions & 0 deletions Sprint-2/3-mandatory-implement/2-cases.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@
// You will need to come up with an appropriate name for the function
// Use the MDN string documentation to help you find a solution
// This might help https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
const greeting = "Hello there."

console.log(greeting.toUpperCase());
13 changes: 13 additions & 0 deletions Sprint-2/3-mandatory-implement/3-to-pounds.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,16 @@
// You will need to declare a function called toPounds with an appropriately named parameter.

// You should call this function a number of times to check it works for different inputs
funnction formatPenceToPounds(penceString) {

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

const pounds = paddedPenceNumberString.slice(0, -2);
const pence = paddedPenceNumberString.slice(-2);

return `£${pounds}.${pence}`;
}

console.log(formatPenceToPounds("9p"));
console.log(formatPenceToPounds("39p"));
console.log(formatPenceToPounds("399"));
Loading
Loading