Create object

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Creating Objects

JS · Objects
Syntax
const obj = { key: value };
const obj = Object.create(proto);
Example
const user = {
  name: "Kai",
  age: 30,
  greet() {
    return `Hi, I'm ${this.name}`;
  }
};
console.log(user.greet());
Output
"Hi, I'm Kai"

Note Method shorthand greet() {} is preferred over greet: function() {}. Arrow functions should not be used as methods because they do not bind their own this.

PYPython

Defining a Class

PY · Classes & OOP
Syntax
class Name:
    def __init__(self, ...):
        self.attr = value
Example
class BankAccount:
    def __init__(self, owner: str, balance: float = 0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount: float) -> None:
        self.balance += amount

acct = BankAccount("Alice", 100)
acct.deposit(50)
print(f"{acct.owner}: ${acct.balance}")
Output
Alice: $150

Note self is not a keyword; it is a convention for the first parameter of instance methods. Python passes the instance automatically.

Frequently asked questions

How do you create object?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Creating Objects" snippet in JavaScript uses `const obj = { key: value };`.
Which code does the JavaScript example use?
The "Creating Objects" snippet uses `const obj = { key: value };`, from the Objects section of the JavaScript cheat sheet.
Which stacks cover "create object" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Creating Objects": Method shorthand greet() {} is preferred over greet: function() {}. Arrow functions should not be used as methods because they do not bind their own this.