0

I have a quick question about console.log in javascript. The following is the code I wrote:

var multiplied = 5;
var timesTwo = function(number) {
 var multiplied = number * 2;
 console.log(multiplied);
};
timesTwo(4);
console.log(timesTwo(4));

the first function call for "4" works perfectly, the second version, where I call the function through console.log, returns undefined. Is this because console.log only returns statements?

Tomer
17.9k17 gold badges82 silver badges139 bronze badges
asked Mar 19, 2013 at 7:51

4 Answers 4

2

Is this because console.log only returns statements?

console.log doesn't return anything. It just logs its argument to the console. So you should return from your timesTwo the result of the multiplication:

var timesTwo = function(number) {
 var multiplied = number * 2;
 return multiplied;
};

and then:

console.log(timesTwo(4));

Remark: you have declared some multiplied outside of your function (in the global scope) which is never used. You probably don't need it because the multiplied variable that is used inside the timesTwo function is local to the function and the one that gets actually used in this example.

answered Mar 19, 2013 at 7:53
Sign up to request clarification or add additional context in comments.

1 Comment

Just for precision : The problem is that the function timesTwo does not return anything contrary to the version of @Darin Dimitrov.
0

Try this

var timesTwo = function(number) {
 var multiplied = number * 2;
 console.log(multiplied);
return multiplied;
};

You need to return something.

answered Mar 19, 2013 at 7:54

Comments

0

timesTwo(4) did not return anything. So undefined was logged in console.

EDIT: console.log does not return anything, only writes something in the console. Not all browsers have console (i.e. IE), so you should use:

if(window.console){
console.log(" log into console");
}else{
alert("alert as not console available"); // using the alert is up to you
}
answered Mar 19, 2013 at 7:54

Comments

0

console.log() only prints stuff to the console, try using a return statement instead of console.log()

const timesTwo = function(number) {
 return number * 2;
};
answered Feb 10, 2018 at 19:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.