Does node.js support the 'let' statement?

后端 未结 5 1912
别那么骄傲
别那么骄傲 2020-12-01 09:03

Does node.js support a let statement something like what\'s described on MDN??

var x = 8,
    y = 12;

let ( x = 5, y = 10) {
    return x + y;
} //15


        
相关标签:
5条回答
  • 2020-12-01 09:39

    Yes, you can use let within node.js, however you have to run node using the optional --harmony flag. Try the following test.js:

    "use strict"
    var x = 8,
        y = 12;
    
    { let x = 5, y = 10; console.log(x + y); }
    
    console.log(x + y);
    

    And then run the file node --harmony test.js which results in:

    15
    20
    

    I would not recommend using this in an important production application, but the functionality is available now.

    0 讨论(0)
  • 2020-12-01 09:43

    I don’t think Node supports let, but you can do this:

    var a = 5;
    
    (function () {
      var a = 6;
      console.log(a); // => 6
    })();
    
    console.log(a); // => 5
    
    0 讨论(0)
  • 2020-12-01 09:49

    This is an old question and the accepted answer is no longer correct.

    let support was added in Node.js 4.x.

    See here for the full version support matrix.

    0 讨论(0)
  • 2020-12-01 09:50
    node --use_strict --harmony_scoping
    
    0 讨论(0)
  • 2020-12-01 09:51

    You can use the Babel transpiler and use let as well as many other ES6/ES2015 features.

    To use babel:

    $ npm install --save-dev babel
    

    Then in your package.json:

    "scripts": {
      "start": "babel-node index.js"
    }
    

    Inside index.js:

    let foo  = 'bar;
    

    Then start the server:

    $ npm start
    
    0 讨论(0)
提交回复
热议问题