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 do you write a code for the following question........

Add a conditional statement that tests if the value in the variable a is greater than the value b.If it is, pop up an alert with the message 'a is greater than b'; also add an else clause that pops up the message 'a is not greater than b'.........given the variables .....var a=10;....var b=20;... .var c=30;

1 Answer

I don't know if this is part of a course or if you are trying this on your own but here is an example of how to write it. If you just want to do a simple conditional you can do so like this:

//define the variables
var a = 10;
var b = 20;

//run the test
if(a > b){
  alert('a is greater than b');
}else{
  alert('a is not greater than b');
}

That works great, but if you put the conditional inside a function you can reuse it by defining a function and then calling it.

//define the variables
var a = 10;
var b = 20;

//put conditional in a function to make it reusable
function compareNumbers(a, b){
  if(a > b){
    alert('a is greater than b');
  }else{
    alert('a is not greater than b');
  }
}

//use the function
compareNumbers(a, b);

Note that the a and b inside the function are different than the a and b outside the function. I will use different letters to make it more clear.

In this function definition we are saying that the numbers that you pass in will be defined as x and y inside the function.

function compareNumbers(x, y){
    //inside this function, although it's not written out:
    //var x = the first value passed in (80);
    //var y = the second value passed in (92);
}

//calling the function with values to be passed in
compareNumbers(80, 92);

This is the function being used multiple times with different values

//define the variables
var a = 10;
var b = 20;
var c = 50;
var d = 30;

//put conditional in a function to make it reusable
//concatenate variable to show the actual number
function compareNumbers(x, y){
  if(x > y){
    alert(x + ' is greater than ' + y);
  }else{
    alert(x + ' is not greater than ' + y);
  }
}

//use the function
compareNumbers(a, b);
compareNumbers(c, d);
compareNumbers(60, 300);

Hopefully that helps you understand how to work out your problem. Good luck!! If you have any specific questions feel free to ask.