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

Darren Healy
seal-mask
.a{fill-rule:evenodd;}techdegree
Darren Healy
Front End Web Development Techdegree Student 23,565 Points

Some help with Javascript...

Hi folks, just have a quick question re Javascript code. I've got this example below... and I'm racking my brain around the "number" in "return number" - what is this called and how does it not affect the rest of the code??

I think I'm confused by the fact that this function works despite the variable and console below referring to "newNumber".

var timesTwo = function(number) { return number * 2; };

var newNumber = timesTwo(8); console.log(newNumber);

If someone can clarify this simply for me I would appreciate it!

2 Answers

Stone Preston
Stone Preston
42,016 Points
var timesTwo = function(number) { return number * 2; };

This is a function. It takes an argument and returns that argument multiplied by 2. using a return statement means that the function gives a value back to you. you can use that value to assign it to a variable.

the variable inside the parenthesis (number) is whats known as a parameter. you use the parameter inside the body of the function and do stuff with it. When you use the function, you pass in an argument which takes the place of the parameter

the variable below calls the timesTwo function called above and passes in 8 as an argument (note that the number in parenthesis of a function call is known as an argument, but in a function implementation its called a parameter. its important to know this distinction)

//note that we use the return value of timesTwo(8) to assign a value to the newNumber variable
var newNumber = timesTwo(8);

When you pass a function an argument, you can think of the functions parameter being replaced with the argument inside the function. so when we call

 timesTwo(8);

you can look at the function implementation and what happens is the parameter gets replaced with the argument and it returns the argument times 2, which is 16

var timesTwo = function(8) { return 8 * 2; };

you could also pass a variable as an argument:

var someNumber = 10;
var newNumber = timesTwo(someNumber); //returns 2 * 10 which is 20