0

I am trying to print text as binary value on console, but the result is "[object Window]".

console.log(toString(number, 2));
ceklock
  • 6,143
  • 10
  • 56
  • 78
  • By binary value, do you mean the binary ascii value? (ex `a` = `01100001`) – Azeirah Oct 20 '13 at 00:39
  • possible duplicate of [how do I convert an integer to binary in javascript?](http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript) – aljordan82 Oct 20 '13 at 00:49
  • @Azeirah: I mean the binary representation of the number. – ceklock Oct 20 '13 at 00:49

2 Answers2

2

Like most things in JS, toString is a method on the particular object, not a global function. See this MDN page, with examples.

So you want:

console.log(number.toString(2));

What is happening in your code is that it is liooking for some object to call toString on, and finding the "root object", which is window. So your code translates to this:

console.log(window.toString(number, 2));

Since window.toString doesn't take any arguments, they are ignored, meaning it's just like running this:

console.log(window.toString());
IMSoP
  • 89,526
  • 13
  • 117
  • 169
1

toString is a method, not a function. Since calling functions in javascript calls them from the window object, you get [object Window]

console.log(number.toString(2));

will convert a number into binary.

ex:

var num = 15;
console.log(num.toString(2));
> num = 1111;
Azeirah
  • 6,176
  • 6
  • 25
  • 44