Skip to content
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

NW6 |Zeliha Pala | JS1 Module | [TECH ED] Complete week 1 exercises | Week1 #133

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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
5 changes: 3 additions & 2 deletions week-1/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?
// we use comments for them
7 changes: 6 additions & 1 deletion week-1/errors/1.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
// trying to create an age variable and then reassign the value by 1

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

//we can not reassign a new value to a constant. if we reassign a value to a const variable, we will get a "TypeError." but we can do this;

Choose a reason for hiding this comment

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

that's right 👍

let age = 33;
age = age + 1;
console.log(age);
4 changes: 2 additions & 2 deletions week-1/errors/2.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Currently trying to print the string "I was born in Bolton" but it isn't working...
// what's the error ?
// what's the error ? cityOfBirth variable needs to be declared before console.log.

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

Choose a reason for hiding this comment

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

Perfect 👍

15 changes: 14 additions & 1 deletion week-1/errors/3.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
const cardNumber = 4533787178994213;
/*const cardNumber = "4533787178994213";
const last4Digits = cardNumber.slice(-4);

console.log(" 4 digits of cardNumber: " + last4Digits); */

const cardNumber = "4533787178994213";
const last4Digits = cardNumber.slice(-4); // I wanted to test if it works without concatenating and it works

console.log("4 digits cardNumber:", last4Digits); // here i want to see if without concatenate

/*1.The slice method is typically used with strings to extract a portion of the string.
to extract the last 4 digits of the card number, we must first convert it to a string and then use the slice method.So we put the number in string */

Choose a reason for hiding this comment

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

Your analysis of the problem is correct. However, the tasks asks to "try updating the expression last4Digits is assigned to, in order to get the correct value"

How might you update the expression to make the value that's being sliced into a string?


// The last4Digits variable should store the last 4 digits of cardNumber

// However, the code isn't working

// Make and explain a prediction about why the code won't work

// Then try updating the expression last4Digits is assigned to, in order to get the correct value
7 changes: 6 additions & 1 deletion week-1/errors/4.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
const 12HourClockTime = "20:53";
const 24hourClockTime = "08:53";
const 24hourClockTime = "08:53";
//variable names in JavaScript cannot start with a digit. They must start with a letter, underscore (_), or dollar sign ($).
//I do not know what to do here

const twelveHourClockTime = "20:53";
const twentyFourHourClockTime = "08:53";
3 changes: 3 additions & 0 deletions week-1/exercises/count.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
let count = 0;

count = count + 1;
console.log(count);

// 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 assignment sign is used to assign a new value to a variable. Here the count variable will have a new value of 1, which means it has been incremented by 1.

Choose a reason for hiding this comment

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

That's correct. It's a reassignment statement

14 changes: 13 additions & 1 deletion week-1/exercises/decimal.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

const num = 56.5467;

// You should look up Math functions for this exercise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
Expand All @@ -8,3 +7,16 @@ const num = 56.5467;
// Create a variable called roundedNum and assign to it an expression that evaluates to 57 ( num rounded to the nearest whole number )

// Log your variables to the console to check your answers

const wholeNumberPart = Math.floor(num); // Extract the whole number part 56
const decimalPart = num - wholeNumberPart; // Calculate the decimal part; num is 56.5467 - wholeNum is 56 so 0,5467 is decimal

Choose a reason for hiding this comment

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

Your thinking here is correct. However, there are some nuances with using floating point numbers, that you will see when this code is run.
To get the right answer, try looking up how to maintain number of decimal places when subtracting floating point numbers in javascript

const roundedNum = Math.round(num); // Round to the nearest whole number is 56,5 and will be 57

console.log("Whole Number Part:", wholeNumberPart);
console.log("Decimal Part:", decimalPart);
console.log("Rounded Number:", roundedNum);

/* a) The Math.floor function is used to round down a decimal number to the nearest integer that is less than or equal to the original number.
If Math.floor(-8.4), the result will be -9. This is because -9 is the closest integer that is less than or equal to -8.4. The function essentially rounds down to the nearest whole number.*/

/* b) If Math.floor(8.4), the result will be 8. The Math.floor function rounds down the given decimal number to the nearest integer that is less than or equal to the original number. In this case, 8 is the closest integer that satisfies this condition for the decimal 8.4. */
6 changes: 5 additions & 1 deletion week-1/exercises/initials.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@ let middleName = "Katherine";
let lastName = "Johnson";

// Declare a variable called initials that stores the first character of each string in upper case to form the user's initials
// Log the variable in each case
// Log the variable in each case.
//Here we use the charAt(0) method with the toUpperCase() method. (the first character of a string in JavaScript starts with 0)
let initials = firstName.charAt(0) + middleName.charAt(0) + lastName.charAt(0);

console.log("User:", initials);
8 changes: 6 additions & 2 deletions week-1/exercises/paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@
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(filePath.indexOf("/"), lastSlashIndex);
console.log(dir);

// Create a variable to store the ext part of the variable .txt file.txt
const ext = filePath.slice(filePath.lastIndexOf("."));

Choose a reason for hiding this comment

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

Nice 👍

console.log(ext);
7 changes: 7 additions & 0 deletions week-1/exercises/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ const minimum = 1;
const maximum = 100;

const num = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
//Math.random() function returns a floating-point number between 0 (inclusive) and 1 (exclusive). It's essentially a random decimal number. like spinning a wheel with numbers between 0 and 1. It gives us a random decimal, like 0.567 or 0.874.

//maximum - minimum + 1: This part helps decide how big your range on the number line should be. If you want numbers from 1 to 100, the range is 100 - 1 + 1, which is 100.
// Math.floor(...): This is like rounding down to the nearest whole number. So, if you got 56.78, you round down to 56.
//+ minimum: Finally, you add the starting point of your range. If the minimum is 1, you add 1 to the rounded-down number. So, if you got 56 earlier, you add 1 and get 57.

console.log(num); // Here we get random numbers each time

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

Choose a reason for hiding this comment

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

Here, try to explain what the expression on line 4 is doing. Run the program a few times - do you get the same value or different values? Also, try breaking down each part of the expression to help understand

Expand Down
4 changes: 2 additions & 2 deletions week-1/explore/chrome.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ Just like the Node REPL, you can input JavaScript code into the Console tab and
Let's try an example.

In the Chrome console,
invoke the function `alert` with an input string of `"Hello world!"`;
invoke the function `alert` with an input string of `"Hello world!"`; alert("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`.
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`. /*let myName = prompt("What is your name?");*/

What effect does calling the `prompt` function have?
What is the return value of `prompt`?
26 changes: 24 additions & 2 deletions week-1/explore/objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,37 @@

In this activity, we'll explore some additional concepts that you'll encounter in more depth later on in the course.

Open the Chrome devtools Console, type in `console.log` and then hit enter
Open the Chrome devtools Console, type in `console.log` and then hit enter
ƒ log() { [native code] }

What output do you get?

Now enter just `console` in the Console, what output do you get back?

console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …}

Try also entering `typeof console`

typeof console
'object'

Answer the following questions:

What does `console` store?
What does the syntax `console.log` or `console.assert` mean? In particular, what does the `.` mean?
What does the syntax `console.log` or `console.assert` mean?
In JavaScript, the console is like a toolbox for developers. It helps them see messages, warnings, and errors while building and fixing things on a website. It's a way to peek behind the scenes and understand what's happening in their code. console.log is like a sticky note to jot down messages for themselves, and console.assert is a tool to shout out if something isn't right.

Choose a reason for hiding this comment

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

Well explained!


both console.log and console.assert provide ways to output information to the console, but they serve different purposes.
console.log is for general logging and debugging,
while console.assert is used to check conditions and log an error if the condition is not met.

examples
let myAge = 42;
console.log("I am :", myAge);

let myAge = 42;
console.assert(myAge >= 18, "Eligible");

In particular, what does the `.` mean?

The . (dot) in JavaScript is called the dot notation and is used to access properties and methods of objects.

Choose a reason for hiding this comment

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

So, in the case of console.log and console.assert, what is being accessed?

24 changes: 19 additions & 5 deletions week-1/interpret/percentage-change.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
let carPrice = "10,000";
let priceAfterOneYear = "8,543";

carPrice = Number(carPrice.replaceAll(",", ""));
carPrice = Number(carPrice.replaceAll(",", "")); // converts to number takes the string quato
priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));

const priceDifference = carPrice - priceAfterOneYear;
Expand All @@ -11,10 +11,24 @@ 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
/* a) How many function calls are there in this file? Write down all the lines where a function call is made
Number is a function. replaceAll is a method

// b) Identify all the lines that are variable reassignment statements
how many function calls would you say are in this file?
carPrice.replaceAll(",", ""): This function call is used to replace commas in the string representation of carPrice with an empty string.

// c) Identify all the lines that are variable declarations
priceAfterOneYear.replaceAll(",", ""): This function call is used to replace commas in the string representation of priceAfterOneYear with an empty string.*/

// d) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?
/* b) Identify all the lines that are variable reassignment statements
carPrice = Number(carPrice.replaceAll(",", "")); // converts to number takes the string quato
priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));
the values of the variables carPrice and priceAfterOneYear has bee changed with removing commas and converting them to numbers */

/* c) Identify all the lines that are variable declarations
let keyword is used to declare two variables, carPrice and priceAfterOneYear, and initialize them with string values.
priceDifference and percentageChange, using the const keyword. The const keyword is used to create constants in JavaScript, meaning that the value of these variables cannot be reassigned once they are initially assigned. If we attempt to reassign a value to a variable declared with const, it will result in a syntax error.*/

/* d) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?
ReplaceAll turns into an empty character with .replaceAll, and it turns into a number with number. */

// e) const keyword is used to declare constants. A constant is a variable whose value cannot be changed or reassigned after it has been initially assigned. If you attempt to reassign a value to a variable declared with const, it will result in a syntax error.
44 changes: 35 additions & 9 deletions week-1/interpret/time-format.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,55 @@
const movieLength = 8784; // length of movie in seconds

const remainingSeconds = movieLength % 60;
const totalMinutes = (movieLength - remainingSeconds) / 60;
const remainingSeconds = movieLength % 60; // This line calculates the remaining seconds by taking the modulus (%) of movieLength divided by 60.
const totalMinutes = (movieLength - remainingSeconds) / 60; //This line calculates the total minutes by subtracting remainingSeconds from movieLength and then dividing the result by 60.

const remainingMinutes = totalMinutes % 60;
const totalHours = (totalMinutes - remainingMinutes) / 60;
const remainingMinutes = totalMinutes % 60; //This line calculates the remaining minutes by taking the modulus of totalMinutes divided by 60.
const totalHours = (totalMinutes - remainingMinutes) / 60; //This line calculates the total hours by subtracting remainingMinutes from totalMinutes and then dividing the result by 60.

const remainingHours = totalHours % 24;
const remainingHours = totalHours % 24; //This line calculates the remaining hours by taking the modulus of totalHours divided by 24.

const result = `${remainingHours}:${remainingMinutes}:${remainingSeconds}`;
const result = `${remainingHours}:${remainingMinutes}:${remainingSeconds}`; // time format "HH:MM:SS".
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?
// a) How many variable declarations are there in this program? 6
/*
const movieLength = 8784;
const remainingSeconds = movieLength % 60;
const totalMinutes = (movieLength - remainingSeconds) / 60;
const remainingMinutes = totalMinutes % 60;
const totalHours = (totalMinutes - remainingMinutes) / 60;
const remainingHours = totalHours % 24;
*/

Choose a reason for hiding this comment

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

Nearly! It looks like you're missing 1 here 👀


// b) How many function calls are there?
// b) How many function calls are there? 1
//console.log(result);

Choose a reason for hiding this comment

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

Excellent spot! ⭐


// c) Using documentation on MDN, explain what the expression movieLength % 60 represents
//This is modulo operation, and it returns the remainder of the division. Here it says the variable movieLength, is divided by 60 and The % modulo operator, returns the remainder of the division operation.

Choose a reason for hiding this comment

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

Nice 👌


// d) Interpret line 4, what does the expression assigned to totalMinutes mean?

/*to find the total minutes of the movie;
we Subtract the remaining seconds (remainingSeconds) from the total seconds (movieLength)
and we Take the result and divide it by 60.
The final result is the total number of minutes in the movie, stored in the variable totalMinutes."*/

// e) What do you think the variable result represents? Can you think of a better name for this variable?
/* It expresses the length of the movie in terms of hours, minutes, and seconds.
The format is HH:MM:SS, where HH is the remaining hours, MM is the remaining minutes, and SS is the remaining seconds.
My suggestion for result variable is :
const movieDurationDisplay */

Choose a reason for hiding this comment

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

Very nice 👍


// f) Think about whether this program will work for all values of movieLength.
//The program correctly converts the total seconds into a formatted string representing hours, minutes, and seconds.It should work correctly for any positive integer value of movieLength.

// Think of what values may cause problems for the code.
// Decide the result should be for those values, then test it out.
// If the movieLength is negative or if movieLength is a floating-point number, or If movieLength is 0, we may have problems

// Decide the result should be for those values, then test it out. ......

// Can you find any values of movieLength which don't give you what you'd expect?

Choose a reason for hiding this comment

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

You've got the right answer above. Given that, what are some example values for movieLength that might cause problems for the code?

const movieLength = "not a number";
const movieLength = 3661.5;
32 changes: 27 additions & 5 deletions week-1/interpret/to-pounds.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
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
Expand All @@ -26,4 +22,30 @@ console.log(`£${pounds}.${pence}`);

// To begin, we can start with

// 1. const penceString = "399p": initialises a string variable with the value "399p"
/* 1. const penceString = "399p": initialises a string variable with the value "399p"

2.const penceStringWithoutTrailingP = penceString.substring( 0, penceString.length - 1 ); penceStringWithoutTrailingP takes a substring of penceString starting from index 0 and ending at the length of penceString minus 1. This effectively removes the last character "p" from penceString.
if penceString is "399p", then penceStringWithoutTrailingP would be "399" because it removes the trailing "p" from the original string. The purpose of this operation seems to be to get the numeric part of the string without the currency symbol ("p" in this case).


3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");

The padStart method is used to ensure that paddedPenceNumberString is always three characters long. If the length is less than 3, "0" is padded to the start of the string.


4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2 );
pounds is assigned the substring of paddedPenceNumberString starting from index 0 and ending two characters before the length of paddedPenceNumberString. This extracts the part of the string representing pounds.


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

pence is assigned the last two characters of paddedPenceNumberString, and if the length is less than 2, "0" is padded to the end of the string.




console.log(`£${pounds}.${pence}`); £3.99 */

//The padStart method is used to pad the start of a string with a specified character (or a specified string) until the resulting string reaches a given length. Here, we are using padStart to ensure that paddedPenceNumberString is at least 3 characters long. If the length of penceStringWithoutTrailingP is less than 3 characters, it will pad the start of the string with zeros until it reaches a length of 3.This method is used to pad a string with a specified character at the beginning until it reaches a certain length. While doing this, the original string remains unchanged; a new string is returned.The first parameter of the padStart method specifies the target length, and the second parameter specifies the character to be added during the padding.

// Since the length of penceStringWithoutTrailingP is already 3, padStart does not add any zeros, and paddedPenceNumberString remains "399".So, in this case, no zeros are added in front of the number because the length requirement is already met. If the length was less than 3, it would pad with zeros accordingly.

Choose a reason for hiding this comment

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

Your explanation looks like you have understood it really well.