JavaScript Functions and Objects
After completing this topic
You will be able to create functions to reuse code and group related data into objects.
Functions β Grouping and Reusing Code
Instead of writing the same code multiple times, you can group it into a function and execute it repeatedly by calling its name.
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function call
console.log(greet("Kim Developer")); // "Hello, Kim Developer!"
console.log(greet("Lee Coder")); // "Hello, Lee Coder!"name is a parameter β an input value passed to the function. return is a keyword that returns a result. If there is no return, the function returns undefined.
// Arrow function β a shorter way to write functions (ES6+)
const add = (a, b) => a + b;
console.log(add(3, 5)); // 8
// If it's multiple lines, use curly braces + return
const calculate = (price, tax) => {
const total = price + price * tax;
return total;
};
console.log(calculate(10000, 0.1)); // 11000Arrow functions (=>) are the most commonly used way to write functions in modern JavaScript. For one-line functions, you can omit the return keyword, making the code more concise.
Objects β Grouping Related Data
If you store a person's name, age, and email in separate variables, it can be difficult to manage. An object groups related data into key-value pairs and manages it as a single unit.
const user = {
name: "Kim Developer",
age: 28,
email: "dev@example.com",
skills: ["JavaScript", "Python"]
};
// Two ways to access
console.log(user.name); // "Kim Developer" (dot notation)
console.log(user["email"]); // "dev@example.com" (bracket notation)
// Modify a value
user.age = 29;
// Add a new property
user.company = "Startup";Methods β Functions Inside Objects
You can put functions inside objects. This is called a method.
const calculator = {
result: 0,
add(value) {
this.result += value;
return this;
},
subtract(value) {
this.result -= value;
return this;
},
show() {
console.log(`Result: ${this.result}`);
}
};
calculator.add(10).add(5).subtract(3).show();
// Result: 12this refers to "this object itself." this.result has the same meaning as calculator.result. Returning this from a method enables chaining β a pattern where methods are called consecutively.