Reputation: 153
Whats the difference between these way of declaring variables in react-native.
import React, { Component } from 'react';
import { AppRegistry, Image, View, Text, } from 'react-native';
export default class Hello extends Component {
render() {
**const var1 = 'hi';**
return ( );
}}
import React, { Component } from 'react';
import { AppRegistry, Image, View, Text, } from 'react-native';
**const var1 = 'hi';**
export default class Hello extends Component {
render() {
return ( );
}}
Upvotes: 8
Views: 45111
Reputation: 135752
The difference between those variables is scope.
In both cases, due to the use of const
, var1
will only be accessible after its declaration.
The scope of a const
variable is it's running execution context. In your two examples, the execution contexts are different.
In the second example:
import React, { Component } from 'react';
import { AppRegistry, Image, View, Text, } from 'react-native';
const var1 = 'hi';
export default class Hello extends Component {
render() {
return ( );
}
}
The execution context where var1
is declared is the file.
This means that at any point in the file after const var1 = 'hi';
the var1
variable is available and its value is 'hi'
.
In your first example:
import React, { Component } from 'react';
import { AppRegistry, Image, View, Text, } from 'react-native';
export default class Hello extends Component {
render() {
const var1 = 'hi';
return ( );
}
}
The execution context of the declaration is the method render()
.
Similarly, it means that at any point in the render()
method and ONLY inside that render()
method after the const var1 = 'hi';
statement the var1
variable is available and its value will be 'hi'
.
In summary, when you use const var1 = 'hi';
inside a method, the var1
(constant) variable will only be available inside that method. OTOH, when you declare const var1 = 'hi';
in the file, outside of any class or {}
or function, var1
will be available in the whole file.
In both cases, though, var1
will only be defined/available after the const var1 = 'hi';
declaration statement.
Upvotes: 10