Skip to content

Assignment #320

Description

@Collinthy

// ============================================
// JAVASCRIPT ASSIGNMENTS
// ============================================

// ============================================
// VARIABLES
// ============================================

// 1. var, let, const
var bunny = "Lucy";
let dog = "Tom";
const cat = "Molly";

console.log(bunny);
console.log(dog);
console.log(cat);

// 2. Valid and invalid variable names

// 1bunny - invalid
// Correct version:
let bunny1;

// _bunny - valid
let _bunny = "Lucy";

// $bunny - valid
let $bunny = "Lucy";

// -bunny - invalid
// Correct version:
let bunnyName;

// @bunny - invalid
// Correct version:
let bunnyAt;

// bunnyName - valid
let validBunnyName = "Lucy";

console.log(bunny1, _bunny, $bunny, bunnyName, bunnyAt, validBunnyName);

// 3. Predicting var and let

console.log(pet);
var pet = "lucy";

// Output: undefined
// var is hoisted, so the variable declaration is known before execution,
// but its value is assigned only when that line is reached.

// console.log(animal);
// let animal = "tom";

// This causes a ReferenceError because let variables cannot be accessed
// before their declaration.

/*
4. Local and global variables
*/

let globalAnimal = "Bunny";

function animalName() {
let localAnimal = "Lucy";

console.log("Local variable:", localAnimal);
console.log("Global variable:", globalAnimal);
}

animalName();

// ============================================
// DATA TYPES
// ============================================

// 5. Object

const bunnyObject = {
name: "Lucy",
age: 3,
isHappy: true
};

console.log(bunnyObject.name);
console.log(bunnyObject.age);
console.log(bunnyObject.isHappy);

// 6. typeof

console.log(3.14, typeof 3.14);
console.log("Lucy", typeof "Lucy");
console.log(true, typeof true);
console.log(null, typeof null);
console.log(undefined, typeof undefined);
console.log(Symbol("Lucy"), typeof Symbol("Lucy"));
console.log({ name: "Lucy" }, typeof { name: "Lucy" });
console.log(["Lucy", "Tom"], typeof ["Lucy", "Tom"]);

// 7. Mixed data types

const mixedDataTypes = [
true,
25,
"Lucy",
null,
undefined,
{ name: "Tom" }
];

console.log(mixedDataTypes);
console.log("Length:", mixedDataTypes.length);

// ============================================
// FUNCTIONS
// ============================================

// 8. Function with no parameters

function sumBunnies() {
const blackBunnies = 10;
const whiteBunnies = 20;

return blackBunnies + whiteBunnies;
}

console.log(sumBunnies());

// 9. Function with parameters

function sumBunniesWithParameters(blackBunnies, whiteBunnies) {
return blackBunnies + whiteBunnies;
}

console.log(sumBunniesWithParameters(10, 20));
console.log(sumBunniesWithParameters(7, 3));

// 10a. Anonymous function

const anonymousSum = function (blackBunnies, whiteBunnies) {
return blackBunnies + whiteBunnies;
};

console.log(anonymousSum(10, 20));

// 10b. Arrow function

const arrowSum = (blackBunnies, whiteBunnies) => {
return blackBunnies + whiteBunnies;
};

console.log(arrowSum(10, 20));

// 11. IIFE

(function () {
const blackBunnies = 10;
const whiteBunnies = 20;

console.log("IIFE total:", blackBunnies + whiteBunnies);
})();

// ============================================
// ARRAYS
// ============================================

// 12. Array manipulation

const bunnyNames = [
"Lucy",
"Tom",
"Molly",
"Bella",
"Max",
"Charlie"
];

bunnyNames.push("Mario");
bunnyNames.unshift("Luigi");

// Remove Lucy
const lucyIndex = bunnyNames.indexOf("Lucy");

if (lucyIndex !== -1) {
bunnyNames.splice(lucyIndex, 1);
}

console.log(bunnyNames);

// 13. Array access

const bunnies = ["Lucy", "Tom", "Molly", "Bella"];

console.log("First item:", bunnies[0]);

console.log(
"Last item:",
bunnies[bunnies.length - 1]
);

console.log(
"Index of Tom:",
bunnies.indexOf("Tom")
);

const bunniesCopy = [...bunnies];

console.log("Copy:", bunniesCopy);

// 14. Loop through bunnies

for (let i = 0; i < bunnies.length; i++) {
console.log(
Bunny ${bunnies[i]} is scheduled for a checkup today.
);
}

// 15. Nested arrays

const nestedArrays = [
["Lucy", "Tom"],
["Molly", "Bella"]
];

console.log(nestedArrays[0][0]); // Lucy
console.log(nestedArrays[1][1]); // Bella

for (let i = 0; i < nestedArrays.length; i++) {
for (let j = 0; j < nestedArrays[i].length; j++) {
console.log(nestedArrays[i][j]);
}
}

// ============================================
// JSON
// ============================================

// 16. JavaScript object -> JSON

const bunnyForJSON = {
name: "Lucy",
age: 3,
isHappy: true
};

const bunnyJSON = JSON.stringify(bunnyForJSON);

console.log(bunnyJSON);

// 17. JSON -> JavaScript object

let bunnyJSON2 = '{"name":"Lucy","age":3,"isHappy":true}';

const bunnyFromJSON = JSON.parse(bunnyJSON2);

console.log(bunnyFromJSON.name);
console.log(bunnyFromJSON.age);

// ============================================
// COMPARISON OPERATORS
// ============================================

// 18. ==, ===, !=, !==

let bunny_age = 3;
let dog_age = "3";

console.log(bunny_age == dog_age); // true
console.log(bunny_age === dog_age); // false
console.log(bunny_age != dog_age); // false
console.log(bunny_age !== dog_age); // true

// == compares values after type conversion,
// while === compares both value and type.

// 19. Compare array lengths

const bunniesForComparison = [
"Lucy",
"Tom",
"Molly"
];

const dogs = [
"Max",
"Buddy",
"Charlie",
"Rocky"
];

if (bunniesForComparison.length <= dogs.length) {
console.log("There are more dogs than bunnies");
} else {
console.log("There are more bunnies than dogs");
}

// ============================================
// CONDITIONAL STATEMENTS
// ============================================

// 20a. if / else if / else

const health = "healthy";

if (health === "healthy") {
console.log("Bunny is healthy");
} else if (health === "sick") {
console.log("Bunny is sick");
} else {
console.log("Unknown health status");
}

// 20b. switch statement

switch (health) {
case "healthy":
console.log("Bunny is healthy");
break;

case "sick":
console.log("Bunny is sick");
break;

default:
console.log("Unknown health status");
}

// 20c. Ternary operator

const healthMessage =
health === "healthy" ? "Bunny is healthy" : "Bunny is not healthy";

console.log(healthMessage);

// 21. Even or odd using ternary

function evenOrOdd(number) {
return number % 2 === 0 ? "even" : "odd";
}

console.log(evenOrOdd(4));
console.log(evenOrOdd(7));
console.log(evenOrOdd(0));

// ============================================
// LOOPS
// ============================================

// 22a. for loop: 0 through 9

for (let i = 0; i <= 9; i++) {
console.log("Number", i);
}

// 22b. while loop: 0 through 9

let number = 0;

while (number <= 9) {
console.log("Number", number);
number++;
}

// 23a. while loop countdown 9 to 1

let countdown = 9;

while (countdown >= 1) {
console.log(countdown);
countdown--;
}

// 23b. for loop countdown 9 to 1

for (let i = 9; i >= 1; i--) {
console.log(i);
}

// ============================================
// EXCEPTION HANDLING AND OPERATORS
// ============================================

// 24. Error handling

function sumBunniesWithValidation(blackBunnies, whiteBunnies) {

if (
typeof blackBunnies !== "number" ||
typeof whiteBunnies !== "number"
) {
throw new Error("Both arguments must be numbers");
}

return blackBunnies + whiteBunnies;
}

try {
console.log(sumBunniesWithValidation(10, "twenty"));
} catch (error) {
console.log(error.message);
}

// 25. Operators

let blackBunnies = 10;
let whiteBunnies = 5;

const totalBunnies = blackBunnies + whiteBunnies;

console.log(
"Are black and white bunnies equal?",
blackBunnies === whiteBunnies
);

console.log("Total bunnies:", totalBunnies);

console.log(
"Are there more than 12 bunnies?",
totalBunnies > 12
);

const answer = totalBunnies > 12 ? "Yes" : "No";

console.log(answer);

// ============================================
// BRAIN TEASERS
// ============================================

// Brain Teaser 1 — The quiet loop

let carrots = 3;

while (carrots) {
console.log("munch");
carrots--;
}

/*
Output:
munch
munch
munch

The loop stops when carrots becomes 0 because 0 is falsy.

If carrots-- were deleted, carrots would remain 3 forever,
so the loop would become an infinite loop.
*/

// Brain Teaser 2 — For loop

const bunnyList = [
"Lucy",
"Tom",
"Molly",
"Bella",
"Mario",
"Luigi"
];

for (let i = 0; i < bunnyList.length; i++) {
if (bunnyList[i].length > 4) {
console.log(bunnyList[i]);
}
}

// Brain Teaser 2 — While loop

let i = 0;

while (i < bunnyList.length) {
if (bunnyList[i].length > 4) {
console.log(bunnyList[i]);
}

i++;
}

// Brain Teaser 3 — Nested checkup

const nestedBunnies = [
["Lucy", "Tom"],
["Molly", "Bella"],
["Mario", "Luigi"]
];

let count = 1;

for (let i = 0; i < nestedBunnies.length; i++) {
for (let j = 0; j < nestedBunnies[i].length; j++) {
console.log(${count}. ${nestedBunnies[i][j]});
count++;
}
}

// Brain Teaser 4 — Loop + condition + function

function countHappyBunnies(bunnies) {
let happyCount = 0;

for (let i = 0; i < bunnies.length; i++) {
if (bunnies[i].isHappy === true) {
happyCount++;
}
}

return happyCount;
}

const happyBunnies = [
{ name: "Lucy", isHappy: true },
{ name: "Tom", isHappy: false },
{ name: "Molly", isHappy: true }
];

const happyCount = countHappyBunnies(happyBunnies);

const happinessMessage =
happyCount >= happyBunnies.length / 2
? "Most bunnies are happy"
: "Most bunnies are not happy";

console.log(happinessMessage);

// Brain Teaser 5 — Snippet A

for (let i = 0; i < 5; i++) {
console.log(i);
}

// Brain Teaser 5 — Snippet B (fixed)

let j = 0;

while (j < 5) {
console.log(j);
j++;
}

/*
When to pick for vs while:

Use a for loop when you know the number/range of repetitions,
and use a while loop when repetition mainly depends on a condition.
*/// ============================================
// JAVASCRIPT ASSIGNMENTS
// ============================================

// ============================================
// VARIABLES
// ============================================

// 1. var, let, const
var bunny = "Lucy";
let dog = "Tom";
const cat = "Molly";

console.log(bunny);
console.log(dog);
console.log(cat);

// 2. Valid and invalid variable names

// 1bunny - invalid
// Correct version:
let bunny1;

// _bunny - valid
let _bunny = "Lucy";

// $bunny - valid
let $bunny = "Lucy";

// -bunny - invalid
// Correct version:
let bunnyName;

// @bunny - invalid
// Correct version:
let bunnyAt;

// bunnyName - valid
let validBunnyName = "Lucy";

console.log(bunny1, _bunny, $bunny, bunnyName, bunnyAt, validBunnyName);

// 3. Predicting var and let

console.log(pet);
var pet = "lucy";

// Output: undefined
// var is hoisted, so the variable declaration is known before execution,
// but its value is assigned only when that line is reached.

// console.log(animal);
// let animal = "tom";

// This causes a ReferenceError because let variables cannot be accessed
// before their declaration.

/*
4. Local and global variables
*/

let globalAnimal = "Bunny";

function animalName() {
let localAnimal = "Lucy";

console.log("Local variable:", localAnimal);
console.log("Global variable:", globalAnimal);
}

animalName();

// ============================================
// DATA TYPES
// ============================================

// 5. Object

const bunnyObject = {
name: "Lucy",
age: 3,
isHappy: true
};

console.log(bunnyObject.name);
console.log(bunnyObject.age);
console.log(bunnyObject.isHappy);

// 6. typeof

console.log(3.14, typeof 3.14);
console.log("Lucy", typeof "Lucy");
console.log(true, typeof true);
console.log(null, typeof null);
console.log(undefined, typeof undefined);
console.log(Symbol("Lucy"), typeof Symbol("Lucy"));
console.log({ name: "Lucy" }, typeof { name: "Lucy" });
console.log(["Lucy", "Tom"], typeof ["Lucy", "Tom"]);

// 7. Mixed data types

const mixedDataTypes = [
true,
25,
"Lucy",
null,
undefined,
{ name: "Tom" }
];

console.log(mixedDataTypes);
console.log("Length:", mixedDataTypes.length);

// ============================================
// FUNCTIONS
// ============================================

// 8. Function with no parameters

function sumBunnies() {
const blackBunnies = 10;
const whiteBunnies = 20;

return blackBunnies + whiteBunnies;
}

console.log(sumBunnies());

// 9. Function with parameters

function sumBunniesWithParameters(blackBunnies, whiteBunnies) {
return blackBunnies + whiteBunnies;
}

console.log(sumBunniesWithParameters(10, 20));
console.log(sumBunniesWithParameters(7, 3));

// 10a. Anonymous function

const anonymousSum = function (blackBunnies, whiteBunnies) {
return blackBunnies + whiteBunnies;
};

console.log(anonymousSum(10, 20));

// 10b. Arrow function

const arrowSum = (blackBunnies, whiteBunnies) => {
return blackBunnies + whiteBunnies;
};

console.log(arrowSum(10, 20));

// 11. IIFE

(function () {
const blackBunnies = 10;
const whiteBunnies = 20;

console.log("IIFE total:", blackBunnies + whiteBunnies);
})();

// ============================================
// ARRAYS
// ============================================

// 12. Array manipulation

const bunnyNames = [
"Lucy",
"Tom",
"Molly",
"Bella",
"Max",
"Charlie"
];

bunnyNames.push("Mario");
bunnyNames.unshift("Luigi");

// Remove Lucy
const lucyIndex = bunnyNames.indexOf("Lucy");

if (lucyIndex !== -1) {
bunnyNames.splice(lucyIndex, 1);
}

console.log(bunnyNames);

// 13. Array access

const bunnies = ["Lucy", "Tom", "Molly", "Bella"];

console.log("First item:", bunnies[0]);

console.log(
"Last item:",
bunnies[bunnies.length - 1]
);

console.log(
"Index of Tom:",
bunnies.indexOf("Tom")
);

const bunniesCopy = [...bunnies];

console.log("Copy:", bunniesCopy);

// 14. Loop through bunnies

for (let i = 0; i < bunnies.length; i++) {
console.log(
Bunny ${bunnies[i]} is scheduled for a checkup today.
);
}

// 15. Nested arrays

const nestedArrays = [
["Lucy", "Tom"],
["Molly", "Bella"]
];

console.log(nestedArrays[0][0]); // Lucy
console.log(nestedArrays[1][1]); // Bella

for (let i = 0; i < nestedArrays.length; i++) {
for (let j = 0; j < nestedArrays[i].length; j++) {
console.log(nestedArrays[i][j]);
}
}

// ============================================
// JSON
// ============================================

// 16. JavaScript object -> JSON

const bunnyForJSON = {
name: "Lucy",
age: 3,
isHappy: true
};

const bunnyJSON = JSON.stringify(bunnyForJSON);

console.log(bunnyJSON);

// 17. JSON -> JavaScript object

let bunnyJSON2 = '{"name":"Lucy","age":3,"isHappy":true}';

const bunnyFromJSON = JSON.parse(bunnyJSON2);

console.log(bunnyFromJSON.name);
console.log(bunnyFromJSON.age);

// ============================================
// COMPARISON OPERATORS
// ============================================

// 18. ==, ===, !=, !==

let bunny_age = 3;
let dog_age = "3";

console.log(bunny_age == dog_age); // true
console.log(bunny_age === dog_age); // false
console.log(bunny_age != dog_age); // false
console.log(bunny_age !== dog_age); // true

// == compares values after type conversion,
// while === compares both value and type.

// 19. Compare array lengths

const bunniesForComparison = [
"Lucy",
"Tom",
"Molly"
];

const dogs = [
"Max",
"Buddy",
"Charlie",
"Rocky"
];

if (bunniesForComparison.length <= dogs.length) {
console.log("There are more dogs than bunnies");
} else {
console.log("There are more bunnies than dogs");
}

// ============================================
// CONDITIONAL STATEMENTS
// ============================================

// 20a. if / else if / else

const health = "healthy";

if (health === "healthy") {
console.log("Bunny is healthy");
} else if (health === "sick") {
console.log("Bunny is sick");
} else {
console.log("Unknown health status");
}

// 20b. switch statement

switch (health) {
case "healthy":
console.log("Bunny is healthy");
break;

case "sick":
console.log("Bunny is sick");
break;

default:
console.log("Unknown health status");
}

// 20c. Ternary operator

const healthMessage =
health === "healthy" ? "Bunny is healthy" : "Bunny is not healthy";

console.log(healthMessage);

// 21. Even or odd using ternary

function evenOrOdd(number) {
return number % 2 === 0 ? "even" : "odd";
}

console.log(evenOrOdd(4));
console.log(evenOrOdd(7));
console.log(evenOrOdd(0));

// ============================================
// LOOPS
// ============================================

// 22a. for loop: 0 through 9

for (let i = 0; i <= 9; i++) {
console.log("Number", i);
}

// 22b. while loop: 0 through 9

let number = 0;

while (number <= 9) {
console.log("Number", number);
number++;
}

// 23a. while loop countdown 9 to 1

let countdown = 9;

while (countdown >= 1) {
console.log(countdown);
countdown--;
}

// 23b. for loop countdown 9 to 1

for (let i = 9; i >= 1; i--) {
console.log(i);
}

// ============================================
// EXCEPTION HANDLING AND OPERATORS
// ============================================

// 24. Error handling

function sumBunniesWithValidation(blackBunnies, whiteBunnies) {

if (
typeof blackBunnies !== "number" ||
typeof whiteBunnies !== "number"
) {
throw new Error("Both arguments must be numbers");
}

return blackBunnies + whiteBunnies;
}

try {
console.log(sumBunniesWithValidation(10, "twenty"));
} catch (error) {
console.log(error.message);
}

// 25. Operators

let blackBunnies = 10;
let whiteBunnies = 5;

const totalBunnies = blackBunnies + whiteBunnies;

console.log(
"Are black and white bunnies equal?",
blackBunnies === whiteBunnies
);

console.log("Total bunnies:", totalBunnies);

console.log(
"Are there more than 12 bunnies?",
totalBunnies > 12
);

const answer = totalBunnies > 12 ? "Yes" : "No";

console.log(answer);

// ============================================
// BRAIN TEASERS
// ============================================

// Brain Teaser 1 — The quiet loop

let carrots = 3;

while (carrots) {
console.log("munch");
carrots--;
}

/*
Output:
munch
munch
munch

The loop stops when carrots becomes 0 because 0 is falsy.

If carrots-- were deleted, carrots would remain 3 forever,
so the loop would become an infinite loop.
*/

// Brain Teaser 2 — For loop

const bunnyList = [
"Lucy",
"Tom",
"Molly",
"Bella",
"Mario",
"Luigi"
];

for (let i = 0; i < bunnyList.length; i++) {
if (bunnyList[i].length > 4) {
console.log(bunnyList[i]);
}
}

// Brain Teaser 2 — While loop

let i = 0;

while (i < bunnyList.length) {
if (bunnyList[i].length > 4) {
console.log(bunnyList[i]);
}

i++;
}

// Brain Teaser 3 — Nested checkup

const nestedBunnies = [
["Lucy", "Tom"],
["Molly", "Bella"],
["Mario", "Luigi"]
];

let count = 1;

for (let i = 0; i < nestedBunnies.length; i++) {
for (let j = 0; j < nestedBunnies[i].length; j++) {
console.log(${count}. ${nestedBunnies[i][j]});
count++;
}
}

// Brain Teaser 4 — Loop + condition + function

function countHappyBunnies(bunnies) {
let happyCount = 0;

for (let i = 0; i < bunnies.length; i++) {
if (bunnies[i].isHappy === true) {
happyCount++;
}
}

return happyCount;
}

const happyBunnies = [
{ name: "Lucy", isHappy: true },
{ name: "Tom", isHappy: false },
{ name: "Molly", isHappy: true }
];

const happyCount = countHappyBunnies(happyBunnies);

const happinessMessage =
happyCount >= happyBunnies.length / 2
? "Most bunnies are happy"
: "Most bunnies are not happy";

console.log(happinessMessage);

// Brain Teaser 5 — Snippet A

for (let i = 0; i < 5; i++) {
console.log(i);
}

// Brain Teaser 5 — Snippet B (fixed)

let j = 0;

while (j < 5) {
console.log(j);
j++;
}

/*
When to pick for vs while:

Use a for loop when you know the number/range of repetitions,
and use a while loop when repetition mainly depends on a condition.
*/

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions