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.