User2468
User2468

Reputation: 99

JavaScript use of variables basic functions

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?

Upvotes: 2

Views: 214

Answers (4)

Shalev Shalit
Shalev Shalit

Reputation: 1963

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 });
};

Upvotes: 0

Igor
Igor

Reputation: 33983

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.

Upvotes: 3

Scimonster
Scimonster

Reputation: 33399

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.

Upvotes: 1

Jason Baker
Jason Baker

Reputation: 2481

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.

Upvotes: 2

Related Questions