Reputation: 567
This is probably super simple but I can't quite word how to search for an answer.
I've just noticed I have functions in my react native components that sometimes I declare with const while others I don't and there seems to be no difference.
Like so
const MyComponent = (props) => {
const myFunction = () => {
console.log("Hello world");
}
return(
<TouchableOpacity onPress={myFunction}>
...somestuff
</TouchableOpacity>
)
}
or
const MyComponent = (props) => {
myFunction = () => {
console.log("Hello world");
}
return(
<TouchableOpacity onPress={myFunction}>
...somestuff
</TouchableOpacity>
)
}
I can't find anything different between them in terms of output. Is this just the compiler saving my a*s or is there actually a difference between them?
Upvotes: 2
Views: 1249
Reputation: 1145
Javascript won't stop you from using undeclared variables.
x = 10; // This is completely fine, as it'll be added in global scope
To avoid doing this, generally use strict
is used.
"use strict";
x = 10; // This will cause an error because x is not declared
Upvotes: 0
Reputation: 1313
I don't think in react native it matters because of it's lifecycles. But in normal javascript it has a difference in hoisting. Without const you can call a function that hasn't been declared:
doTheThing();
function doTheThing() {
console.log(`This is awesome number ${getAwesome()}`)
}
function getAwesome() {
return (+((Math.random() * 10000).toString().split('.')[0]))
}
With Const/let it doens't let you do that:
const tryDoTheThing = () => {
console.log(`This is me trying to be awesome ${getAwesome()}`)
}
// "getAwesome is not defined", because it is referenced too early
tryDoTheThing() // comment to see the rest work
const getAwesome = () => (+((Math.random() * 10000).toString().split('.')[0]))
const doTheThing = () => {
console.log(`This is awesome! ${getAwesome()}`)
}
doTheThing() // prints
using function
will put it's declaration on top of the current scope (to the top of the current script or the current function).
Upvotes: 3