003.  Solving 30-Days-Of-JavaScript challenge questions.

003. Solving 30-Days-Of-JavaScript challenge questions.

Table of contents

DAY 3.

Welcome to day 3 of the 30 -Days-Of-JavaScript challenge by Asabeneh. You can go ahead and do challenge while using this series of articles as your reference.

Visit Day-2 for previous article.

Exercises: Level 1

1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it and use the typeof operator to check different data types.

Not hard, right?

Solution:

image.png

2. Check if type of '10' is equal to 10

Solution:

image.png

3. Check if parseInt('9.8') is equal to 10

Solution:

image.png

4. Boolean value is either true or false.

JavaScript coerces values to either truthy : values that evaluate to true or falsy : values that evaluate to false.

There are six falsy values in JavaScript :

  1. undefined
  2. null
  3. NaN
  4. 0 (zero)
  5. An empty string: no space between the quotes i.e. ('' or "" or ``)
  6. false.

Anything else other than these six is a truthy value.

        I. Write three JavaScript statements which provide truthy value.

You can assign assign any value(s) to your variables as long as they coerce to true.

Solution(s):

image.png

       I. Write three JavaScript statements which provide falsy value.

Here you'll need to assign any of the six falsy values to your variables.

Solution:

image.png

5. Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log()

image.png

Solution(s) :

image.png

6. Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log()

image.png

Logic operators have different use cases. In this question(s), the logic AND (&&) will return a boolean : either true or false. The JavaScript engine evaluates the logic from left to right and returns true if the both the left part of the operand and the right part of the operand evaluate to true otherwise false.

true and true returns true i.e. true && true = true

false and true returns false i.e. false && true = false

true and false returns false i.e. true && false = false

false and false returns false i.e. false && false = false

While the logic operator OR ( || ) returns true if either part of the operand is true: If one part of the operand is true.

true or true returns true i.e. true || true = true

false or true returns false i.e. false || true = true

true or false returns false i.e. true || false = true

false or false returns false i.e. false || false = false

Note The above logic OR symbols appear to slant forward but actually these are vertical bars ||

Notes:

      > represents greater than.

      < represents less than.

      !  represents negation  ( means contradiction or opposite of something). i.e. We return the actual opposite of something.

Solution(s):

image.png

Try the last part: There is no 'on' in both dragon and python. using the includes method that we used in solving some of the questions in Day-2

7. Use the Date object to do the following activities

The Date is a built-in objects that stores date and time. This object provides a get method that we can use to get specific date information like hours, minutes, seconds etcetera.

Date methods return the most recent date information unless we explicitly construct our own date.

image.png

  1. To get the year, we will use getFullYear() method.
  2. To get the month, we will use getMonth() method. The returned value is an index, and since we have 12 months in a year the first month: January takes 0 as its index while December takes an index of 11.
  3. To get the date, we'll use getDate() method.
  4. To get the day use getDay() method. This method also returns an index. Sunday has an index of 0, Monday 1, Tuesday 2 ... Saturday 6.
  5. To get hours, we'll use getHours() method.
  6. To get minutes, we'll use getMinutes() method.
  7. To get the number of second that have elapsed since January 1, 1970 we'll use the getTime() Method.

This method returns time in milliseconds

,then we divide the returned time by 1000 to convert it to seconds.

1000ms = 1s

Solution(s):

image.png

Exercises: Level 2

1. Write a script that prompt the user to enter base and height of the triangle and calculate an area of a triangle (area = 0.5 x b x h).

The returned value of any input area is by default a string. Even on forms. So, we need to convert it to a number first before doing the calculation.

Notes

  1. We didn't use parseInt() because the user might enter a floating point number. The value will be rounded to the nearest integer. And thus reduce the accuracy.

  2. Number() also works but treats white spaces as acceptable. You can try and submit one of the prompt values without typing anything and see the results. The JavaScript engine will treat whites spaces as a zero.

  3. Just like number, The unary operator (+) accepts white spaces.

  4. There are other methods to perform this operation like using double tiles (~~), or Multiplying our input with 1. These two aren't reliable either since they accept white spaces just like Number() and unary operator (+).

  5. Math.floor also converts a string to a number but rounds it down and it also accepts white spaces. Which is not what we want.

You can use these methods as long as you understand how they work.

In this use case, parseFloat() is the method I'll use. If we submit one empty input area, the result will be NaN. Which is correct in that sense.

Solution:

let base = prompt('Enter base: ');
let height = prompt('Enter height: ');
//The prompt input returned is a string we need to convert it to a number for arithmetic calculations
let area = 0.5 * parseFloat(base) * parseFloat(height);
console.log(area);

2. Write a script that prompt the user to enter side a, side b, and side c of the triangle and and calculate the perimeter of triangle (perimeter = a + b + c)

Solution:

let sideA = prompt('Enter side A: ');
let sideB = prompt('Enter side B: ');
let sideC = prompt('Enter side C: ');
//The prompt input returned is a string we need ot convert it to a number for arithmetic calculations
let perimeter = parseFloat(sideA) + parseFloat(sideB) + parseFloat(sideC);
console.log(perimeter);

3. Get length and width using prompt and calculate an area of rectangle (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width))

Solution:

let length = prompt('Enter length: ');
let width = prompt('Enter width: ');
//The prompt input returned is a string we need ot convert it to a number for arithmetic calculations
let perimeter = 2 * (parseFloat(length) + parseFloat(width));
let area = parseFloat(length) * parseFloat(width);
console.log(perimeter, area);

4. Get radius using prompt and calculate the area of a circle (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14.

Solution:

let radius = prompt('Enter radius: ');
let pi = Math.round(Math.PI * 100) / 100; // same as 3.14
let area = pi * parseFloat(radius) ** 2;
let circumference = 2 * pi * parseFloat(radius);
console.group(area, circumference);

5. Calculate the slope, x-intercept and y-intercept of y = 2x -2

Solution:

//we'll break the equation into small parts. y = 2x - 2
// for x-intercept replace y with 0 and then solve for x. 0 = 2x - 2
// a = 0 , b = 2x, c = -2
let a = 1,
  b = 2,
  c = -2;
//let's divide everything by a to make sure we have y alone on one side of the equation.
let a1 = a / a,
  b1 = b / a,
  c1 = c / a;
//let's negate (change the sign) the value of c.
// Then add it to both a and c. a will be zero that's why we won't need a.
// Then we divide negated c1 by b1.
let x_intercept = -c1 / b1;
console.log(x_intercept);
//for y intercept let's replace x with 0 then solve for y. y = 2(x) - 2.
// y = 2 (0) - 2. b will be zero hence we don't need it. divide c1 by b1
let y_intercept = c1 / a1; // we added c because it comes with its negative and overwrites the +
console.log(y_intercept);
// for slope. Change in y over change in x.
//we can use our x and y intercepts to calculate the slope. (x,0) (0,y)
// slope will be either (y - 0)/ (0 - x) or (0 - y)/(x - 0)
// then we round of the result to 2 decimal places just in case we have floats.
let slope = Math.round(((y_intercept - 0) / (0 - x_intercept)) * 100) / 100;
let slope1 = Math.round(((0 - y_intercept) / (x_intercept - 0)) * 100) / 100;
console.log(slope);
console.log(slope1);

image.png

Note that I used many comments in this question. They are for illustration purposes. That's not how you'll write your programs.

6. Slope is m = (y2-y1)/(x2-x1). Find the slope between point (2, 2) and point(6,10)

Solution:

image.png

7. Compare the slope of above two questions.

Their slopes are equal.

8. Calculate the value of y (y = x2 + 6x + 9). Try to use different x values and figure out at what x value y is 0.

Solution:

// you can try with different values of a, b and c.
let a = 1,
  b = 6,
  c = 9;
// part under the root.
let bSquared = Math.abs(b) ** 2;
let fourAC = 4 * a * c;
let twoA = 2 * a;
let bSquaredMinusFourAC = bSquared - fourAC;
let sqrt = Math.sqrt(bSquaredMinusFourAC);
let operation1 = Math.round(((-b + sqrt) / twoA) * 100) / 100;
let operation2 = Math.round(((-b - sqrt) / twoA) * 100) / 100;
operation1 === operation2
  ? console.log(`x = ${operation1}`)
  : console.log(`x = ${operation1} or x = ${operation2}`);
// This is a simple example. you could use regex to make it super complex to get the values of a, b, c instead of hand coding them.

9. Write a script that prompt a user to enter hours and rate per hour. Calculate pay of the person?

Solution:

let hours = prompt('Enter hours: ');
let ratePerHour = prompt('Enter rate per hour: ');
let pay = parseFloat(hours) * parseFloat(ratePerHour);
console.log(` Your pay is $${pay}`);

10. If the length of your name is greater than 7 say, your name is long else say your name is short.

Solution:

let name = prompt('Enter your name: ');
name.length > 7
  ? console.log('your name is long')
  : console.log('your name is short');
// you can use if statements as well.
// if(name.length > 7){
//   console.log('your name is long');
// }else{
//   console.log('your name is shot');
// }

11. Compare your first name length and your family name length and you should get this output.

image.png

Solution:

let firstName = 'Franklin',
  lastName = 'Mayoyo';
let length1 = firstName.length,
  length2 = lastName.length;
if (length1 > length2) {
  console.log(
    `Your first name ${firstName} is longer than your family name ${lastName}`
  );
} else if (length2 > length1) {
  console.log(
    `Your family name ${lastName} is longer than your first name ${firstName}`
  );
} else {
  console.log(
    `Your first name ${firstName} and your family name ${lastName} are equal in length`
  );
}
  1. Declare two variables myAge and yourAge and assign them initial values and myAge and yourAge.

Solution:

let myAge = 22,
  yourAge = 35;

if (myAge > yourAge) {
  console.log(`I am ${myAge - yourAge} years older than you`);
} else if (yourAge > myAge) {
  console.log(`You are ${yourAge - myAge} years older than me`);
} else {
  console.log(`we are the same age`);
}

13. Using prompt get the year the user was born and if the user is 18 or above allow the user to drive if not tell the user to wait a certain amount of years.

Solution:

let yourBirthYear = parseFloat(prompt('Enter the year you were born: '));
let age = new Date().getFullYear() - yourBirthYear;
if (age >= 18) {
  console.log(`You are ${age}. You are allowed to drive.`);
} else {
  console.log(
    `You are ${age}. You will be allowed to drive in ${18 - age} years.`
  );
}

14. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years.

Solution:

let age = parseFloat(prompt('Enter your age: '));
let remainingYears = 100 - age;
// remainingYears * 365.25days * 24hours * 60minutes * 60seconds
let remainingSeconds = remainingYears * 365.25 * 24 * 60 * 60;
console.log(
  `You have lived ${
    age * 365.25 * 24 * 60 * 60
  } seconds. You have ${remainingSeconds} seconds more to live reach 100 years`
);
// you can also use the Date object and a date constructor to calculate the number of seconds in a year. For accuracy calculate number of seconds in four years then divide your answer by 4 to get for 1 year.
//Then calculate the number of seconds in 100 years.
// or hand code this way seconds in 100 years = 100years * 365.25days * 24hours * 60minutes * 60seconds
//Find the number of seconds the user has lived.
// Find the difference. That's it.

15. Create a human readable time format using the Date time object

Capture.PNG

Solution(s):

let dateInfo = new Date();
let year = dateInfo.getFullYear();
let month = dateInfo.getMonth();
let date = dateInfo.getDate();
let hours = dateInfo.getHours();
let minutes = dateInfo.getMinutes();
// Solution 1
console.log(`${year}-${month}-${date} ${hours}:${minutes}`);
// solution 2
console.log(`${date}-${month}-${year} ${hours}:${minutes}`);
// solution 3
console.log(`${date}/${month}/${year} ${hours}:${minutes}`);

image.png

Exercises: Level 3

1. Create a human readable time format using the Date time object. The hour and the minute should be all the time two digits(7 hours should be 07 and 5 minutes should be 05 )

i. YYY-MM-DD HH:mm eg. 20120-01-02 07:05


let dateInfo = new Date();
let year = dateInfo.getFullYear();
let month = dateInfo.getMonth();
let date = dateInfo.getDate();
let hours = dateInfo.getHours();
let minutes = dateInfo.getMinutes();

function format(a) {
  if (a < 10) {
    return (a = `0${a}`);
  }
  return a;
}
let formatHours = format(hours);
let formatMinutes = format(minutes);
console.log(`${year}-${month}-${date} ${formatHours}:${formatMinutes}`);

Congratulations for making it this far. Next Day-4.