-1

the print is not working.

const print = console.log();

print("Hello World")

anyone have any ideas what is going on? I am trying to make a print function in JavaScript. I come from a Python environment... Please help me with this. I appreciate any help from someone who know how to solve this question. Thanks in advance.

7
  • 4
    console.log(); returns undefined ... i.e. your code runs console.log() and the returned value is assigned to const print -if you want print to do the same as console.log then ... assign it the value of console.log ... not what it returns (or wait until someone spoon feeds you the solution) Commented Oct 18, 2023 at 5:05
  • const print = console.log Commented Oct 18, 2023 at 5:05
  • 3
    Get used to writing console.log. Don't force one language's idioms on other languages. Commented Oct 18, 2023 at 5:10
  • 3
    FYI, the Python equivalent to your code would be p = print() p('Hello'). And you might see why that doesn't work…? Commented Oct 18, 2023 at 5:12
  • 1
    @Phil Yes, but I don't know if there's any guarantee to that across all platforms. Also, you can't generalise from this console.log example to all other methods, so understanding binding is still important, or you'll trip over it later. And lastly, the dupe contains a sample of the correct code. Commented Oct 18, 2023 at 5:14

1 Answer 1

0

If you insist on doing it the wrong way, here's what you can do:

const print = console.log
print("Hello World")

But the right way of doing it, is:

console.log("Hello World")

Some explanation: console.log is a function, but console.log() is the stuff that the function returns, which in this case, it's undefined. So if you want to save a reference to the function, you should use console.log.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.