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

Javascript Functions and Objects

The document provides an overview of functions and objects in JavaScript, explaining their definitions, creation, and usage. It covers function declarations, expressions, arrow functions, object properties, methods, and constructors, along with examples. Key concepts include the first-class nature of functions, dynamic property access, and the use of prototypes for efficient object method sharing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Javascript Functions and Objects

The document provides an overview of functions and objects in JavaScript, explaining their definitions, creation, and usage. It covers function declarations, expressions, arrow functions, object properties, methods, and constructors, along with examples. Key concepts include the first-class nature of functions, dynamic property access, and the use of prototypes for efficient object method sharing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

1.

Functions in JavaScript

A function in JavaScript is a block of code that can be defined once and executed multiple times.
Functions are useful for performing operations like calculations, validations, and repeating tasks.

Function Declaration:

A standard way of declaring a function in JavaScript.

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

let result = addNumbers(5, 3);


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

Function Expression:

Functions can also be assigned to variables. This is known as function expressions.

const multiplyNumbers = function(a, b) {


return a * b;
};

let result = multiplyNumbers(4, 2);


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

Arrow Function (ES6):

Arrow functions provide a more concise syntax for writing functions.

const divideNumbers = (a, b) => a / b;

let result = divideNumbers(8, 2);


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

Functions as First-Class Citizens:

In JavaScript, functions are first-class objects. This means that functions can be passed as
arguments, returned from other functions, and assigned to variables.

// Passing a function as an argument


function greet(name, greetingFunction) {
console.log(greetingFunction(name));
}

greet("Alice", (name) => "Hello, " + name); // Output: Hello, Alice

Returning Functions:
Functions can also return other functions.

function multiplyBy(factor) {
return function (number) {
return number * factor;
};
}

let multiplyBy2 = multiplyBy(2);


console.log(multiplyBy2(5)); // Output: 10

2. Objects in JavaScript

Objects are essential to JavaScript and are used to store collections of data and more complex
entities. Objects are composed of key-value pairs where the keys are typically strings (or
symbols) and the values can be any valid data type, including other objects or functions.

Object Creation:

Objects can be created using literal notation or the new Object() constructor.

// Using Object Literal Syntax


let person = {
name: "John",
age: 30,
isStudent: false,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};

person.greet(); // Output: Hello, my name is John

You can also use the new Object() syntax, but using object literals is more common:

let person = new Object();


person.name = "Jane";
person.age = 28;
person.isStudent = true;
person.greet = function() {
console.log("Hi, I'm " + this.name);
};

person.greet(); // Output: Hi, I'm Jane

3. Object Properties

Properties are key-value pairs stored in an object. You can access properties using dot notation or
bracket notation.
Dot Notation:

let car = {
brand: "Toyota",
model: "Corolla",
year: 2020
};

console.log(car.brand); // Output: Toyota

Bracket Notation (useful when the property name contains spaces or is dynamic):

let student = {
"first name": "Alice",
"last name": "Smith",
age: 22
};

console.log(student["first name"]); // Output: Alice


console.log(student["last name"]); // Output: Smith

Dynamic Property Access:

You can use a variable to dynamically access object properties.

let key = "age";


console.log(student[key]); // Output: 22

Adding/Modifying Properties:

Properties can be added or changed at any time.

car.color = "red"; // Adding a new property


car.year = 2022; // Modifying an existing property

console.log(car.color); // Output: red


console.log(car.year); // Output: 2022

4. Object Methods

Methods are functions that are stored as properties of objects. They can access and modify object
properties using the this keyword.

Example with a Method:

let person = {
name: "Alice",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name + " and I am " + this.age +
" years old.");
}
};

person.greet(); // Output: Hello, my name is Alice and I am 30 years old.

Using Arrow Functions as Methods:

As mentioned earlier, arrow functions do not bind their own this, which can lead to issues when
used as object methods.

let person = {
name: "Bob",
greet: () => {
console.log("Hello, my name is " + this.name); // `this` will refer to
the global object
}
};

person.greet(); // Output: Hello, my name is undefined

Fixing this with Regular Functions:

let person = {
name: "Bob",
greet: function() {
console.log("Hello, my name is " + this.name); // `this` correctly
refers to the object
}
};

person.greet(); // Output: Hello, my name is Bob

5. Object Display

Displaying objects and their properties is a common task for debugging or output purposes.
There are several ways to display or inspect an object’s properties.

Using console.log():

The simplest way to display the entire object is by logging it to the console.

let user = {
username: "john_doe",
email: "john@example.com"
};

console.log(user); // Output: { username: 'john_doe', email:


'john@example.com' }
Iterating Over Object Properties with for...in Loop:

You can loop through all properties of an object using the for...in loop.

let person = {
name: "Sarah",
age: 25,
profession: "Engineer"
};

for (let key in person) {


console.log(key + ": " + person[key]);
}
// Output:
// name: Sarah
// age: 25
// profession: Engineer

Using Object.keys(), Object.values(), and Object.entries():

• Object.keys() returns an array of the object’s property names.


• Object.values() returns an array of the object’s property values.
• Object.entries() returns an array of the object’s key-value pairs as arrays.

let person = {
name: "David",
age: 34
};

// Get keys
console.log(Object.keys(person)); // Output: ["name", "age"]

// Get values
console.log(Object.values(person)); // Output: ["David", 34]

// Get entries (key-value pairs)


console.log(Object.entries(person)); // Output: [["name", "David"], ["age",
34]]

6. Object Constructors

Constructor functions are a way to create multiple instances of objects that share the same
structure and methods. When you call a constructor function with the new keyword, a new object
is created, and the constructor function's this refers to that object.

Constructor Function Syntax:

function Car(brand, model, year) {


this.brand = brand;
this.model = model;
this.year = year;
this.displayInfo = function() {
console.log(this.year + " " + this.brand + " " + this.model);
};
}

// Creating instances of the Car object


let car1 = new Car("Toyota", "Camry", 2021);
let car2 = new Car("Ford", "Mustang", 2020);

car1.displayInfo(); // Output: 2021 Toyota Camry


car2.displayInfo(); // Output: 2020 Ford Mustang

Using Prototypes:

Instead of adding methods inside the constructor function (which can be inefficient as each
instance gets its own copy of the method), you can use prototypes to share methods across
instances.

function Car(brand, model, year) {


this.brand = brand;
this.model = model;
this.year = year;
}

// Adding a method to the prototype


Car.prototype.displayInfo = function() {
console.log(this.year + " " + this.brand + " " + this.model);
};

let car1 = new Car("Toyota", "Corolla", 2021);


let car2 = new Car("Honda", "Civic", 2020);

car1.displayInfo(); // Output: 2021 Toyota Corolla


car2.displayInfo(); // Output: 2020 Honda Civic

new Keyword:

The new keyword creates a new object, sets the context (this) of the constructor function to that
object, and finally returns the object.

function Animal(name, species) {


this.name = name;
this.species = species;
}

let tiger = new Animal("Tony", "Tiger");


console.log(tiger.name); // Output: Tony
console.log(tiger.species); // Output: Tiger

Summary
• Functions: Functions are a way to encapsulate code into reusable blocks. They can be
declared, expressed, or written as arrow functions.
• Objects: Objects group related data and functions (methods). They are essential for
modeling real-world entities.
• Object Properties: Object properties store data. You can access and modify them using
dot notation or bracket notation.
• Object Methods: Methods are functions that belong to an object. They can manipulate or
access object properties via the this keyword.
• Object Display: You can display or iterate through objects using console.log(),
for...in loops, and methods like Object.keys(), Object.values(), and
Object.entries().
• Object Constructors: Constructors are functions used to create multiple instances of
objects with the same structure. Methods can be added using prototypes to avoid
duplication across instances.

You might also like