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
Keith Corona
9,553 PointsNecessity of parenthesis in the 'if' statement
In the following code, I eliminated ( ) after "answer" in the 'if' statement
var answer = prompt('What is the best programming language?');
if( answer === 'JavaScript') {
alert('You are correct!');
}
compare with () appearing after the variable 'answer' in the if statement...
var answer = prompt('What is the best programming language?');
if( answer() === 'JavaScript') {
alert('You are correct!');
}
In the challenge, the first code passed while the second code did not. In the exercises prior to this challenge, I had () appearing after the variable name in the if statement - my question: what is the purpose of these parenthesis? Are the necessary?
1 Answer
Keli'i Martin
8,227 PointsHaving a set of parentheses after a name would indicate that you are working with a function. In this case, answer is declared as a variable, so no parentheses are necessary. If instead of a variable, you had a function that returned a string, then you would have parentheses.
For example:
function answer() {
return prompt('What is the best programming language?');
}
In that case, you would have parentheses after answer. Hope that makes sense.