2

I'm currently learning JavaScript on Codecademy. On there, it gives an example of a basic variable:

var divideByThree = function (number) {
    var val = number / 3;
    console.log(val);
};

However, it seems to me as if the variable inside the function is unnecessary. Would it not be possible to do this instead?:

var divideByThree = function (number) {
    console.log(number/3);
};

It seems this is cutting out a whole line of code. Would the function still work and if so, why is this not used instead?

7
  • Why haven't you tried first? Commented Jun 26, 2014 at 20:13
  • 4
    Yes, but then you wouldn't be learning about variables... Commented Jun 26, 2014 at 20:13
  • It seems to be showing you how variables are used, but not why they're used. Commented Jun 26, 2014 at 20:13
  • 2
    You are right. The variable is redundant. But as you said this is just for learning code, not a real example. Commented Jun 26, 2014 at 20:13
  • But that sorta defeats the purpose of showing you how to declare and show a local variable. Commented Jun 26, 2014 at 20:14

4 Answers 4

3

It looks like the purpose of that code is simply to demonstrate one way how/where variables are used. Yes, you could just as easily replace the variable for the value. There are certainly times when a variable IS necessary, but I imagine your instructing tool will eventually get to that.

One reason that variables may be assigned in situations where they are immediately used is to give them a name. In this case value is a poor example as well, but there are scenarios where you may be doing complex math or computing to calculate a value, and assigning it a name helps maintain readability.

Another reason is to "cache" the result (especially useful if you're doing DOM lookups), so you do not need to re-compute the value each time you need it.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, the variable is unnecessary. The purpose of the lesson is to teach you the syntax for declaring variables, and the lesson designer chose to do this with the most trivial case possible.

Comments

1

Yes, it would work perfectly. In fact, i often get annoyed when i see unnecessary variables like this in real code.

However, this was done to explain how variables work, so it wouldn't make any sense to avoid the variable.

Comments

0

It is used. you can use values instead of caching it to variable.

function (number) {
    var val = true ? 8*2 + number : function(){ return number + 2 };
    console.log(val);
};

equals to:

function (number) {
    console.log(true ? 8*2 + number : function(){ return number + 2 });
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.