Output
Output
Table of Contents
Phase 1: Foundation Knowledge (Chapters 1-3)
What is a Computer?
A computer is like a very smart calculator that can follow instructions. Just like how
you might follow a recipe to bake cookies, a computer follows instructions called
"code" to do things.
Key Parts of a Computer: - Screen (Monitor): Where you see things - Keyboard:
Where you type - Mouse: How you point and click - Brain (CPU): The part that
thinks and follows instructions - Memory (RAM): Where the computer remembers
things temporarily - Storage (Hard Drive): Where the computer saves things
permanently
The Internet is like a giant library where computers can talk to each other and share
information. When you visit a website, your computer is asking another computer
(called a "server") to send you a web page.
Think of it like this: - You want to read a book (website) - You ask the librarian
(server) for the book - The librarian finds the book and gives it to you - You can now
read the book on your computer
What is a Web Browser?
A web browser is a special program that helps you look at websites. It's like a window
that shows you web pages. Common browsers include: - Chrome - Firefox - Safari -
Edge
Practice Exercise 1.1: Open your web browser and visit at least 3 different websites.
Notice how each one looks different but they all work in your browser.
Every web page is made of three main parts: 1. HTML - The structure (like the
skeleton of a house) 2. CSS - The style (like the paint and decorations) 3. JavaScript
- The behavior (like the lights and doors that work)
HTML stands for "HyperText Markup Language." It's like the blueprint for a web
page. It tells the browser what parts go where.
html
<!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>Welcome to My Website!</h1>
<p>This is my first paragraph.</p>
<button>Click Me!</button>
</body>
</html>
CSS stands for "Cascading Style Sheets." It makes web pages look pretty by
controlling colors, sizes, and positions.
p {
color: green;
}
button {
background-color: yellow;
padding: 10px;
}
HTML creates the parts, and CSS makes them look good. But neither one can make
the page interactive - that's where JavaScript comes in!
Practice Exercise 2.1: Create a simple HTML file with a heading, a paragraph, and a
button. Don't worry about making it work yet - we'll learn that with JavaScript!
What is JavaScript?
JavaScript is a programming language that makes web pages interactive. It's what
makes buttons work, forms submit, and websites respond to what you do.
JavaScript is NOT Java! They're completely different languages that just happen to
have similar names.
Without JavaScript, websites would be like books - you could read them, but you
couldn't interact with them. JavaScript lets you: - Click buttons and have things
happen - Fill out forms and submit them - Play games - Chat with friends - Watch
videos - And much more!
A Brief History of JavaScript
• Python: Great for beginners, often used for science and data
• Java: Used for big business applications
• C++: Used for video games and system programming
• JavaScript: The only language that runs in web browsers by default
Practice Exercise 3.1: Think of 5 websites you use regularly. For each one, write
down 3 things that happen when you click or interact with the page. All of those
interactions are powered by JavaScript!
Recommended editors: - Visual Studio Code (VS Code): Free, powerful, and
beginner-friendly - Sublime Text: Fast and simple - Atom: Easy to use with lots of
plugins
Every browser has built-in developer tools. To open them: - Chrome/Edge: Press
F12 or Ctrl+Shift+I - Firefox: Press F12 or Ctrl+Shift+I - Safari: Press Cmd+Option+I
The Console Tab: This is where you can type JavaScript code and see it run
immediately!
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning JavaScript</title>
</head>
<body>
<h1>My JavaScript Learning Journey</h1>
<script src="script.js"></script>
</body>
</html>
Practice Exercise 4.1: Set up your development environment and create your first
HTML file. Open it in your browser and make sure you can see the heading.
Practice Exercise 4.2: Open your browser's developer tools and find the Console
tab. Type 2 + 2 and press Enter. You just ran your first JavaScript code!
Let's start with the most traditional first program: "Hello, World!"
In your script.js file:
javascript
console.log("Hello, World!");
What does this do? - console.log() is a function that displays text in the browser's
console - The text inside the parentheses and quotes is what gets displayed
The console is like a communication channel between your code and you. It's where:
- Your program can show you messages - You can see error messages - You can test
small pieces of code
Comments in JavaScript
Comments are notes you write in your code that don't run. They help you remember
what your code does.
javascript
// This is a single-line comment
console.log("Hello, World!"); // This comment is at the end of a line
/*
This is a multi-line comment
You can write multiple lines here
Very useful for longer explanations
*/
1. In the Console:
javascript
console.log("This runs in the console");
2. Alert Boxes:
javascript
alert("This shows a popup message");
javascript
document.write("This writes directly to the page");
javascript
document.getElementById("demo").innerHTML = "This changes HTML content";
Create a script that displays three different messages: 1. One in the console 2. One
in an alert box 3. One written to the page
Write a script that introduces you with your name, age, and favorite color using
console.log.
Take your introduction script and add comments explaining what each line does.
Mini-Quiz 5.1
Variables are like boxes where you can store information. You can put things in the
box, look at what's in the box, and even change what's in the box.
Think of variables like: - A labeled box where you store toys - A parking space with
a number - A locker at school with your name on it
javascript
var myName = "Alex";
var myAge = 25;
javascript
let myName = "Alex";
let myAge = 25;
javascript
const myBirthday = "January 1st";
const pi = 3.14159;
Rules you MUST follow: - Must start with a letter, underscore (_), or dollar sign ($) -
Cannot start with a number - Cannot contain spaces - Cannot use reserved words
(like if, for, function)
javascript
let firstName = "John";
let age = 25;
let isStudent = true;
let totalScore = 100;
javascript
let 1name = "John"; // Can't start with number
let first name = "John"; // Can't have spaces
let if = "John"; // Can't use reserved words
javascript
let myFavoriteColor = "blue";
let numberOfPets = 3;
let isLoggedIn = true;
javascript
// Good
let userEmail = "[email protected]";
let shoppingCartTotal = 29.99;
// Bad
let x = "[email protected]";
let y = 29.99;
javascript
let score = 0;
console.log(score); // Shows: 0
score = 10;
console.log(score); // Shows: 10
score = score + 5;
console.log(score); // Shows: 15
The Difference Between let, var, and const
javascript
let temperature = 72;
temperature = 75; // This is okay
javascript
const myName = "Alex";
myName = "Bob"; // This will cause an error!
javascript
var oldVariable = "I'm old-fashioned";
Understanding Assignment
The = sign in programming doesn't mean "equals" like in math. It means "assign" or
"store."
javascript
let x = 5; // "Store the value 5 in variable x"
x = x + 1; // "Add 1 to x and store the result back in x"
Create variables for: 1. Your first name 2. Your age 3. Your favorite number 4.
Whether you like pizza (true or false)
Create a program that stores and displays: - Your name (use const because it won't
change) - Your age (use let because it changes every year) - Your grade in school
(use let) - Your favorite subject (use const)
Mini-Quiz 6.1
Data types are different categories of information, like how we have different types
of containers for different things: - A glass for water - A bowl for soup - A plate for
food
javascript
let age = 25;
let price = 19.99;
let temperature = -5;
let bigNumber = 1000000;
javascript
let infinity = Infinity;
let notANumber = NaN; // "Not a Number"
String quotes: - Use double quotes: "Hello" - Use single quotes: 'Hello' - Use
template literals: `Hello`
javascript
let isRaining = true;
let isSchoolDay = false;
let hasHomework = true;
4. Undefined Undefined means a variable has been created but no value has been
assigned.
javascript
let something;
console.log(something); // Shows: undefined
javascript
let data = null; // Intentionally empty
javascript
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
javascript
let firstName = "John";
let lastName = "Doe";
// String length
console.log(fullName.length); // 8
// Making uppercase/lowercase
console.log(fullName.toUpperCase()); // "JOHN DOE"
console.log(fullName.toLowerCase()); // "john doe"
Template literals use backticks (`) and allow you to insert variables easily:
javascript
let name = "Sarah";
let age = 16;
// Old way
let message1 = "Hi, I'm " + name + " and I'm " + age + " years old.";
Converting to Number:
javascript
let stringNumber = "25";
let realNumber = Number(stringNumber);
console.log(realNumber + 5); // 30
Converting to String:
javascript
let number = 42;
let text = String(number);
console.log(text + " is my favorite number"); // "42 is my favorite number"
Converting to Boolean:
javascript
let zero = 0;
let empty = "";
let something = "hello";
console.log(Boolean(zero)); // false
console.log(Boolean(empty)); // false
console.log(Boolean(something)); // true
javascript
// This might surprise you!
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (number subtraction)
console.log("5" * 3); // 15 (number multiplication)
Create variables of each data type and use typeof to check them: 1. A number 2. A
string 3. A boolean 4. An undefined variable 5. A null variable
Practice Exercise 7.2: Calculator
Create a Mad Libs game using template literals: 1. Create variables for a name,
adjective, noun, and verb 2. Use template literals to create a funny sentence 3.
Display the result
Mini-Quiz 7.1
Operators are symbols that tell JavaScript to perform specific operations. They're
like the buttons on a calculator or the action words in a sentence.
Arithmetic Operators
javascript
let a = 10;
let b = 3;
javascript
console.log(10 % 3); // 1 (10 ÷ 3 = 3 remainder 1)
console.log(15 % 4); // 3 (15 ÷ 4 = 3 remainder 3)
console.log(20 % 5); // 0 (20 ÷ 5 = 4 remainder 0)
Assignment Operators
javascript
let x = 10; // Basic assignment
// Pre-increment vs Post-increment
let a = 5;
let b = ++a; // Pre-increment: a becomes 6, then b gets 6
console.log(a, b); // 6, 6
let c = 5;
let d = c++; // Post-increment: d gets 5, then c becomes 6
console.log(c, d); // 6, 5
Comparison Operators
javascript
let a = 10;
let b = 5;
Equality: == vs ===
javascript
console.log(5 == "5"); // true (converts string to number)
console.log(true == 1); // true (converts boolean to number)
console.log(null == undefined); // true
Best Practice: Always use === and !== unless you specifically need type conversion.
Logical Operators
javascript
let isRaining = true;
let hasUmbrella = false;
javascript
console.log(Boolean("hello")); // true
console.log(Boolean(42)); // true
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Boolean("")); // false
console.log(Boolean(0)); // false
String Operators
javascript
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // "John Doe"
Operator Precedence
javascript
let result = 5 + 3 * 2; // Multiplication first: 5 + 6 = 11
console.log(result); // 11
Create a calculator that: 1. Stores two numbers 2. Performs all arithmetic operations
3. Displays the results with descriptive messages
Create variables for your age and your friend's age, then compare them using all
comparison operators.
Practice Exercise 8.3: Logical Thinking
Create a program that checks if it's a good day to go to the beach: - It's sunny (true/
false) - Temperature is above 75°F - It's not raining - Use logical operators to
determine if it's a good beach day
Create a program that checks if a number is even or odd using the modulo operator.
Create a program that: 1. Stores test scores for 3 tests 2. Calculates the average 3.
Determines if the student passed (average >= 70)
Mini-Quiz 8.1
Control flow is how your program makes decisions and chooses what to do next. It's
like following a recipe that has different steps depending on what ingredients you
have.
Think of it like: - If it's raining, take an umbrella - If you're hungry, eat something - If
you finished your homework, you can play games
The if Statement
javascript
let temperature = 75;
if (temperature > 70) {
console.log("It's a nice day!");
}
How it works: 1. JavaScript checks if the condition is true 2. If true, it runs the code
inside the {} 3. If false, it skips that code
Sometimes you want to do one thing if the condition is true, and something else if
it's false:
javascript
let age = 16;
javascript
let grade = 85;
Nested if Statements
javascript
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week");
break;
case "Tuesday":
console.log("Tuesday blues");
break;
case "Wednesday":
console.log("Hump day!");
break;
case "Thursday":
console.log("Almost Friday");
break;
case "Friday":
console.log("TGIF!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Not a valid day");
}
Important: Don't forget the break statements! Without them, the code keeps
running through all the cases.
The Ternary Operator (Conditional Operator)
javascript
let age = 20;
// Long way
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}
Combining Conditions
javascript
let age = 25;
let hasLicense = true;
let hasInsurance = true;
if (isWeekend || isHoliday) {
console.log("No school today!");
} else {
console.log("Time for school.");
}
Loops - Repeating Actions
What are Loops? Loops let you repeat code multiple times without writing it over
and over. It's like telling someone "do this 10 times" instead of saying "do this" 10
separate times.
javascript
// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
How it works: 1. let i = 1 - Start with i = 1 2. i <= 5 - Keep going while i is 5 or less
3. i++ - Add 1 to i after each loop
Use when you don't know exactly how many times to repeat:
javascript
let count = 1;
do {
userInput = prompt("Enter 'quit' to exit:");
console.log("You entered: " + userInput);
} while (userInput !== "quit");
javascript
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Exit the loop when i equals 5
}
console.log(i);
}
// Output: 1, 2, 3, 4
javascript
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip when i equals 3
}
console.log(i);
}
// Output: 1, 2, 4, 5
Nested Loops
javascript
for (let row = 1; row <= 3; row++) {
for (let col = 1; col <= 3; col++) {
console.log(`Row ${row}, Column ${col}`);
}
}
1. Counting up:
javascript
for (let i = 0; i < 10; i++) {
console.log(i);
}
2. Counting down:
javascript
for (let i = 10; i > 0; i--) {
console.log(i);
}
3. Counting by twos:
javascript
for (let i = 0; i <= 10; i += 2) {
console.log(i); // 0, 2, 4, 6, 8, 10
}
Create a simple number guessing game: 1. Pick a secret number between 1 and 10 2.
Ask the user to guess 3. Tell them if their guess is too high, too low, or correct 4. Use
a loop to let them keep guessing
Create a program that prints the multiplication table for a given number:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
... and so on
Create the classic FizzBuzz program: 1. Count from 1 to 100 2. If the number is
divisible by 3, print "Fizz" 3. If divisible by 5, print "Buzz" 4. If divisible by both 3 and
5, print "FizzBuzz" 5. Otherwise, print the number
Mini-Quiz 9.1
Functions are like recipes - they're a set of instructions that you can use over and
over again. Instead of writing the same code multiple times, you create a function
once and then "call" it whenever you need it.
Think of functions like: - A recipe you can follow to make cookies - A machine that
takes inputs and gives outputs - A magic spell that does something when you say its
name
Function Declaration:
javascript
function sayHello() {
console.log("Hello, World!");
}
javascript
function greet(name) {
console.log("Hello, " + name + "!");
}
Multiple Parameters
javascript
function introduce(name, age, city) {
console.log(`Hi, I'm ${name}. I'm ${age} years old and I live in ${city}.`);
}
Return Values
javascript
function add(a, b) {
return a + b;
}
Function Expressions
javascript
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // 20
javascript
// Traditional function
function square(x) {
return x * x;
}
// Arrow function
const square = (x) => {
return x * x;
};
console.log(square(4)); // 16
Default Parameters
javascript
function greet(name = "Friend") {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Hello, Alice!
greet(); // Hello, Friend!
Variables inside functions are "local" - they only exist inside the function:
javascript
let globalVar = "I'm global";
function myFunction() {
let localVar = "I'm local";
console.log(globalVar); // Can access global variables
console.log(localVar); // Can access local variables
}
myFunction();
console.log(globalVar); // Works fine
console.log(localVar); // Error! localVar doesn't exist here
Function Hoisting
Function declarations are "hoisted" - you can call them before they're defined:
javascript
sayHi(); // This works!
function sayHi() {
console.log("Hi there!");
}
javascript
sayBye(); // This causes an error!
Recursive Functions
javascript
function countdown(n) {
if (n <= 0) {
console.log("Blast off!");
return;
}
console.log(n);
countdown(n - 1); // Function calls itself
}
Anonymous Functions
javascript
// Using an anonymous function with setTimeout
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
1. Calculator Functions:
javascript
function calculate(operation, a, b) {
switch(operation) {
case "add":
return a + b;
case "subtract":
return a - b;
case "multiply":
return a * b;
case "divide":
return a / b;
default:
return "Invalid operation";
}
}
2. Validation Functions:
javascript
function isValidEmail(email) {
return email.includes("@") && email.includes(".");
}
function isValidAge(age) {
return age >= 0 && age <= 120;
}
console.log(isValidEmail("[email protected]")); // true
console.log(isValidAge(25)); // true
3. Utility Functions:
javascript
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
Create functions that: 1. Format a full name (first + last) 2. Calculate age from birth
year 3. Create a profile summary using the other functions
Create functions for a simple game: 1. Generate a random number 2. Check if a guess
is correct 3. Keep track of attempts 4. Display game status
Mini-Quiz 10.1
Arrays are like containers that can hold multiple pieces of information in order.
Think of them as: - A shopping list with multiple items - A playlist with multiple
songs - A box with multiple toys, each in a numbered slot
Creating Arrays
javascript
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = ["hello", 42, true, "world"];
let empty = [];
Array Constructor:
javascript
let colors = new Array("red", "green", "blue");
let scores = new Array(5); // Creates array with 5 empty slots
javascript
let fruits = ["apple", "banana", "orange"];
javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 3
javascript
let fruits = ["apple", "banana", "orange"];
fruits[1] = "grape";
console.log(fruits); // ["apple", "grape", "orange"]
javascript
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
javascript
let fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "orange"]
javascript
let fruits = ["apple", "banana", "orange"];
let firstFruit = fruits.shift();
console.log(firstFruit); // "apple"
console.log(fruits); // ["banana", "orange"]
javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.indexOf("banana")); // 1
console.log(fruits.indexOf("grape")); // -1 (not found)
javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false
javascript
let fruits = ["apple", "banana", "orange"];
javascript
let fruits = ["apple", "banana", "orange"];
fruits.forEach(function(fruit, index) {
console.log(index + ": " + fruit);
});
Array Methods
javascript
let fruits = ["apple", "banana", "orange"];
let fruitString = fruits.join(", ");
console.log(fruitString); // "apple, banana, orange"
javascript
let sentence = "Hello world from JavaScript";
let words = sentence.split(" ");
console.log(words); // ["Hello", "world", "from", "JavaScript"]
Reversing an array:
javascript
let numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1]
Sorting an array:
javascript
let fruits = ["banana", "apple", "orange"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "orange"]
Slicing Arrays
javascript
let fruits = ["apple", "banana", "orange", "grape", "kiwi"];
let someFruits = fruits.slice(1, 3);
console.log(someFruits); // ["banana", "orange"]
console.log(fruits); // Original array unchanged
Splicing Arrays
javascript
let fruits = ["apple", "banana", "orange"];
Combining Arrays
Using concat:
javascript
let fruits = ["apple", "banana"];
let vegetables = ["carrot", "broccoli"];
let food = fruits.concat(vegetables);
console.log(food); // ["apple", "banana", "carrot", "broccoli"]
javascript
let fruits = ["apple", "banana"];
let vegetables = ["carrot", "broccoli"];
let food = [...fruits, ...vegetables];
console.log(food); // ["apple", "banana", "carrot", "broccoli"]
Multi-dimensional Arrays
javascript
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
javascript
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
javascript
let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
javascript
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
javascript
let numbers = [5, 2, 8, 1, 9];
let max = Math.max(...numbers);
let min = Math.min(...numbers);
console.log(max); // 9
console.log(min); // 1
2. Removing duplicates:
javascript
let numbers = [1, 2, 2, 3, 3, 3, 4];
let unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4]
3. Flattening arrays:
javascript
let nested = [[1, 2], [3, 4], [5, 6]];
let flat = nested.flat();
console.log(flat); // [1, 2, 3, 4, 5, 6]
Create a shopping list application: 1. Create an array for your shopping list 2. Add
items to the list 3. Remove items when "bought" 4. Display the current list 5. Check if
a specific item is on the list
Practice Exercise 11.2: Grade Book
Create a grade book system: 1. Store student grades in an array 2. Calculate the
average grade 3. Find the highest and lowest grades 4. Count how many students
passed (grade >= 70)
Create a to-do list manager: 1. Add tasks to the list 2. Mark tasks as complete 3.
Remove completed tasks 4. Display remaining tasks 5. Show statistics (total tasks,
completed, remaining)
Create a program that analyzes an array of numbers: 1. Find even and odd numbers
2. Calculate sum and average 3. Find numbers greater than the average 4. Sort
numbers in ascending and descending order
Create word game functions: 1. Find the longest word in an array 2. Count words
that start with a specific letter 3. Create rhyming pairs 4. Sort words alphabetically
Mini-Quiz 11.1
Objects are like containers that hold related information together. Think of them as:
- A person's profile with name, age, and hobbies - A car with make, model, year, and
color - A book with title, author, pages, and genre
Unlike arrays that store items in order, objects store information in key-value pairs.
Creating Objects
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
city: "New York"
};
Empty object:
javascript
let emptyObject = {};
Dot notation:
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
console.log(person.firstName); // "John"
console.log(person.age); // 25
Bracket notation:
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
console.log(person["firstName"]); // "John"
console.log(person["age"]); // 25
javascript
let person = {
firstName: "John",
lastName: "Doe"
};
console.log(person); // {firstName: "John", lastName: "Doe", age: 26, city: "New York"}
Removing Properties
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
city: "New York"
};
delete person.city;
console.log(person); // {firstName: "John", lastName: "Doe", age: 25}
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
// Method to introduce
introduce: function() {
return "Hi, I'm " + this.getFullName() + " and I'm " + this.age + " years old.";
}
};
javascript
let car = {
brand: "Toyota",
model: "Camry",
year: 2020,
getInfo: function() {
return this.brand + " " + this.model + " (" + this.year + ")";
}
};
javascript
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.getFullName = function() {
return this.firstName + " " + this.lastName;
};
}
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
Using Object.keys():
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
Object.keys(person).forEach(key => {
console.log(key + ": " + person[key]);
});
Nested Objects
javascript
let person = {
firstName: "John",
lastName: "Doe",
address: {
street: "123 Main St",
city: "New York",
zipCode: "10001"
},
hobbies: ["reading", "swimming", "coding"]
};
Arrays of Objects
javascript
let students = [
{
name: "Alice",
grade: 85,
subject: "Math"
},
{
name: "Bob",
grade: 92,
subject: "Science"
},
{
name: "Charlie",
grade: 78,
subject: "English"
}
];
console.log(topStudent.name); // "Bob"
javascript
let person = {
firstName: "John",
lastName: "Doe"
};
Copying objects:
javascript
let person = {
firstName: "John",
lastName: "Doe"
};
// Shallow copy
let copy1 = Object.assign({}, person);
let copy2 = {...person}; // Spread operator
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
1. Configuration objects:
javascript
let gameConfig = {
playerName: "Player1",
difficulty: "medium",
soundEnabled: true,
controls: {
up: "W",
down: "S",
left: "A",
right: "D"
}
};
2. Data models:
javascript
let product = {
id: 1,
name: "Laptop",
price: 999.99,
inStock: true,
category: "Electronics",
getDisplayPrice: function() {
return "$" + this.price.toFixed(2);
}
};
Create a personal profile object with: 1. Basic information (name, age, city) 2.
Hobbies array 3. Methods to introduce yourself 4. Method to add/remove hobbies
Create a library system with: 1. Book objects (title, author, pages, available) 2.
Methods to check out/return books 3. Search functionality 4. Display book
information