0% found this document useful (0 votes)
18 views

Objects in JS

s3

Uploaded by

Shreyas Gowda
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Objects in JS

s3

Uploaded by

Shreyas Gowda
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

//DAY-2

Constructor function for creating Person objects:


function Person(name, age) {
this.name = name;
this.age = age;
}

// Creating instances of Person objects


const john = new Person('John', 30);
const jane = new Person('Jane', 25);

console.log(john.name); // Output: 'John'


console.log(jane.age); // Output: 25

..........................................................

Object literals: Object literals provide a simple way to create objects by


enclosing key-value pairs within curly braces.

object literals is a comma-separated list of name-value pairs enclosed in a curly


braces.

For example:
const person = {
name: 'John',
age: 30,
isStudent: true
};

console.log(person.name);
console.log(person['age'])

........................................
const person = {
name: 'John',
age: 30,
email: '[email protected]',
child: {
address: {
street: '123 Main St',
city: 'Cityville',
state: 'State'
}
},
hobbies: ['reading', 'painting', 'swimming'],
sayHello: function() {
console.log('Hello!');
}
};

console.log(person.name); // Output: 'John'


console.log(person.age); // Output: 30
console.log(person.email); // Output: '[email protected]'
console.log(person.child.address.street); // Output: '123 Main St'
console.log(person.child.address.city); // Output: 'Cityville'
console.log(person.child.address.state); // Output: 'State'
console.log(person.hobbies); // Output: ['reading', 'painting', 'swimming']
person.sayHello(); // Output: 'Hello!'

Filtering hobbies:

const filteredHobbies = person.hobbies.filter(hobby => hobby.length > 6);


Output: ["painting", "swimming"]

Mapping hobbies to uppercase:

const uppercaseHobbies = person.hobbies.map(hobby => hobby.toUpperCase());


Output: ["READING", "PAINTING", "SWIMMING"]

Reducing the age of the person:

const totalAge = person.age.reduce((sum, age) => sum + age, 0);

...............................................
Destructuring :

Destructuring is a feature introduced in JavaScript that allows you to extract


values from arrays or properties from objects and assign them to variables in a
concise and convenient way

Destructuring Arrays:

const numbers = [1, 2, 3, 4, 5];

// Destructuring array
const [a, b, ...rest] = numbers;

console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(rest); // Output: [3, 4, 5]

...........................................

Destructuring Objects:

const person = {
name: 'John',
age: 30,
city: 'New York'
};

// Destructuring object
const { name, age, city } = person;

console.log(name); // Output: 'John'


console.log(age); // Output: 30
console.log(city); // Output: 'New York'

..............................................

Array of objects:

An array of objects in JavaScript is an array where each element is an object. It


allows you to store multiple objects in a single array, making it convenient for
organizing and manipulating collections of related data.
const students = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 22 },
{ name: 'Alex', age: 19 }
];

console.log(students[1].name);
...........................................................
Array of objects problems:

const books = [
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', pages: 218 },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee', pages: 281 },
{ title: 'Pride and Prejudice', author: 'Jane Austen', pages: 432 },
{ title: '1984', author: 'George Orwell', pages: 328 },
{ title: 'The Catcher in the Rye', author: 'J.D. Salinger', pages: 234 }
];

Problem: Filter books with more than 250 pages.


const longBooks = books.filter(book => book.pages > 250);

// Output: [
// { title: 'To Kill a Mockingbird', author: 'Harper Lee', pages: 281 },
// { title: 'Pride and Prejudice', author: 'Jane Austen', pages: 432 },
// { title: '1984', author: 'George Orwell', pages: 328 }
// ]

Problem: Map book titles to an array.

const bookTitles = books.map(book => book.title);


// Output: [
// 'The Great Gatsby',
// 'To Kill a Mockingbird',
// 'Pride and Prejudice',
// '1984',
// 'The Catcher in the Rye'
// ]

Problem: Calculate the total number of pages across all books.

const totalPages = books.reduce((sum, book) => sum + book.pages, 0);


// Output: 1483

...........................................................................

const products = [
{ id: 1, name: 'iPhone', price: 999 },
{ id: 2, name: 'Samsung Galaxy', price: 899 },
{ id: 3, name: 'Google Pixel', price: 799 },
{ id: 4, name: 'OnePlus', price: 699 },
{ id: 5, name: 'Xiaomi', price: 499 }
];

Problem: Filter products with a price less than $800.

const affordableProducts = products.filter(product => product.price < 800);


// Output: [
// { id: 2, name: 'Samsung Galaxy', price: 899 },
// { id: 4, name: 'OnePlus', price: 699 },
// { id: 5, name: 'Xiaomi', price: 499 }
// ]

Problem: Map products to an array of names and prices.

const productDetails = products.map(product => ({ name: product.name, price:


product.price }));

// Output: [
// { name: 'iPhone', price: 999 },
// { name: 'Samsung Galaxy', price: 899 },
// { name: 'Google Pixel', price: 799 },
// { name: 'OnePlus', price: 699 },
// { name: 'Xiaomi', price: 499 }
// ]

Problem: Calculate the total price of all products.


const totalPrice = products.reduce((sum, product) => sum + product.price, 0);
// Output: 3995

................................................................

function in javascript:

In JavaScript, a function is a block of reusable code that performs a specific task


or calculates a value. Functions are one of the fundamental building blocks of the
language and play a crucial role in organizing and structuring code.

Functions can be defined using the function keyword, and they can accept input
values called parameters or arguments. Functions can also return a value using the
return statement.

function addNumbers(a, b) {
return a + b;
}

const result = addNumbers(5, 3);


console.log(result); // Output: 8

...............................................
Types of Function

Named Functions:

These are functions with a specific name and can be defined using the function
keyword. They can be invoked by using their assigned name.

function greet() {
console.log("Hello!");
}
greet(); // Output: "Hello!"

.......................

Anonymous Functions:
These functions do not have a name and are typically assigned to variables or used
as arguments to other functions.

const greet = function() {


console.log("Hello!");
};
greet(); // Output: "Hello!"
===============================================
Arrow Functions:

Arrow functions provide a concise syntax for writing functions. They have a shorter
syntax compared to traditional named or anonymous functions.

const greet = () => {


console.log("Hello!");
};
greet(); // Output: "Hello!"
//=======================

single line of statement :

const multiply = (a, b) => a * b;


console.log(multiply);

single arguments:

const square = num => num * num;

...............................................
IIFE (Immediately Invoked Function Expression):

These are self-invoking functions that are executed immediately after they are
defined.

(function() {
console.log("IIFE executed!");
})(); // Output: "IIFE executed!"

//DAY-2

(function(name) {
console.log(`Hello, ${name}! IIFE executed!`);
})("John");

const result = (function(a, b) {


return a + b;
})(5, 3);
console.log(result); // Output: 8

.........................................
Constructor Functions:

Constructor functions are used to create objects. They are typically invoked with
the new keyword to create instances of the objects they define.

function Person(name) {
this.name = name;
}
const john = new Person("John");
console.log(john.name); // Output: "John"

...............................................................
Callback Functions:

Callback functions are passed as arguments to other functions and are invoked at a
later time or when a specific event occurs.

function calculate(num1, num2, callback) {


const result = num1 + num2;
callback(result);
}

function displayResult(result) {
console.log(`The result is: ${result}`);
}

calculate(5, 3, displayResult); // Output: "The result is: 8"

You might also like