I am very new to JS.
I ran into something strange, while learning about console.log behavior. Console is very important for me, because I believe that if console.log does not see it, then it is not there. I will start with simple things, just to make sure I do not miss anything.
Assumption: console.log can print results of simple calculations.
console.log(1+0); //1. Console.log can calculate!
Assumption: console.log can print results of functions, if those return values.
var test = function(a,b){
var c = a+b;
return c;
};
console.log(test); //prints the assigned value of the variable "test", which happens to be a function and thus function code is printed. Function is NOT called here.
console.log(test()); //prints NaN, since the function is called but no arguments are provided. Thus, JS is unable to calculate the result.
console.log(test(1,1)); // this one prints the result of the function, which is variable "c"
console.log(test(1,1) + 2); //I can then manipulate results further in the console.
Assumption: with closures there is a problem?
var testClosure = function(a,b){
var c = a+b;
return function(){
var d = c + 1;
return d;
}
};
console.log(testClosure); //so far standard behavior - console prints the assigned value of a function - its code.
console.log(testClosure()); //trying to call the function here without arguments. Expected result that it will attempt to calculate "d" and return NaN (since it cannot calculate), but it returns the code for the anonymous function. JS does not attempt to do calculation.
console.log(testClosure(1,2)); //does not produce the expected result of 4. It produces same output as in the previous case. JS does not attempt to do calculation for some reason.
var result = testClosure(1,2);// Do I understand it correctly that at this point I only create a reference but testClosure() function is not actually launched? Therefore, variable "result" does not have any meaningful value yet?
console.log(result); //printing the assigned value of this variable, which is the code for the anonimous function in testClosure().
console.log(result()); // here I am actually calling the testClosure() function by proxy and get the desired result of 4.
My main questions are
Why does
console.log(test(1,1));
work and
console.log(testClosure(1,2));
does not?
Why does
console.log(testClosure(1,2));
does not work but
var result = testClosure(1,2);
console.log(result());
does work.
I seem to be doing essentually the same thing: calculate given the provided argument and print the result.
Where is the key difference I am missing, since I obviously do?
test is a function, which returns a value, but testClosure is a function which returns a function which returns a value. Function in JS is a first class object, which means that it also can be used as an argument, assigned to a variable or returned from a function (that's what you do in your closure example, you return a function, not the value). But to get a value of this returned function you have to call it too, it does not call itself.
console.log( typeof test(1,2) ); // number
console.log( typeof testClosure(1,2) ); // function, which also needs to be called
console.log( typeof testClosure(1,2)() ); // number
// ---------------------------------^-----// call the returned function
1) because you are logging the result of executing the function, which returns the expected value.
2) because you are logging the result, which in this case is a function, you need to then execute this function to get the desired value - try doing console.log(testClosure(1, 2)());
Related
I'm still new to Javascript so please forgive me if this seems like a silly question.
I defined a function called randomNumberGenerator, and in it is just one line of code. Basically, the purpose of it is to return a number between 0 and 2.
function randomNumberGenerator() {
return Math.round(Math.random() * 2);
};
However, when I tried to log the result of this function in my console, it shows me the outline (is that what it's called) of that function instead of a random number. You can see it here:
ƒ randomQuestionSelector() {
return Math.round(Math.random() * 2);
}
I tried assigning 'Math.round(Math.random() * 2)' to a simple variable, and logging that variable to the console. It worked as expected (I got a random number), so I'm confused why doing the same with a function doesn't.
Hope someone can help me out with this. Thank you!
The reason why console.log(randomNumberGenerator) returned such a value is that you did not really invoke this function. You called the default .toString() method which exists on every object. And default implementation (which can be overriden) returns what you saw in the console. If you want to get the result of the function you need to use () operator which calls the function, like this:
randomNumberGenerator()
And to capture the returned value you can assign it to the variable, for example:
const random = randomNumberGenerator()
console.log(random);
That way you are calling the function and assigning the returned value to the new variable.
You need to call the method. What you are likely doing is calling console.log(randomNumberGenerator) rather than console.log(randomNumberGenerator())
I don't know if I chose the right title for this question, and maybe this is why I cannot also find an answer to this question.
While reading a javascript book, I found this example while talking about closures.
function multiplier(factor){
console.log('factor:'+factor);
return function(number){
console.log('number:'+number)
return number * factor;
};
}
var twice = multiplier(2);
console.log('twice:'+twice(5));
And in console I get this output:
factor:2
number:5
twice:10
I understand what a closure is meant to be, but I do not understand how the variable number, that by my knowledge I expected to be undefined, get the value 5.
My reasoning is the following:
When I call the function multiplier(2) the local variable factor is assigned the value 2, so the first output is correct.
But when it reaches the line return function(number){ it shall assign number undefined, since no value has been previously assigned to such a name.
So it shall crash at all, and not doing correctly the output I got.
May anyone help me understand why calling twice(5) it get the output
number: 5?
Thank you all, excuse me again If i did not post the question in the right way, feel free to modify anything to make this question more intelligible.
return function (number) { ... } returns a function. number is not a variable, it's a function parameter. The same way that factor in function multiplier(factor) is a parameter. It is neither undefined nor does it cause anything to crash either.
In essence, multiplier(2) returns this function:
function (number) {
console.log('number:' + number)
return number * 2;
}
...which you assign to twice, so twice is now the above function.
I think the key thing that you're missing here is that the returned function acts just like any other function. The function isn't entered until it's called.
return number * factor;
doesn't run until you call twice. It's just like how
console.log('factor:'+factor);
doesn't run until you call multiplier. The body of the function isn't entered until the function is called. number doesn't have a value until twice is called, but the code that uses number also doesn't run until twice is called.
But when it reaches the line return function(number){ it shall assign number undefined, since no value has been previously assigned to such a name.
Here's the misunderstanding. Remember: In Javascript, almost everything is an Object. Some will say that many things that you interact with regularly (strings, numbers, booleans (Notice how I put these types/primitives/words first letter in lowercase. I usually use uppercase for Classes and lowercase for primitives)) are primitives, not objects. This is true, but for the purpose of this thread let's consider (almost) everything is an Object.
Let's get back on this sentence you wrote:
when it reaches the line return function(number){ it shall assign number undefined
Here's the issue: when it reaches the line "return function(number){}", it actually returns a function, which is an object.
It does not execute this function, it only declares it, and returns it, as an Object.
You could have wrote "return 666", it would have returned an Object. A Number.
Let's continue.
Your variable "twice" now contains a function. Guess which one. This one:
function(number){
console.log('number:'+number)
return number * factor;
}
Remember, you've declared it and returned it in only one statement:
"return function(number){...}"
Your "twice" variable is now equivalent to a named function you could've declared this way :
function twice(number){
console.log('number:'+number)
return number * factor;
}
Yes, functions are Objects, named functions are like named variables, and variables can be functions.
You can call it this way for example: twice(9), or this way: twice(5).
That's what you've done.
Now let's answer your question:
why calling twice(5) it get the output number: 5?
Because:
var twice = function(number){
console.log('number:'+number)
return number * factor;
}
And you've executed "twice(5);" which in turn executed console.log this way:
console.log('number:'+5);
As far as I've understood, in your "function multiplier()", you do not want to return a function but rather the result of this function itself. I advise you to read about IIFE (Immediately-invoked function expression).
With this you will be able, in only one statement, to:
- declare a function
- execute that function
- (and eventually return its result)
Have fun playing with Javascript. Javascript is great, only when you know what's going behind.
I am now beginning my JavaScript path and have a question on usage of variables in Console.log
How can this code give me an error?
var myAns = console.log(65/240);
console.log(100* +Number(myAns) );
If I am assigning output of the Console.log to the variable 'myAns' cannot I use that as a reference in another Console.log?
I searched elsewhere and saw that I needed to use another +operator right in front of the value (didnt work) or that I needed to input the Number() method in place (didnt work)
And the error I am getting is just: NaN
I believe I am Passing by reference, or is that the scope problem?
If I am assigning output of the Console.log to the variable 'myAns' cannot I use that as a reference in another Console.log?
In order to do this you would need to override the default console.log() function. Another, easier approach would be to do:
console.log(myAns = 65/240)
As in, console.log the result of assigning 65/240 to myAns.
Right now, you're doing var myAns = console.log(65/240); which, as Bergi mentioned, assigns the return value of console.log(65/240) (undefined) to myAns.
You are assigning return value of "console.log" to myAns. It doesn't return the result of the calculation. What you need is:
var myAns = 65/240;
console.log(myAns);
var myOtherAnswer = 100 * myAns;
console.log(myOtherAnswer);
IF a specific function has a return statement with a return value, then it will return that value once that function is being invoked from somewhere..
console.log just logs (displays) the value passed inside the parenthesis of the console.log(....) to the browser.
console.log() doesn't assigns a value back to a variable...
var value = console.log(100);
here it just displays the 100 on the browser but nothing will be assigned to value variable..
Hi i have been exploring closures and javascript core concepts i couldn't understand why does the console.log(factory[i]) outputs undefined i have pushed my function inside there right? And if i call temp outside the loop it says undefined whereas if i call inside the loop it returns am bit confused can anyone explain me?Here is my code
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i]);
}
factory.push(temp());
}
temp();
console.log(factory);
for(var i=0;i<factory.length;i++)
{
temp(i);
console.log(factory[i]);
}
https://jsfiddle.net/kh3okLca/
You are not passing function but the result of the executed function temp() as it don't return anything its undefined. change factory.push(temp()); to factory.push(temp);
The temp() outside return undefined because by that time loop has executed and the value of i is 2 check this following piece of code which logs value of i.
var fruits=["apple","orange"];
var factory=[];
for(var i=0;i<fruits.length;i++)
{
var temp=function()
{
console.log(fruits[i],"console",i);
}
factory.push(temp);
}
temp();
console.log(factory,"factory");
for(var i=0;i<factory.length;i++)
{
temp(i); //i resets to 0 here in same scope
console.log(factory[i](i),"factoryi"); //this doesnt return anything so its undefined but statements are executed
}
Here is the output you have.
//next two executed due to factory.push(temp()) in first if loop
& there is a console.log there inside the function
apple
orange
//here i++ in first loop will be 3, but array have only two element, so it is undefined
undefined
// due to console.log(factory)
// temp function is actually returning undefined,
[undefined, undefined]
// due to temp(i) in second if block
apple
// but factory array is stil empty so factory[i] will be undefined
undefined
from temp orange
undefined
Closure are nothing but function with preserve data. Till now a function is treated as peace of code which takes input and produces some output ,for every function call this code remain same, but closure gives you opportunity to save some data with the function which can be changed so that for each function call it will react differently, keep that in mind everything will be easy .
Suppose you have a function that finds rate of interest , but this functions is used by three teams whose interest rates are different, So in general what we do we pass the team name with the principle amount , each and everytime we have to pass the team name , So by using closure we can three instance of a function for each team (team name as a preserve data ) and now only send the principle amount and get the interest calculated according to the team, I a moment i will add example also,
It's a petty basic question which seems I don't fully understand,
What exactly is the use of return? In what cases should I use it?
What would the difference between these code samples be?
function fun(text) {
console.log(text);
};
function fun(text) {
return console.log(text);
};
To be clear: I know what return does, I just don't feel like I fully understand it's purpose and when should I use it
You should use return if your function needs to, well, return anything to its caller. In your example, it's not necessary to use return because console.log already does what you want it to do. But, if your function calculates something (for example a mathematical operation like adding the first two params it receives), it's logical it "returns" the result, like this:
function add(a, b) {
return a + b;
}
This way the function caller can use the result for whatever it's doing.
return is used to send a value back to where's it's called from. You use it if you want to return a value.
If you don't have a return statement, it's the same as return undefined. console.log returns undefined, so return console.log(text) returns undefined.
So, only return if you want to get a value from the function.
return exits from the function, possibly with a value.
Lets say we have these two functions:
function foo(a, b) {
return a + b;
}
function bar(a) {
if (a > 10)
return;
// Do something with 'a'
}
If the first function, foo, return exits the function and the result of calling the function (e.g. var c = foo(1, 2)) is the result of the expression given to return, in this case the sum of a and b.
In the second function, bar, return is used to exit the function if a is larger than 10, but otherwise execution of the function continues. It doesn't return with a value like foo, so using bar as part of an expression could result in an error.
return halts the execution of the function and defines the value that is returned as the result of calling the function.