From a4a94de9420dec757c625124782773a5ef8dc47a Mon Sep 17 00:00:00 2001 From: Aliaksandr Kalenik Date: Mon, 18 Sep 2023 16:59:02 +0200 Subject: [PATCH] LibJS: Get initial_value from local variables if id represents a local If identifier represents local variable we should get its value from `local_variables` in `ExecutionContext` instead of environment. --- .../Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp | 6 +++++- .../LibJS/Tests/functions/function-default-parameters.js | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp index d500772c41..2847c3e6a9 100644 --- a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp +++ b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp @@ -661,7 +661,11 @@ ThrowCompletionOr ECMAScriptFunctionObject::function_declaration_instantia // 4. Else, else { // a. Let initialValue be ! env.GetBindingValue(n, false). - initial_value = MUST(environment->get_binding_value(vm, id.string(), false)); + if (id.is_local()) { + initial_value = callee_context.local_variables[id.local_variable_index()]; + } else { + initial_value = MUST(environment->get_binding_value(vm, id.string(), false)); + } } // 5. Perform ! varEnv.InitializeBinding(n, initialValue). diff --git a/Userland/Libraries/LibJS/Tests/functions/function-default-parameters.js b/Userland/Libraries/LibJS/Tests/functions/function-default-parameters.js index 1962a4fa53..6deb559dbc 100644 --- a/Userland/Libraries/LibJS/Tests/functions/function-default-parameters.js +++ b/Userland/Libraries/LibJS/Tests/functions/function-default-parameters.js @@ -151,3 +151,12 @@ test("use variable as default function parameter", () => { expect(func()).toBe(a); }); + +test("variable is initialized to the value of the parameter if one with the same name exists", () => { + function func(a = 1) { + var a; + return a; + } + + expect(func()).toBe(1); +});