Search code examples
reactjsfunctionreact-nativefunction-declaration

Functions in a React Native Component (function vs const function)


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?


Solution

  • 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