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

Help a noob out

Hey guys. So just learning the basics and getting stuck at functions. I'm trying to create my own to get a better understanding. What I'm trying to do is simply make a function that calculates how many letters are in your first and last name combined. But I'm having some problems. I keep getting the answer 0. Maybe somebody can point me in the right direction and tell me what exactly I'm doing wrong.

Here's the code :

var firstName = prompt('What is your first name?') var lastName = prompt('What is your last name?')

function getLength() { var completeName = firstName + lastName; var nameLength = completeName.length; return completeName; }

document.write(getLength());

2 Answers

Basilissa Albers
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Basilissa Albers
Full Stack JavaScript Techdegree Graduate 23,755 Points

You have quite a bit of unnecessary code, for example the variables completeName and nameLength have the exact same value, and you don't need both. And on the last line you're calling the function twice, and the first call basically doesn't do anything as you're not storing the result anywhere. You could either store the result of calling the function in a variable and console.log that variable, or you could just call the function in console.log as you did last.

Also you could pass the first and last name as arguments to the function when calling it like this:

var firstName = prompt('What is your first name?'); var lastName = prompt('What is your last name?');

function getLength(firstName, lastName){ return firstName.length + lastName.length; }

console.log(getLength(firstName, lastName));

Hi Basilissa. Thank you for the reply and explanation. Still trying to get the basics down bu after reading your comment i can clearly see the mistakes that i have made. I will practice some more. Thanks again the information.

Edit.

I figure out the problem and here is the new code. Is there a way I could make this even easier ?

var firstName = prompt('What is your first name?') var lastName = prompt('What is your last name?')

function getLength() { var completeName = firstName.length + lastName.length; var nameLength = completeName; return completeName; }

getLength(); console.log(getLength());