-
-
Notifications
You must be signed in to change notification settings - Fork 340
Expand file tree
/
Copy path1-percentage-change.js
More file actions
36 lines (27 loc) · 2.19 KB
/
1-percentage-change.js
File metadata and controls
36 lines (27 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
// There are 4 function calls in this file. The lines where a function call is made are:
// Line 1: carPrice.replaceAll(",", "")
// Line 2: priceAfterOneYear.replaceAll(",", "")
// Line 3: Number(carPrice.replaceAll(",", ""))
// Line 4: Number(priceAfterOneYear.replaceAll(",", ""))
// line 10: console.log(`The percentage change is ${percentageChange}`);
// 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?
// Error on line 5 where comma was missing in replaceAll function call.
// c) Identify all the lines that are variable reassignment statements
// Line 4: carPrice = Number(carPrice.replaceAll(",", ""));
// Line 5: priceAfterOneYear = Number(priceAfterOneYear.replaceAll(",", ""));
// d) Identify all the lines that are variable declarations
// Line 1: let carPrice = "10,000";
// Line 2: let priceAfterOneYear = "8,543";
// Line 7: const priceDifference = carPrice - priceAfterOneYear;
// Line 8: const percentageChange = (priceDifference / carPrice) * 100;
// e) Describe what the expression Number(carPrice.replaceAll(",","")) is doing - what is the purpose of this expression?
// The expression Number(carPrice.replaceAll(",","")) is first calling the replaceAll method on the carPrice string to remove all commas from the string. This is necessary because the presence of commas in a number string can cause issues when trying to convert it to a number. After the commas are removed, the resulting string is passed to the Number function, which converts the string into a numeric value. The purpose of this expression is to convert the carPrice string, which may contain commas, into a number that can be used for calculations.