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

Why create variable name 'num' ?

that duplicate with input parameter or have another propose? so, how program know the 'num' in return line mean input parameter or the new one?

Nattapol Kamolbal
Nattapol Kamolbal
15,528 Points

Can you share the code or point to the course you're talking about so that we can look at it and maybe explain it to you?

Opp. sorry, I thought this question will show under the video. in topic : MASH Choice and Random Number Functions

script.js

function random_number(num) {  
    // New function called random_choice that takes one parameter, num (or a number)
    // Get a random number between 0 and a passed-in number
    var num = num || 4  // If no number passed in, default to 4
    return Math.floor(Math.random() * num); // Round the answer down (floor) of a random number between 0 and 1 and multiply it by a number. Then return a value and exit the function.
}```

2 Answers

Nattapol Kamolbal
Nattapol Kamolbal
15,528 Points

For what I research on the internet, it's quite acceptable to use this line in this situation. The code is the shorthand of this code

if (!num) {
  num = 4;
}

which will set the default value of num to 4 if num isn't passed to the function or if num is falsy. On my own opinion, I think it's hard to read and quite confusing so you can stick to the full approach not the shorthand one.

To answer on more general of your question. The answer is that you can declare the same variable name as the parameter. I tested this code on the Chrome Console:

function test(num) {
var num = 4;
console.log(num);
}

test(5);

The result is 4. (At first you pass 5 to the function so num is 5, then you declare the same name and the value is 4 so when you log the console the result is 4.)

Although this may work, I can't think of any situation to use this one. It's easier to declare a new variable.

Steven Parker
Steven Parker
229,644 Points

:eyes: Wow, that was hard to read ... refer to the Markdown Cheatsheet (see link below) for future code posts

:point_right: The num on the right side of the assignment is the input parameter, it is referenced before the new one is created. All the other num references inside the function are the new one.

:information_source: I would consider this bad programming practice. I would much rather see the new one have a different name.