Skip to content Skip to sidebar Skip to footer

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.lo

Solution 1:

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.

Solution 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.

Solution 3:

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.

Solution 4:

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

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

equals to:

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

Post a Comment for "Javascript Use Of Variables Basic Functions"