Skip to content
27 changes: 22 additions & 5 deletions Sprint-2/1-key-errors/0.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
// Predict and explain first...
// =============> write your prediction here
// If you try to run this code, it will throw a SyntaxError: Identifier 'str' has already been declared.

// call the function capitalise with a string input
// interpret the error message and figure out why an error is occurring

function capitalise(str) {
let str = `${str[0].toUpperCase()}${str.slice(1)}`;
return str;
let str = `${str[0].toUpperCase()}${str.slice(1)}`;

return str;
}
// When you define function capitalise(str), JavaScript automatically creates a local variable named str inside the function's scope,
// assigning it whatever value you pass into the function.
// The let keyword has a strict rule: you cannot declare a variable that already exists in the same scope.
// Because str was already claimed by the function's parameter, JavaScript immediately stops and throws a SyntaxError before it even tries to capitalize anything.
// this is the reason why the error is occurring.
// the if condition i added is to ensure that if an empty string is passed to the function, it will return the empty string instead of throwing an error.
// To fix the error, you can simply remove the let keyword and just assign the new value to str without redeclaring it.

function capitalise(str) {
if (typeof str !== "string") {
return str;
}

return `${str[0].toUpperCase()}${str.slice(1)}`;

}
console.log(capitalise("hello world!"));


// =============> write your explanation here
// =============> write your new code here
16 changes: 13 additions & 3 deletions Sprint-2/1-key-errors/1.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Predict and explain first...

// Why will an error occur when this program runs?
// =============> write your prediction here
// this will throw a SyntaxError: Identifier 'decimalNumber' has already been declared.

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

Expand All @@ -14,7 +14,17 @@ function convertToPercentage(decimalNumber) {

console.log(decimalNumber);

// =============> write your explanation here
// it will throw this error SyntaxError: Identifier 'decimalNumber' has already been declared.
// by declaring the variable decimalNumber as a parameter inside the function parentheses.
// This will create it again on the next line using const, JavaScript gets confused and blocks the code from running.

// Finally, correct the code to fix the problem
// =============> write your new code here
// this is the correct code below

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

return percentage;
}

console.log(convertToPercentage(0.5));
17 changes: 10 additions & 7 deletions Sprint-2/1-key-errors/2.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@

// this function should square any number but instead we're going to get an error

// =============> write your prediction of the error here
// Variable and parameter names must be identifiers (like words, e.g., num, x, myNumber).
//They cannot be literal values or specific numbers like 3.

function square(3) {
return num * num;
//return num * num;
}

// =============> write the error message here
// the error message is: SyntaxError: Unexpected number.

// =============> explain this error message here
// The error message SyntaxError: Unexpected number means that JavaScript encountered a raw number,
// where it was strictly expecting to see a variable name.

// Finally, correct the code to fix the problem

// =============> write your new code here


function square(num) {
return num * num;
}
console.log(square(3));
16 changes: 12 additions & 4 deletions Sprint-2/2-mandatory-debug/0.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
// Predict and explain first...

// =============> write your prediction here
// This code will actually run without throwing a red crash error,
// but it will print something very strange. the result of multiplying 10 and 32 is undefined.

function multiply(a, b) {
console.log(a * b);
}

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

// =============> write your explanation here
// console.log() inside the function: Inside the multiply function, you used console.log(a * b).
// This instantly prints 320 to the screen, but it does not give that number back to the code that called it.
//The Missing return: In JavaScript, if a function does not explicitly use the word return, it automatically hands back undefined.
//The undefined string: Because multiply(10, 32) returns undefined, your outer console.log plugs undefined into the sentence, resulting in: "The result of multiplying 10 and 32 is undefined".

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

console.log(multiply(10, 32));
13 changes: 11 additions & 2 deletions Sprint-2/2-mandatory-debug/1.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Predict and explain first...
// =============> write your prediction here
// This code will run without throwing a crash error, but it will print an incorrect result.
// The output will be:This code will run without throwing a crash error, but it will print an incorrect result.
// The output will be: The sum of 10 and 32 is undefined

function sum(a, b) {
return;
Expand All @@ -8,6 +10,13 @@ function sum(a, b) {

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

// =============> write your explanation here
// =============> the explanation:
// The function sum has a return statement before the addition operation, which causes the function to return undefined immediately.
// To fix this, the return statement should be placed after the addition operation.
// because the function is not a string i have to remove the backticks and use a normal string concatenation to print the result correctly.
// Finally, correct the code to fix the problem
// =============> write your new code here
function sum(a, b) {
return a + b;
}
console.log(sum(10, 32));
31 changes: 25 additions & 6 deletions Sprint-2/2-mandatory-debug/2.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// Predict and explain first...

// Predict the output of the following code:
// =============> Write your prediction here
// this code might not run properly because the function getLastDigit is not set up to take any parameters,
// but we are trying to pass in a number when we call it.

const num = 103;
//const num = 103;

function getLastDigit() {
function getLastDigit(num) {
return num.toString().slice(-1);
}

Expand All @@ -14,11 +15,29 @@ console.log(`The last digit of 105 is ${getLastDigit(105)}`);
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 output is the way it is because the function getLastDigit does not take any parameters,
// but we are trying to pass in a number when we call it. Instead, the function is using the variable num which is set to 103.
// Therefore, regardless of what number we pass in, the function will always return the last digit of 103, which is 3.

// Finally, correct the code to fix the problem
// =============> write your new code here

const num = 103;

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
// The function getLastDigit is not working properly because it does not take any parameters,
// to fix the problem, we need to add a parameter to the function definition so that it can accept a number when called.
6 changes: 4 additions & 2 deletions Sprint-2/3-mandatory-implement/1-bmi.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@
// It should return their Body Mass Index to 1 decimal place

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(calculateBMI(70, 1.73));
5 changes: 5 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,8 @@
// 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

function toUpperSnakeCase(str) {
return str.toUpperCase().replace(/ /g, '_');
}
console.log(toUpperSnakeCase("lord of the rings"));
24 changes: 24 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,27 @@
// 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
function toPounds(penceString) {
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");

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

console.log(toPounds("399p"));
console.log(toPounds("1250p"));
console.log(toPounds("5p"));
console.log(toPounds("70p"));
console.log(toPounds("0p"));
17 changes: 12 additions & 5 deletions Sprint-2/4-mandatory-interpret/time-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,25 @@ function formatTimeDisplay(seconds) {
// Questions

// a) When formatTimeDisplay is called how many times will pad be called?
// =============> write your answer here
// pad will be called 3 times. Inside the return statement of formatTimeDisplay,
// pad is called once for totalHours, once for remainingMinutes, and once for remainingSeconds.

// Call formatTimeDisplay with an input of 61, now answer the following:

// b) What is the value assigned to num when pad is called for the first time?
// =============> write your answer here
// Answer: 0. Reason: The first evaluation in the template literal is pad(totalHours).
// Since totalHours is 0, 0 is passed as the argument to num.

// c) What is the return value of pad is called for the first time?
// =============> write your answer here
// answer: "00". Reason: The while loop in pad checks if the length of numString is less than 2.
// Since numString is "0", the loop runs and adds a "0" to the front, making it "00".
// The loop then checks again, and since the length is now 2, it exits and returns "00".

// d) What is the value assigned to num when pad is called for the last time in this program? Explain your answer
// =============> write your answer here
// Answer: 1. Reason: The last evaluation in the template literal is pad(remainingSeconds).
// Since remainingSeconds is 1, 1 is passed as the argument to num.

// e) What is the return value of pad when it is called for the last time in this program? Explain your answer
// =============> write your answer here
// Answer: "01". Reason: The while loop in pad checks if the length of numString is less than 2.
// Since numString is "1", the loop runs and adds a "0" to the front, making it "01".
// The loop then checks again, and since the length is now 2, it exits and returns "01".
18 changes: 17 additions & 1 deletion Sprint-2/5-stretch-extend/format-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,20 @@

function formatAs12HourClock(time) {
const hours = Number(time.slice(0, 2));
const minutes = time.slice(3, 5);

if (hours > 12) {
return `${hours - 12}:00 pm`;
const convertedHours = hours - 12;
// Pad the hour with a leading zero if it's a single digit (e.g., 3 becomes "03")
const paddedHours = String(convertedHours).padStart(2, "0");
return `${paddedHours}:${minutes} pm`;
}

return `${time} am`;
}

// === Your Tests (All will now pass silently!) ===

const currentOutput = formatAs12HourClock("08:00");
const targetOutput = "08:00 am";
console.assert(
Expand All @@ -23,3 +31,11 @@ console.assert(
currentOutput2 === targetOutput2,
`current output: ${currentOutput2}, target output: ${targetOutput2}`
);

console.assert(formatAs12HourClock("15:00") === "03:00 pm", `Failed Case D: 03:00 pm`);
console.assert(formatAs12HourClock("13:00") === "01:00 pm", `Failed Case E: 01:00 pm`);
console.assert(formatAs12HourClock("15:45") === "03:45 pm", `Failed Case D: 03:45 pm`);
console.assert(formatAs12HourClock("13:45") === "01:45 pm", `Failed Case E: 01:45 pm`);
console.assert(formatAs12HourClock("08:45") === "08:45 am", `Failed Case F: 08:45 am`);

console.log("All current assertions completed!");
Loading