Search code examples
javascriptnode.jsgoogle-chromeecmascript-6v8

Using 'let' as a variable name is not throwing any errors in google v8


I was writing some random code in the chrome developer console. For my surprise, chrome let me use let as a variable name which is completely wrong as let is a reserved keyword. I need to understand why is this happening.

Scenarios:

var const = 78 //throws an error as expected

var function = 46 //throws an error as expected

var let = 56 //didn't throw an error :O

let //prints 56, which is wrong because 'let' is a keyword

let ab = 90

ab //prints 90 as expected

This flaw exists in node. But, when I try it in Babel REPL it is throwing an error.

I think this is something to do with Google v8


Solution

  • A nice write-up of the reasoning behind this can be found in this article by Mohsen Azimi. Here's a quick summary of it.

    The following keywords are defined in the JavaScript spec as FutureReservedWord:

    implements     interface   let       package    private
    protected      public      static    yield
    

    In normal mode, these can be used as variable names without errors; however, in strict mode they are treated as reserved words and will throw the following error:

    SyntaxError: Cannot use the reserved word 'let' as a variable name in strict mode.
    

    This is so that pre-ES2015 code doesn't break - if someone had named lots of their variables let in a legacy app, they probably wouldn't be happy if the JS spec suddenly broke everything.