is a block of code designed to perform a particular task.
JavaScript Function
It is executed when it is invoked (called) and can take parameters (inputs) and return a result (output).
JavaScript Function
help organize and reuse code by encapsulating logic in a reusable unit.
Functions
Function Declaration
function greet(name) {
return Hello, ${name}!;
}
Function Expression:
const greet = function(name) {
return Hello, ${name}!;
};
Arrow Function
const greet = (name) => Hello, ${name}!;
Returning a Value:
function add(a, b) {
return a + b;
}
Returning Multiple Values: (Using an Object or Array)
function getPerson() {
return {
name: ‘Alice’,
age: 25
};
}
No Return Statement:
function logMessage(message) {
console.log(message);
}
Defining Object Properties:
let person = {
name: ‘John’,
age: 30
};
Dot Notation:
let name = person.name;
Bracket Notation:
let age = person[‘age’];
Defining Methods in Objects:
let person = {
name: ‘John’,
greet() {
return Hello, ${this.name}!;
}
};
Accessing Methods:
console.log(person.greet());
Defining Nested Objects:
let person = {
name: ‘John’,
address: {
street: ‘123 Main St’,
city: ‘Anytown’
}
};
How to access nested properties
let city = person.address.city;
is a lightweight format for data interchange.
JSON (JavaScript Object Notation)
Commonly used to transmit data between a server and web application.
JSON (JavaScript Object Notation)