You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《You Don’t Know JS》中变量b未被作用域找到引发ReferenceError的疑问

Why b isn't found in the scope?

Great question! Let's unpack this using the scope rules explained in Kyle Simpson's You Don’t Know JS: Scope & Closures.

First, let's recap how JavaScript looks up variables: when your code tries to access a variable (like reading its value, which is what happens in a + b), it performs an RHS reference lookup. Here's the step-by-step breakdown for your code:

  1. When foo(2) runs, we enter the local scope of the foo function.
  2. The engine first looks for a in this local scope—since a is a function parameter, it's already declared here, so that works fine.
  3. Next, it tries to find b to get its value for the a + b calculation. It checks the local scope of foo first... and there's no var b, let b, or const b declared here.
  4. Then it moves up to the outer (global) scope to look for b—but there's no declaration for b in the global scope either.

Since the engine can't find b anywhere in the scope chain during this RHS lookup, it throws a ReferenceError immediately. The line b = a never even gets a chance to run, because the error happens before that.

It's important to note: if this were an LHS reference (like if you were assigning to b first without reading it), JavaScript would create a global b variable in non-strict mode. But in your case, we're trying to read b first, which triggers the failed RHS lookup and the error.

The key takeaway from You Don’t Know JS here is that scope lookup stops at the first match, and if no match is found in the entire chain, RHS lookups throw ReferenceErrors, while LHS lookups in non-strict mode create a global variable.

内容的提问来源于stack exchange,提问作者Maruf Hasan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:08:50