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 ( );
}}
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.
Strings and string operations will be much like in JavaScript. To create a simple string in React Native and save it in a variable use let or const and single quotes. const hello = 'Hello, ' ; const world = 'World!
Embedding Expressions in JSX In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces: const name = 'Josh Perez';const element = <h1>Hello, {name}</h1>; You can put any valid JavaScript expression inside the curly braces in JSX.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With