I’m wondering why I’m able to use this const BEFORE it is declared.
The following code works fine:
import { relations } from 'drizzle-orm'
import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm/pg-core'
// users
export const usersTable = pgTable('users', {
id: serial('id').primaryKey(),
name: varchar('name'),
email: varchar('email'),
}, (table) => ({
nameIndex: index('users_name_index').on(table.name),
emailIndex: uniqueIndex('users_email_index').on(table.email),
}))
export const usersRelations = relations(usersTable, ({ many }) => ({
pets: many(petsTable),
}))
// pets
export const petsTable = pgTable('pets', {
id: serial('id').primaryKey(),
userId: integer('user_id'),
name: varchar('name'),
}, (table) => ({
nameIndex: index('pets_name_index').on(table.name),
}))
export const petsRelations = relations(petsTable, ({ one }) => ({
user: one(usersTable, {
fields: [petsTable.userId],
references: [usersTable.id],
}),
}))
As you can see, I’m referencing petsTable before it is even declared. Are exported consts available anywhere in the module? Or is this just a Drizzle thing they’ve implemented into their API?
>Solution :
Yes, this is how Javascript works. Variables are scope-bound ("hoisting"), therefore, lexically, a reference to a variable can precede its declaration:
function later() {
console.log(FOO) // works
}
const FOO = 42
later()
However, at the runtime, you’re only allowed to use a variable after it has been actually initialized.
function later() {
console.log(FOO) // syntactically ok, but doesn't work at runtime
}
later()
const FOO = 42