Back to List

JavaScript Functions and Objects

Learn how to create and call functions in JavaScript, and how to group data into objects.

Beginner
|
7min
|
Verified (2026-07)
Progress0/55 (0%)

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.

javascript
// 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.

javascript
// 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)); // 11000

Arrow 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.

javascript
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.

javascript
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: 12

this 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.


πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...