Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 688
Pranesh Ravi Avatar asked Dec 15 '22 02:12

Pranesh Ravi


2 Answers

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.

like image 122
Joe Clay Avatar answered Dec 17 '22 01:12

Joe Clay


The usage of reserved ES6 keywords is forbidden only in strict mode for compatibility reasons.

Babel (via the strict mode plugin) use strict mode by default. In the browser or in Node you can implicitly set strict mode by adding "use strict"; in the beginning of the file or the function.

Running the following code snippet will throw an error in Chrome as you expect it:

"use strict";
var let = 43;
// Throws: Uncaught SyntaxError: Unexpected strict mode reserved word
like image 20
NoNameProvided Avatar answered Dec 17 '22 02:12

NoNameProvided