Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this const available before the declaration?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading