How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it.

The code below is functioning perfectly:

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],
    }),
}))

It's interesting to note that I'm using petsTable before its declaration. Does this mean that exported constants are accessible throughout the module? Or is this a feature specific to the Drizzle API?

Answer №1

Absolutely, this illustrates the behavior of Javascript accurately. Variables in Javascript are hoisted, meaning a reference to a variable can appear before its declaration thanks to lexical scoping.

function example() {
    console.log(FOO) // This will work
}

const FOO = 42

example()

However, when it comes to runtime, you must ensure that a variable has been initialized before using it.

function example() {
    console.log(FOO) // It's syntactically correct but won't work at runtime
}

example()

const FOO = 42

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am attempting to add a new row (div) for the invoice, but when I do so, the

Looking for a solution to repeat a row when clicking a button in order to utilize PHP for data manipulation? Check out the code snippet below: <!-- Table row --> <br><br> <div class="row"> <!--Product Table--> <div ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

Having trouble sending AJAX select options with Choices.js

I'm currently utilizing Choices.js (https://github.com/jshjohnson/Choices) along with Ajax to dynamically populate data into my select field from a database. However, I've encountered an issue when using the following code: const choices = new C ...

Flip an image by analyzing the colors beneath it

Looking for a way to invert the color of specific areas under a mask (PNG) for a floating menu. Rather than inverting all at once, I want only certain parts to be inverted underneath the mask. Is this achievable, or is there another approach I should consi ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

The Ajax function fails to trigger during the first load of the page

Note: Kindly refer to the update at the end of this question before proceeding. The problem described is specific to IE 11 and emerged after a recent Windows update. Following the installation of 5 updates, including one for IE, I removed the latter hopin ...

Error: Failed to load chunk 552 due to chunk loading issue

Currently in the process of migrating Angular 12 to version 13. The migration itself was successful, however, upon running the project in the browser post a successful build, the application fails to display. On checking the console, I encountered the foll ...

transfer scope variable to scope function

I notice this pattern frequently view: <input ng-model="vm.model"> <button ng-click="vm.method(vm.model)"></button> controller: function Controller() { var vm = this; this.method = function(parameter) { // perform acti ...

I'm curious about the method used to create this body fadeIn effect

Recently, I stumbled upon the website "". I must say, it is truly remarkable. I can't help but wonder how the content on this page is cleverly faded in and slides up. This specific page caught my attention: ...

Positioning Multi-level Drop Down Div in Javascript - How to do it efficiently?

I'm currently working on a horizontal menu using CSS and JavaScript with multiple levels. I've implemented a toggle function to show the submenu container, but it's causing the links below it to be pushed down. Is there a way to make the dis ...

What might be the reason for jQuery not functioning in Internet Explorer 11?

Working on developing a slideout menu for my website using jQuery. It functions perfectly in Chrome, but encountering issues in Internet Explorer (IE11). Extensive search hasn't provided a solution yet. Seeking assistance and any help would be highly ...

Difficulty arises when trying to deploy a React application on a stationary Nginx server

I'm encountering issues trying to deploy my React app on a remote server. My Nginx configuration looks like this: server { listen 80; listen [::]:80; server_name xxx.xxx.x.x; root /var/www/my-site; inde ...

jQuery ajax doesn't function properly on the server, it only works locally

When I send a jQuery Ajax request from my front-end to the back-end to retrieve values for calculations, it works perfectly on my local web server. However, when I try it online, all I get is a result of 0 in my calculations, indicating that the Ajax respo ...

Utilize Flexbox to arrange elements in a grid layout based on specified number of columns and rows

My div is currently empty. <div id="container"></div> I have applied the following styling with CSS: #container{ display: flex; position: relative; flex-flow: row wrap; width: 100%; } The goal is to add more divs to the cont ...

Ajax Complete adds Jquery two times in a row

I have a simple ajax complete call that is designed to add some text after an ajax load finishes. However, I'm encountering an issue where the information is sometimes displayed multiple times. I suspect there might be something missing in my approach ...

Can Angular reactive forms be used to validate based on external conditions?

Currently, I am exploring Angular reactive forms validation and facing an issue with implementing Google autocomplete in an input field: <input autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="input-auto input" formControlName ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

Move the JavaScript code from the <script> element in the HTML file to a

Recently, I've been exploring the idea of incorporating a tradingview ticker on my website. Trading view has kindly provided me with a snippet to embed into my webpage: <!-- TradingView Widget BEGIN --> <div class="tradingview-widget-co ...

Converting CSV into an Array of Hash Tables

Currently, I am working on parsing a CSV file and creating an array of hashes. While I initially implemented this using my own code, I feel that it may not be the most efficient solution. My aim is to utilize the CSV-Parser library, but so far, I have only ...