JavaScript Exercises - Chapter 4

Exercise 1: Understanding JavaScript Variables and Data Types

Instructions:

1. Declare a constant variable PI with a value of 3.14159.

2. Declare a variable radius and set it to 5.

3. Calculate the area of a circle (PI * radius * radius) and store it in a variable area.

4. Print the result using console.log().

5. Change radius to 7 and update area accordingly.

Output:
Area of the circle: 78.53975
Updated area: 153.93791

Exercise 2: Conditionals and User Input

Instructions:

1. Ask the user for their age using prompt().

2. If the user is under 18, print "You are a minor."

3. If the user is 18 or older, print "You are an adult."

4. Use a ternary operator to store the message in a variable and then print it.

Output:
User input: 16
Output: "You are a minor."

User input: 20
Output: "You are an adult."

Exercise 3: Loops and Arrays

Instructions:

1. Create an array of five city names.

2. Use a for loop to print each city using console.log().

3. Use a while loop to display the cities using document.write().

Output:
console.log Output:
New York
London
Tokyo
Paris
Sydney

document.write Output:
New York, London, Tokyo, Paris, Sydney

Exercise 4: Array Methods & Destructuring

Instructions:

1. Create an array of programming languages: ["JavaScript", "Python", "C++", "Java"]

2. Use array destructuring to extract the first two elements into variables.

3. Use the .map() method to convert all languages to uppercase.

4. Use .filter() to create a new array containing only languages with more than 4 letters.

Output:
console.log Output:
First language: JavaScript
Second language: Python
Uppercase languages: ["JAVASCRIPT", "PYTHON", "C++", "JAVA"]
Filtered languages: ["JavaScript", "Python"]

Exercise 5: Working with Functions

Instructions:

1. Write a function multiply(a, b) that returns the product of two numbers.

2. Modify the function to use default parameters, so if no values are passed, it defaults to a = 2 and b = 3.

3. Call the function with and without arguments and print the results.

Output:
console.log(multiply(4, 5));  // Output: 20
console.log(multiply());      // Output: 6 (default values used)

Exercise 6: Objects and JSON

Instructions:

1. Create an object student with the properties:

2. Convert the object to a JSON string and print it using console.log().

Output:
console.log Output:
Alice is 21 years old and studies Math, Physics, and Computer Science.
{"name":"Alice","age":21,"courses":["Math","Physics","Computer Science"]}

Bonus Challenge: Error Handling

Instructions:

1. Write a function that takes a number and returns its square root.

2. Use try...catch to handle errors when passing invalid inputs (like a string).

3. If an error occurs, print "Invalid input" instead of crashing.

Output:
console.log(squareRoot(16));  // Output: 4
console.log(squareRoot("ABC"));  // Output: "Invalid input"