最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Multiplying a variable by number inside a console.log on javascript - Stack Overflow

programmeradmin7浏览0评论

I wish I could log to the console the result of a multiplication of a number by a variable but I get NaN as a result while using Javascript.

My attempt:

var div = Number(console.log(10 / 50)); //returns 0.2
typeof div //number
console.log(div * 100); //returns NaN

I also tried

var div = Number(console.log(10 / 50)); //returns 0.2
typeof div //number
console.log(Number(div) * 100); //returns NaN

Why is it happening and how should I avoid it?

I wish I could log to the console the result of a multiplication of a number by a variable but I get NaN as a result while using Javascript.

My attempt:

var div = Number(console.log(10 / 50)); //returns 0.2
typeof div //number
console.log(div * 100); //returns NaN

I also tried

var div = Number(console.log(10 / 50)); //returns 0.2
typeof div //number
console.log(Number(div) * 100); //returns NaN

Why is it happening and how should I avoid it?

Share Improve this question asked Aug 14, 2017 at 14:07 pedrezpedrez 3691 gold badge6 silver badges17 bronze badges 3
  • You could define your own function tap = x => (console.log(x), x) and use it instead of console.log var div = Number(tap(10 / 50)); – Yury Tarabanko Commented Aug 14, 2017 at 14:11
  • Thanks, but what I was looking for required me to log a step by step result. That solution would give me only the final result. – pedrez Commented Aug 14, 2017 at 14:36
  • It will give whatever result you use this function on. – Yury Tarabanko Commented Aug 14, 2017 at 14:40
Add a ment  | 

4 Answers 4

Reset to default 5

The console.log() function returns undefined, so Number(console.log(anything)) will always be NaN. Your code assumes that console.log() returns the value that it wrote to the browser developer console, but that is not the case.

Also, probably counter intuitively, NaN is a number, so typeof NaN is "number". Your code tested the return value from Number(console.log()) and it was in fact a number, but that number is NaN.

console.log only display the result and returns undefined.

Try directly:

 var div = Number(10 / 50);

var div = Number(10 / 50); //returns 0.2
typeof div //number
console.log(div * 100); 

console.log() does not return a number, and so you get a NaN error.

You can instead do:

var div = Number(10 / 50);
console.log(div * 100);

Hope this helps!

A small workaround:

 function log(...values){
  console.log(...values);
  return values.length === 1 ? values[0] : values;
}

So you can do:

var a = log(5/10)*2;
log(a);
log(log(1,2)[0]+3)

Alternatively, do it the other way round:

 var a;

console.log(
  a = 10/50,
  10*a,
  11*a
);
发布评论

评论列表(0)

  1. 暂无评论