Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How can I define these two variables?

Does anyone know how I can define the firstNumber and secondNumber variables in the operator function? I know variables in functions won't register in other functions, but I need to find out if there is another way.

// making a function to store the code block in

var name = prompt("What is your name?"); console.log(name);

window.onload = function calculator() { // creating prompts for the user to type their answers // creating alerts to increase interactivity

alert(name + ", my name is Mr. Calculator, I can help you out with your math problems!");

var firstNumber = prompt(name + ", what is your first number?"); console.log(firstNumber); firstNumber += parseInt(firstNumber); if (!isNaN(firstNumber)) { numbers(); } else { alert("That is not an acceptable value, restart the program to try again"); } }; // creating a conditional function

function numbers() { var secondNumber = prompt("What is your second number, " + name); console.log(secondNumber); secondNumber += parseInt(secondNumber); if(!isNaN(secondNumber)) { operator(); } else { alert("That is not an acceptable value, restart the program to try again"); } }

// creating another conditional function

function operator() { var operation = prompt(name + ", what would you like to do to your two numbers?"); console.log(operation); if (operation === "+") { alert(name + " , the answer is " + firstNumber + secondNumber); } else if (operation === "-") { alert(name + " , the answer is " + firstNumber - secondNumber); } else if (operation === "*") { alert(name + " , the answer is " + firstNumber * secondNumber); } else if (operation === "/") { alert(name + " , the answer is " + firstNumber / secondNumber); } else { alert("That is not an acceptable operator, restart the program to try again"); } }

1 Answer

Steven Parker
Steven Parker
243,656 Points

You can define new variables just by putting "var" (or "let" or "const") in front of the variable name.

:warning: Note that any variables defined in a function that have the same name as global variables will prevent the function from being able to access the global ones.