Skip to content

const demoted to var #3680

@alecmocatta

Description

@alecmocatta

const variable declarations are sometimes demoted to var declarations. See for example:

window['foo'] = function () {
    const a = window['a'],
        b = window['b'];
    let c = window['c'];
    while (a < b[c]) c--;
    for (let i = 0; i < window['d'].length; i++) {}
};

which with compiler --compilation_level ADVANCED --language_in ECMASCRIPT_NEXT --strict_mode_input --language_out ECMASCRIPT_2017 --assume_function_wrapper --use_types_for_optimization compiles to:

'use strict';
window.foo = function() {
    var a = window.a;
    const c = window.b;
    let b = window.c;
    for (; a < c[b];) b--;
    for (a = 0; a < window.d.length; a++);
};

I'm not sure if this is ever incorrect, but this seems surprising? In this instance it's more characters, plus it's (slightly) increasing the work for the ultimate interpreter/compiler who'll now have to deduce that a is const rather than verifying it's const to perform optimisations. Admittedly that won't make a difference in this snippet but I noticed this in a hot loop in my code while profiling and trying to optimize.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions