Skip to content

next.js seems to be handling JS closures incorrectly #33600

@johnfn

Description

@johnfn

Run next info (available from version 12.0.8 and up)

/bin/sh: pnpm: command not found

    Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 21.0.1: Tue Sep 14 20:56:24 PDT 2021; root:xnu-8019.30.61~4/RELEASE_ARM64_T6000
    Binaries:
      Node: 17.1.0
      npm: 8.1.2
      Yarn: 1.22.17
      pnpm: N/A
    Relevant packages:
      next: 12.0.9-canary.6
      react: 17.0.2
      react-dom: 17.0.2

What version of Next.js are you using?

12.0.8

What version of Node.js are you using?

v17.1.0

What browser are you using?

Chrome

What operating system are you using?

MacOS

How are you deploying your application?

next run dev

Describe the Bug

The following code executes differently in my browser than in next.js:

const myFunction = () => {
  for (let j = 0; j <= 3; j++) {
    for (const _ of []) {
    }

    if (j === 1) {
      console.log("before set timeout, j is:", j)

      setTimeout(() => {
        console.log("in timeout: j is", j)
      }, 50)
    }
  }

  return null
}

myFunction()

In my browser, this code correctly prints:

before set timeout, j is: 1
in timeout: j is 1

When I paste this into the top level of index.tsx, run yarn run dev and navigate my browser to localhost:3000, I see:

before set timeout, j is: 1
in timeout: j is 4

Expected Behavior

I expected the output to be the same whether in browser console or in next.js.

To Reproduce

  1. Create a new next app with npx create-next-app my-app
  2. Paste the code into pages/index.js
  3. yarn run dev and look at the console

Metadata

Metadata

Assignees

Labels

SWCRelated to minification/transpilation in Next.js.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions