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?
4 Answers 4
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.
1 Comment
timesTwo does not return anything contrary to the version of @Darin Dimitrov.Try this
var timesTwo = function(number) {
var multiplied = number * 2;
console.log(multiplied);
return multiplied;
};
You need to return something.
Comments
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
}
Comments
console.log() only prints stuff to the console, try using a return statement instead of console.log()
const timesTwo = function(number) {
return number * 2;
};