头图
This article is the second in the series of "A JSer's Dart Learning Log". This series of articles mainly aims to explore the similarities and differences between JS and Dart, while reviewing and consolidating JS while smoothly transitioning to the Dart language.
Since the author is still a beginner to Dart, his understanding may be superficial and one-sided. If you know the worms, I hope you can correct me.
Unless otherwise specified, the JS in this article contains all the features from ES5 to ES2021, and the Dart version is 2.0 or higher.

1. Keywords

(On the surface) common ground

  • Variable keyword var ;
  • Constant keyword const .

difference

1.1 The scope of var

  • var JS is the scope of the function, and there is a very classic example associated with this (that is, for loop of setTimeout , which will not be repeated);
  • The variable scope declared by the keyword var Dart is a block-level scope.
> /* JS */                          | // Dart
> function foo(){                   | foo(){
>     if(true){                     |     if(true){
>         var a = 321;              |         var a = 321;
>     }                             |     }
>     console.log(`a = ${a}`);      |     print('a = $a');
>   /* a = 321; */                  | // Getter not found: 'a'.
> }                                 | }

1.2 The semantics of const

  • In JS, const can be calculated temporarily during operation;
  • In Dart, const must be a compile-time constant, that is, its value must be determined before running.
> /* JS */                          | // Dart
> var a = Date.now();    /* OK */   | var a = new DateTime.now();   // OK
> const b = Date.now();  /* OK */   | const b = new DateTime.now(); // NOT OK

2. Their own characteristics

This is considered to be a special grammar award for the two languages, so they will not be listed anymore.

2.1 final , late and let , their own special keywords

  • JS introduced let keyword to compensate var design flaws, but Dart in var does not have these drawbacks, probably therefore, Dart no let keyword reluctant let , you can go next door to learn Rust;
  • The constants declared by the const keyword in Dart need to be determined at compile time, but in daily programming, we need to fix some variables whose value can be determined during operation to prevent accidental modification. It can also provide a certain value to the compiler. For optimization reference, at this time we can use final , and its characteristics can refer to const JS;
  • The default value of the variable without initial value specified in JS is undefined , and although there is a default value of null with "empty safety" in Dart, in order to write more robust code, you can use late declare the variable, which means that the variable has no initial value. , It will be assigned a value when the time is right.
/* JS only */                            | /* Dart only */
> let x = 0;                             |
>                                        | final x = new DateTime.now();
> let msg;                               | late String msg;

2.2 Dart supports declaring variable types

  • Dart is a strongly typed language. When declaring a variable/constant, you can also declare its type explicitly, but the variable type and the var keyword cannot be used in parallel.

    > var int a = 0; // 错误,`var` 与变量名不得并列使用
    > var     a = 0; // 正确,Dart 会推断类型
    >     int a = 0; // 正确,得到一个类型为 int 的变量
    >
    > const int a = 0; // 正确,得到一个类型为 int 的编译时常量
    > final int a = 0; // 正确,得到一个类型为 int 的常量
    >
    > Set<num> a = {0}; // 正确, 所得 Set 可包含 int 和 double 子项
In fact, if you don't explicitly declare the variable type, Dart will infer the type of the variable based on the assigned value. var a = 0 in, a type is inferred to int ; var a = 0.1 in, a type was double .

2.3 Dart uses const determine compile-time constants

The const Dart has been determined at compile time. This should be due to performance optimization considerations, to transfer some runtime calculations to the compilation process, or to avoid the additional overhead of repeated execution in the same program.
  • The variable value can be determined at compile time such a good function, if only const can enjoy it, it is too wasteful, so when declaring the value of the variable as a complex data type, you can use the const keyword to label the value as a compile-time constant :

    var a = const { 123456 };
    Set<num> a = const { 123456 };

    , But this syntax does not apply to simple types:

    var a = const 123456; // 这将无法通过编译

2.4 JS omitted keywords var

  • In JS, you can omit var , directly name a variable and assign a value, this variable will automatically become a global variable, which is the "implicit global variable" of JS, which is a JS feature with a bad reputation and should be avoided in development ;
As mentioned in 2.2 of this article: Dart's var keyword and type declaration cannot be used in parallel. In a sense, the keyword var is also omitted.

2.5 Dart does not have variable promotion

  • Variable promotion is also a slot in JS. Fortunately, ES6+'s let and const avoid this slot in a "dead zone" way, which proves that TC39 doesn't like this feature;
  • Dart is a "normal" language. It follows the principle of variable declaration before use, and there is no variable promotion.
> /* JS */                         | // Dart
> var b = a + 1;                   | var b = a + 1;
> var a = 100;                     | var a = 100;
> console.log(`b = ${b}`);         | print('b = $b');
> // b = NaN                       | // 无法通过编译

3. Summary & comparison

See the table below:

characteristicJSDart
var Function level Variable keywordsBlock-level variable keywords
constConstant keyword Compile-time constant Keywords
let Block level Variable keywords does not have this keyword
final does not have this keyword runtime constant keyword
late does not have this keyword Variable keyword with no initial value specified
Type declaration does not support type declaration Supports type declarations, and can also be handed over to Dart to automatically infer the type

知名喷子
5.9k 声望2.5k 粉丝

话糙码不糙。