Lexical Scoping in Dart Programming


Dart is a lexically scoped language. Lexically scoped means that as we move downwards to the latest variable declaration, the variable value will depend on the innermost scope in which the variable is present.

Example

Consider the example shown below −

 Live Demo

void main(){
   var language = 'Dart';
   void printLanguage(){
      language = 'DartLang';
      print("Language is ${language}");
   }
   printLanguage();
}

In the above example, we changed the value of the language variable inside the scope of the printLanguage() function and since we are printing the value inside the printLanguage() function, the innermost scope is the one inside the same code block, and hence we will get the value of the language = 'DartLang' instead of language = 'Dart'.

Output

Language is DartLang

Example

Let us consider one more example, a bit more complicated one to understand the lexical scoping in a better way.

Consider the example shown below −

 Live Demo

void main() {
   String language = "Dart";
   void outerFunction() {
      String level = 'one';
      String ex = "scope";
      void innerFunction() {
         Map level = {'count': "Two"};
         print('ex: $ex, level: $level');
         print('Language: $language');
      }
      innerFunction();
      print('ex: $ex, level: $level');
   }
   outerFunction();
}

There are multiple scopes in the above example, for instance, we have a scope as soon as we start the main function, after that, another inner scope opens as soon as we enter the outerFunction() and an even more scope as we move inside the innerFunction().

Output

ex: scope, level: {count: Two}
Language: Dart
ex: scope, level: one

Updated on: 21-May-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements