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 Introduction to Programming Objects and Arrays Objects

If/Else with Objects on pop-up

Hi, I have just started with programming here and I am curious, what I am doing wrong in my code. I would like to define the name in pop-up asking me "What is your name". If answered name will be Daniel, the program executes the first alert, otherwise the other alert.

Here is my code:

var myself = {
    first_name: "Daniel",
    last_name: "Trueman",
    birth_place: "Prague",
};

var fake_name = "Roman";

var name = prompt("What is your name?");
var Daniel = "Daniel";

if (Daniel) {
    alert(myself.first_name + " " + myself.last_name + " nice to meet you!")
} else {
    alert("So, you must be " + fake_name + " " + myself.last_name)
};

1 Answer

In your if statement, you're not comparing the variable to anything. Any string that has a length more than '0' is a a truthy value so, since you've set the variable Daniel to a string "Daniel" the first part of the if statement will always run.

So...

if (someVar === someOtherVar) {
  // do something
} else {
  // do something else
}

Also, in JavaScript, never name a variable with a capital letter as you've done with Daniel. The usual convention is that you use a first uppercase letter for constructor names, not regular variables.