Variable Scope


#1

So I've just finished part 10 (if conditionals) and I've got a few questions about variable scope
I have experience in a fare few languages and in all of hem the code used here would throw an error about not being able to access the img outside the if statement.
The code from the example is below, any help on why this works would be appreciated

Thanks

var React = require('react');
var ReactDOM = require('react-dom');

function coinToss () {
  // This function will randomly return either 'heads' or 'tails'.
  return Math.random() < 0.5 ? 'heads' : 'tails';
}

var pics = {
  kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg',
  doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg'
};

// if/else statement begins here:

if (coinToss() == "heads") {
  var img = <img src={pics.kitty} />;
} else {
  var img = <img src={pics.doggy} />;
}

ReactDOM.render(img, document.getElementById("app"));

#2

It works because you have something special called an: "Combiner" or something for the JavaScript, Codecademy already have this installed.

There was an exercise where they explained everything!


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.