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

Joe Williams
4,014 PointsWhy do I keep getting the error, "TypeError: xxx is not a function?" Is there a better way to do this?
I am trying to test myself a bit by combining some of the things I've learned in these beginning Javascript courses. What I'm trying to do is make it so when you arrive to a website, you're greeted with an alert, asked your name, and if it is Joe, I want it to print to the console, "the user's name is joe." Otherwise, I want it to print, "the user's name isn't joe."
What am I doing wrong?
alert("Welcome to my first mini-program.")
firstPrompt = prompt("What is your name?")
(function () {
if (firstPrompt == 'joe') {
console.log("The user's name is joe")
} else {console.log("The user's name isn't joe")}
})()
My logic was that I needed the function to run automatically when the user arrives to the page, and I remembered learning that a benefit to the anonymous function is that you can immediately call it.
Am I close, or is this attempt way off? This is assuming that the user types in "joe" in lowercase, and no other name, when prompted after loading the page.
((( Also, for the record, inside the function I also tried it as (firstPrompt ==='ally') )))
1 Answer

Chris Shaw
26,676 PointsHi Joe,
The anonymous function isn't needed as it offers no benefit to this example since your declarations all occur within the global scope of the page, normally you only need to use anonymous functions when you want your code locally scoped so it can't be accessed by anything not in that same scope.
In any case the below would suffice and achieve the result you're looking for, of course semi-colons aren't a requirement but it's better to have them to avoid any issues down the track.
alert("Welcome to my first mini-program.");
firstPrompt = prompt("What is your name?");
if (firstPrompt === 'joe') {
console.log("The user's name is joe");
} else {
console.log("The user's name isn't joe");
}

Joe Williams
4,014 PointsThank you for the feedback! That makes a lot more sense. In my head, the function was necessary for the program to run. Now I realize that "if/else" will run automatically simply by meeting the correct criteria.
Alex Lewis
15,619 PointsAlex Lewis
15,619 PointsYou just needed to add some semicolons to your statements. Javascript was getting confused since you were missing a few.
Here's what you should have:
Check out the jsfiddle