6

I noticed one interesting thing in react native. I thought that const and let does not support hoisting in ES6. How is it possible to use const styles above its define?

    render() {
        const { repos } = this.state;
        const reposList = repos.map((rep, index) => {
            return (
                    <Text>{rep.name}</Text>
            )
        });

        return (
                <View style={styles.container}>  <-- styles should not be defined
                    {reposList}
                </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

Is it because of hoisting mechanism in React Native?

Dmitry
  • 809
  • 3
  • 16
  • 29
  • 2
    All declarations are hoisted in javascript. Please read [this](https://stackoverflow.com/a/31222689/6731368). – arunmmanoharan Nov 16 '17 at 18:00
  • 2
    I'm not sure if this is really "true". There exists a temporal dead zone in let/const. var hoists because the compiler afaik reads LHS assignments, stores them in memory, and then goes through reading RHS assignments. I am not sure how the compiler reads const/let but if you attempt to use a let/const before it's declaration you will get a temporal dead zone error. his issue is not hoisting, he has a class defined, and a styles object defined in the same file. the class isn't invoked, just defined. – cheussy Nov 16 '17 at 18:02
  • 1
    Agreed, not really a hoisting issues. Calling `render()` before `styles` is defined would cause an error. *Defining* `render()` before `styles` is not. – Mark Nov 16 '17 at 18:04
  • what @a2441918 posted should answer your question. – JJJ Nov 16 '17 at 18:08

1 Answers1

6

you have render defined in a class, the class is just defined not executed so it can see the styles you create below it. it's not really hoisting.

cheussy
  • 361
  • 2
  • 11