Problem1:
1. Log "Hello, JavaScript!" to the console in 3 different ways.
Solution:
console.log("Hello, JavaScript!");
console.info("Hello, JavaScript!");
console.warn("Hello, JavaScript!");
console.error("Hello, JavaScript!");
console.table([{ Message: "Hello, JavaScript!" }]);
Problem2:
2. Perform 35 * 2 - (10 / 2) + 7 and log the result.
Solution:
console.log(35 * 2 - (10 / 2) + 7);
Problem3:
3. Log the data type of "123", 123, true, and null using typeof.
Solution:
console.log(typeof "123");
console.log(typeof 123);
console.log(typeof true);
console.log(typeof null);
Problem4:
4. Write a program that swaps the values of two variables.
Solution:
// Method 1: Using a temporary variable
let a = 5, b = 10;
let temp = a;
a = b;
b = temp;
console.log(a, b);
// Method 2: Using destructuring assignment
let x = 5, y = 10;
[x, y] = [y, x];
console.log(x, y);
// Method 3: Using arithmetic operations
let p = 5, q = 10;
p = p + q;
q = p - q;
p = p - q;
console.log(p, q);
Problem5:
5. Use console.group() to organize logs into a group.
Solution:
console.group("User Info");
console.log("Name: John Doe");
console.log("Age: 25");
console.log("Location: New York");
console.groupEnd();
Problem6:
6. Declare a const object, modify its properties, and log the updated object.
Solution:
const person = { name: "Alice", age: 30, city: "Paris" };
person.age = 31;
person.city = "London";
console.log(person); //{ name: "Alice", age: 31, city: "London" }
Problem7:
7. Convert "50" (string) into a number using all different methods.
Solution:
console.log(Number("50"));
console.log(parseInt("50"));
console.log(parseFloat("50"));
console.log(+"50");
console.log("50" * 1);
console.log("50" / 1);
console.log("50" - 0);
console.log("50" | 0);
Problem8:
8. Check if "JavaScript" contains "Script" without using .includes().
Solution:
console.log("JavaScript".indexOf("Script") !== -1); //true
console.log("JavaScript".search("Script") !== -1); //true
console.log(/Script/.test("JavaScript")); //true
Problem9:
9. Create an array of 5 numbers and log the sum using .reduce().
Solution:
const numbers = [10, 20, 30, 40, 50];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); //150
Problem10:
10. Explain the difference between undefined, null, and NaN with examples.
Solution:
| Type | Description | Example |
|---|---|---|
| undefined | A variable declared but not assigned a value. | let x; console.log(x); // undefined |
| null | An intentional absence of a value. | let y = null; console.log(y); // null |
| NaN | "Not-a-Number", occurs in invalid math ops. | console.log("abc" / 2); // NaN |