r/javascript • • Dec 16 '18

Coming from Python to JS NSFW

const print = console.log

I found my safe space.

607 Upvotes

156 comments sorted by

337

u/Pavlo100 Dec 16 '18

Here is the Java implementation for those who want to make their life harder

const System = {out: {println: console.log}};
System.out.println("why?");

98

u/blasto_blastocyst Dec 17 '18 edited Dec 17 '18
import com.half.your.ram.is.gone.for.no.reason;

4

u/unquietwiki Dec 17 '18

Must install outdated JDK, to support libraries not updated since 2006 on SourceForge...

2

u/YasZedOP Dec 17 '18

Could you explain why this would result in more RAM usage?

4

u/LaSalsiccione Dec 17 '18

It’s a joke about Java/JVM being memory hungry I believe

0

u/jasie3k Dec 17 '18

Oh, JaVa iS BaD circlejerk.

0

u/[deleted] Dec 17 '18

[deleted]

211

u/themaincop Dec 17 '18
Java apps      Javascript apps 
           🤝  
    Using half your ram
   for no goddamn reason

69

u/rangeDSP Dec 17 '18

A text meme. This is amazing

13

u/mutexjp Dec 17 '18

shots fired

6

u/placidified Dec 17 '18

Was using VS Code to as my editor for our Python backend. VS Code kept using 10GB of memory !

Switched to PyCharm.

13

u/PM_ME_HTML_SNIPPETS Dec 17 '18

Oddly enough, I don’t think I’ve ever had that problem with Code, but have had a few runaway memory sessions with ST3.

9

u/AlexAegis Dec 17 '18

there was a bug a month or two ago in the Python Language Server which caused heavy memory leaks. Probably still has some issues.

37

u/loopsdeer Dec 17 '18 edited Dec 17 '18

Shouldn't that err? I think you need console.log.bind(console). On mobile, can't test. I just don't want to give Java'rs anymore ammunition

Edit: Wow I've never been more excited to be wrong and to be down-voted. I'm not sure when this bug was fixed, but FOREVER this would have caused Illegal Invocation error. If you don't believe me, just search "console.log illegal invocation". Another one to throw on the "well, in my day..." pile. Yay!

20

u/[deleted] Dec 17 '18 edited Dec 17 '18

Stop downvoting him, assholes.

This didn't work without binding up until, if I'm not mistaken, Node.js 8.x. I don't remember it causing any errors, if I remember correctly it used to silently fail (i.e. not print anything because the log function would simply log to global).

Then at some point log() didn't depend on console being it's this. I've never seen a single sentence of explanation why this was changed, I've never used this kind of aliasing in browser so I'm not even sure it's a Node.js console implementation bug or a V8 bug, nor how Firefox behaved before (doesn't need bind() now).

So he was right.

Edit: Ah, yes, just needed to scroll down and find another post re the same thing and presto:

https://chromium.googlesource.com/chromium/src.git/+/807ec9550e8a31517966636e6a5b506474ab4ea9

3

u/loopsdeer Dec 17 '18

Aw thanks for the defense! Ya I looked through the chromium and firefox bugs and it looks like these have been very quietly resolved within the past year and a half.

But as I said in my edit, this is just one more thing on the "in my day" category now. For those of us using JavaScript since before jQuery, that category is quite huge and ever-growing. It's actually kind of delightful to be wrong in this way.

7

u/[deleted] Dec 17 '18

I'm no Samaritan tho, just extremely irritated by immature Reddit behavior of downvoting people out of own ignorance. Downvoting non-abuse is bad enough, but this really makes my blood boil sometimes.

3

u/loopsdeer Dec 17 '18

Why don't we walk together back to r/pcj friend, and blow off some steam. We can kick some rust crates over on the way.

2

u/[deleted] Dec 17 '18

Yeah. /r/javascript is such a toxic place. Nobody truly embraced the Script here from what I see.

2

u/ESCAPE_PLANET_X Dec 17 '18

The more technical a sub is, the more the reflexive downvote behavior is present.

Especially in broad subs where I assume people are just full Dunning Krueger -ing it.

2

u/kingocad Dec 17 '18

My favourite “in my day” was this IE6 bug that caused IE6 to lose the name attribute when manipulating form dom elements, they would never submit but would be visible in the developer toolbar. Trying to track this down pre-stackoverflow was a nightmare!

I still have PTSD form that one!

6

u/EriktheRed Dec 17 '18

Works in my browser console

4

u/loopsdeer Dec 17 '18

Thank you for checking. Just got to my computer to test and yes! No error! See my edit for why I am excited

2

u/MonkeyNin Dec 18 '18

I'm all about economy of characters, so I use

Ω = console.log.bind(console)
Ω("hi world")
// hi world

1

u/MRGrazyD96 Dec 17 '18

nope, absolutely no need for binding

4

u/loopsdeer Dec 17 '18

Well this is exciting! See my edit

4

u/rodrigocfd Dec 17 '18

My browser tripled its memory usage by showing this piece of code.

3

u/[deleted] Dec 17 '18

What is wrong with your whole family line?

0

u/[deleted] Dec 17 '18

[deleted]

6

u/sh0rtwave Dec 17 '18

So, which is it gonna be? The language itself? Or the runtime? I've seen the language itself be, well...never really that fast, but kinda OK. I mean once you get it up and going...(disclaimer: Have written much Java code, and once-upon-a-time liked it. I don't know what was wrong with me. Then I picked up As3, which is like Flash + Java. Again, I'm not right.).

To be fair though, I've had that same thought about Python...the indents. Don't get me started about way back in the day trying to work with a team that had all different editor setups, and then 3 people edit the same file in one day, and the whole server goes down. I just wanted to seize Guido every now and then and shake him and say "What the hell is wrong with you?".

2

u/Treolioe Dec 17 '18

Java is a snail in many ways

0

u/[deleted] Dec 17 '18

[deleted]

5

u/sh0rtwave Dec 17 '18

I did not know this! Fascinating! Did you know that nearly 99.928% of Reddit has no idea what what a sarcastic rebuttal even looks like, or understand the art of conversation and context?

I got my data by just reading Reddit. How'd you get yours?

0

u/[deleted] Dec 17 '18

[deleted]

5

u/sh0rtwave Dec 17 '18

What gives you that idea?

84

u/uberpwnzorz Dec 17 '18

you need to use bind so the log function keeps the context of console.

const print = console.log.bind(console)

6

u/jetpacmonkey Dec 17 '18

Is this still true in every browser? I've noticed in Chrome that I can do promise.then(console.log), and I'm pretty sure that didn't work a few years ago.

10

u/LiverReich Dec 17 '18

This comment needs a lot more appreciation

5

u/username_is_taken43 Dec 17 '18

Yeah, don't hide the beauty of Javascript

1

u/bart2019 Dec 17 '18

Except, console doesn't care, afaik.

7

u/theXpanther Dec 17 '18

It does, there was a stack overflow question about someone forgetting to bind

6

u/maple3142 Dec 17 '18

I think it depends on your javascript engine version. http://www.reddit.com/r/javascript/comments/a6txtp/-/eby144i

3

u/minuskruste Dec 17 '18

It depends on the context. It also won’t throw an error but it won’t work in some cases either. Particularly if you pass console.log as a function to a tap in an observable pipe.

0

u/[deleted] Dec 17 '18

[deleted]

2

u/uberpwnzorz Dec 18 '18

it's a prototype function, technically. MDN calls it a function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

Classes and Methods are just sugar for prototype in JavaScript

1

u/saadq_ Dec 17 '18

A method is a function though

41

u/kuanysh2210 Dec 16 '18

Needs more appreciation.

20

u/Capaj Dec 16 '18

you can go even further: global.print = console.log even though it's probably not the best idea to pollute your global ;-)

10

u/[deleted] Dec 16 '18

...where is the global?

19

u/joelangeway Dec 16 '18

Iirc that works in node.js like window works in the browser, in that it’s synonymous with the global scope.

4

u/[deleted] Dec 17 '18

Ah right!

6

u/nickbreaton Dec 17 '18

If you're interested, there is an ECMAScript proposal to add globalThis so the same variable can be used for both node and the browser (or whatever JS environment you're in).

https://github.com/tc39/proposal-global

1

u/baubleglue Dec 17 '18

global || global = window;

6

u/Rezistik Dec 16 '18

In Node. Attach it to the window on the browser.

2

u/bart2019 Dec 17 '18
global = window;

94

u/mishugashu Dec 16 '18

If I came across that shit at work, I'd git blame in a heartbeat and tell you to never do that again.

But if you're doing it in personal projects, more power to you, I guess. Nothing really wrong with it code-wise.

193

u/[deleted] Dec 16 '18

That's why it's marked NSFW!

54

u/Uhh_derp Dec 16 '18

Lol now I get it

16

u/yoda_of_usernames Dec 17 '18

checks out username does

2

u/willtoshower Dec 17 '18

Can I get a checks out on username?

4

u/kchoudhury Dec 17 '18

He aliased a function and it is amply obvious what it does. What standard did he violate?

5

u/mrbojingle Dec 17 '18

none, some people are just anal.

4

u/vellian Dec 17 '18

He's adding complexity with almost zero benefit. You have to look at the definition to see exactly what it does. Don't change the code for something like that. Change yourself. If it were something more complicated from another language that's complex then that's great. Don't do it for trivial shit like this.

Someone else pointed out that not binding this may cause problems. So he possibly introduced bugs as well.

Yeah it's a joke, but no, you should never do this.

6

u/kchoudhury Dec 17 '18

"Change yourself"

I hate this attitude so much. Programming languages and compilers are there to work for us, not the other way around.

5

u/vellian Dec 17 '18

You're adapting for other people, not languages or compilers. If you're working on a team you have to take this attitude. If not, you're more free to do what you want.

0

u/spazz_monkey Dec 17 '18

There's a dude at my work who did this in production code.

self = this

16

u/_xiphiaz Dec 17 '18

This used to be super common when creating JavaScript libraries before modules and arrow functions; it was used to maintain a reference to the parent scope for use within a callback function

2

u/spazz_monkey Dec 17 '18

Fair enough, I assumed it was coz he loves python

1

u/alejalapeno Dec 17 '18

I prefer(ed) _this = this

1

u/fluxxis Dec 17 '18

Such a thisish behavior!

1

u/[deleted] Dec 17 '18

Narc

1

u/username_is_taken43 Dec 17 '18

Good thing we don't work together.

0

u/[deleted] Dec 17 '18

[deleted]

26

u/placidified Dec 17 '18

console.log(error) // eslint-disable-line no-console

cries in legacy code

3

u/Morphray Dec 17 '18

You forgot eslint-disable-line semi also

2

u/Anaphase Dec 17 '18

nah, that's in the base rules #fucksemicolons

5

u/Bonsoir_Elliott Dec 17 '18

Genuine question: why is it bad to have ‘console.log’ in the code? Is it bad to generate logs in a Node app?

5

u/FrancisStokes Dec 17 '18

Console logs do not have a level associated with them, so you have no way to run your app with only error logs, or with debugging information. That makes it easy to not only write bad logs, but to get to a situation where you can't remove a bunch of related but distributed logs without some effort. Basically, logging without levels and organisation leads to bad code hygiene.

6

u/13steinj Dec 17 '18

Aren't the 4 levels info, error, warn, (output to stderr), and log (output to stdout)?

1

u/Haramboid Dec 17 '18

Yes but that’s not very versatile. A good logger usually has multiple channels, separate from levels so you can categorize logs on the process you’re actually trying to debug.

4

u/mrbojingle Dec 17 '18

like console.group?

1

u/13steinj Dec 17 '18 edited Dec 17 '18

Well thats silly.

You can create any kind of grouping with console.group and console.groupEnd() if thats whag you mean, otherwise you either mean separate files or prefixed messages.

Which you can easily extend the console object to do, which you would extend by using one of the levels I mentioned.

If you mean to separate files, that's by definition not what the console is for.

Neither of which are a part of yourthe original argument~~, so you're moving the goalposts here. But okay~~.

E: I need to learn to read usernames.

1

u/mishugashu Dec 17 '18

Exactly. It's a useless alias of a function that shouldn't be checked in in the first place.

0

u/davidpaulsson Dec 17 '18

Who cares any more when there's babel-plugin-transform-remove-console

22

u/BloodAndTsundere Dec 16 '18

I actually kind of like this because I always manage a typo when I type 'console.log'. I get a lot of 'cosnole.log'. I think I'm much more consistent typing 'print'.

26

u/Earhacker Dec 16 '18

VS Code, Atom and the like usually have a snippet that autocompletes when you just type "log".

2

u/ItsReallyEasy Dec 16 '18

Sweet! Enabled by default on VS Code? Gets me closer to muscle memory of Lombok as a Java dev

2

u/killchain Dec 16 '18

WebStorm has one also, you just append .log to the whole expression.

0

u/[deleted] Dec 16 '18

[deleted]

33

u/Earhacker Dec 16 '18

You could go to Menu -> Preferences -> User Snippets -> JavaScript and add this to the file:

"Print to console": {
    "prefix": "print",
    "body": [
        "console.log('$1');",
        "$2"
    ],
    "description": "Log output to console"
}

And now every time you type "print" in a JS file it will autocomplete to "console.log()" with your cursor between the brackets.

Safe space safely restored!

0

u/[deleted] Dec 16 '18

[deleted]

16

u/Earhacker Dec 17 '18

for loops are for dirty Python casuals. Over here in JavaScript we use Array.prototype.forEach.

(but sure, we use your fornum loop sometimes too)

4

u/mrbojingle Dec 17 '18

eww. map ftw! Unless you want to run print, then forEach away!

2

u/Earhacker Dec 17 '18

They’re not exactly interchangeable

0

u/linuxdropout Dec 22 '18

If you want your code to be approximately 90% slower -_-

1

u/linuxdropout Dec 22 '18

1

u/Earhacker Dec 23 '18

If you really need those milliseconds, forEach is not your only problem. Performance isn't everything.

1

u/linuxdropout Dec 23 '18

It's not a matter of milliseconds it's that it's an entire magnitude slower. Sure if you're just doing a single foreach loop then it is what it is. But if you're doing a "common pattern" of filter -> map I've seen all over code bases. And then you do that in 10 different places on a front-end application, all at page load time. All of a sudden you've added an entire second to time-to-interactive.

I get the whole maintainability thing. And there are plenty of places that it ends up being much cleaner and easier to maintain using map/filter/reduce/foreach. And in some places you can add functionality with callback chains or async-await.

But it's something to be aware of that I've seen many more developers just use Array functions as the "default" without thinking.

0

u/[deleted] Dec 17 '18

[deleted]

8

u/Earhacker Dec 17 '18

You monster.

6

u/MrStLouis Dec 17 '18

Use const in for loops you filthy animal

1

u/restart_kun Dec 18 '18

Sorry for this noob question. I always see let in for loops so I thought that was the best so why const?

2

u/MrStLouis Dec 18 '18

I'm not entirely sure, and I think at some point the specs changed on it. The only for loops I think you can use const in are the for of and maybe for in. It's due to the nature of how that variable is scoped. Technically in a basic i<=length for loop you use the same i-variable over the course of the loop. With the other loops, each loop has its own version of the iterator. Using const is a good way to denote this technical difference in the loop, but in practice it's only really a safeguard to not change the iterator in your code. It doesn't affect anything other loop in the series to change it though. An interesting example would be to run each loop logging the iterator from a settimeout function. For 5 iterations the i-loop would log 4 5 times whereas the for of would log 0,1,2,3,4; because it is technically logging each loops unique iterator (sorry on mobile)

→ More replies (0)

3

u/[deleted] Dec 17 '18

I did the same thing when I started learning react and found a nifty autocomplete vscode addon. I thought “wait, how are these snippets generated?”

Somehow it never occurred to me that I could write boilerplate snippets for other languages until this point.

Super handy way to cut down on typing and dumb mistakes.

2

u/mrbojingle Dec 17 '18

Right!? It's so useful. I've got my most common stuff all made into snippets that are context sensitive (using some regex magic), so if I hit { inside an object it gives me `: { }`, in a function `const = {}`, in an array or parens {}. It's pretty sweet.

1

u/CrazyFarmer__ Dec 17 '18

Sounds like me when typing clear in my terminal. After some time I just created aliases:

  • clear

  • celar

  • claer

  • clera

  • ...

1

u/[deleted] Dec 17 '18

I keep typing "functino" all the time.

1

u/BloodAndTsundere Dec 17 '18

That's the supersymmetric partner to the function

1

u/MonkeyNin Dec 18 '18

Do you have a linter enabled?

0

u/[deleted] Dec 16 '18

[deleted]

26

u/filleduchaos Dec 16 '18

Yes officer, this post right here

5

u/killchain Dec 16 '18

Almost like npm isntall is a default alias for npm install.

8

u/GabrielChiconiDev Dec 17 '18

Why doesn't everybody npm i though?

4

u/killchain Dec 17 '18

I do. At one point I was so lazy that I even had ni alias for the same thing.

2

u/mrbojingle Dec 17 '18

The fewer characters the better.

1

u/diatu Dec 17 '18

Are you trying to reinvent bash commands? Cause that's how you get bash commands!

edit:pnctatn

2

u/mrbojingle Dec 17 '18

Yes! All my bash aliases are 1-3 chars abbrivations. I also made a nice aliases builder that takes a name and my last run command and sticks a new alias in my bash_aliases file. It's pretty sweet.

1

u/MonkeyNin Dec 18 '18

The Knights who say ni

2

u/killchain Dec 18 '18

NI! NI! NI! NI NI

0

u/[deleted] Dec 17 '18

[deleted]

2

u/killchain Dec 17 '18

Npm isn't all. There's also yarn and pnpm.

2

u/robolab-io Dec 17 '18

git blame

5

u/basyt Dec 17 '18

The horror

5

u/Shivam_RawatOxox Dec 17 '18

why the fuck nsfw

7

u/I_AM_GODDAMN_BATMAN Dec 17 '18

Because if you commit this, me and other developers will come to your table and beat the shit out of you.

14

u/Asmor Dec 16 '18

This won't work. Or at least, it didn't used to work. I haven't tried it in a very long time.

You'd need to do print = console.log.bind(console).

16

u/konaraddio Dec 16 '18

It works

I think you only need the .bind if console.log were to use this in its implementation

15

u/dvlsg Dec 17 '18

It used to need the bind. That was a recent-ish change, IIRC.

2

u/imguralbumbot Dec 17 '18

Hi, I'm a bot for linking direct images of albums with only 1 image

https://i.imgur.com/YMlhou8.png

Source | Why? | Creator | ignoreme | deletthis

0

u/[deleted] Dec 16 '18

[deleted]

5

u/cyphern Dec 17 '18 edited Dec 17 '18

Should be fine on modern javascript engines, but older ones can still have a problem with it. I just ran into a bug with this recently at work. I was porting some code over to a smart tv, and it threw an exception. The cause was an un-bound console.log (and console.warn and console.error) function.

3

u/bart2019 Dec 17 '18

And with browsers' tendency of constantly updating... Who cares about old browsers?

Especially since this is functionality for yourself, not for random visitors to your site.

0

u/[deleted] Dec 17 '18

[deleted]

2

u/Asmor Dec 17 '18

Honestly, it's even better to just not do this in the first place. If you're gonna screw with it, might as well wrap it in a function. That also gives you some extra control, like having a variable for debug level and silently eating logs below the level you care about.

6

u/bart2019 Dec 17 '18

That nsfw tag, is that a joke?

0

u/[deleted] Dec 17 '18

[deleted]

3

u/mrbojingle Dec 17 '18

If you were the owner of the company would you allow it? :P

3

u/bart2019 Dec 17 '18

I don't come from Python... So, "no".

But as this is for interactive debugging, I don't see ham in a shorthand. I'd even dare to use "p" or something equally short.

1

u/[deleted] Dec 17 '18

A non-exhaustive list of reasons this would be a bad idea in the workplace:

  1. These shenanigans will make your code illegible to other developers 1A) If you're only used to your own special syntax, it'll be harder for you to sight read other people's code.

  2. What if you decide you want to use 'p' for something else? Why reserve such a common letter (or word, in the case of 'print')?

  3. Most text editors will allow you to autocomplete to console.log in a keystroke or two anyway

Never assume that you're going to be the only person working with or reading your code, even in "personal projects." You never know when you're going to want to reuse that code, get help, or how projects might expand. Also there's no reason to accustom yourself to bad practices or syntax you'll never encounter in the workplace.

3

u/[deleted] Dec 17 '18

This needs console.log.bind(console) though, doesn't it??

3

u/[deleted] Dec 17 '18

If you forget this line and just print('something') it opens the printer dialog. I sometimes do this by accident after coding in Python for hours and it's funny.

3

u/m_elange Dec 17 '18
window.onerror = window.close;

For that native feel.

2

u/[deleted] Dec 17 '18

for the win..

2

u/JackAppDev Dec 17 '18

I used to do this coming from swift as my first language

2

u/Ncell50 Dec 17 '18

Stupid me always wrapped console.log inside a new print function

2

u/messified Dec 17 '18

Bahahaha 🤦‍♂️

2

u/evenisto Dec 17 '18

Delet this

2

u/[deleted] Dec 17 '18

Why is this even nsfw lol

2

u/MonkeyNin Dec 18 '18

Because it's bad for work.

2

u/Hegemon1984 Dec 17 '18

Why is this labeled NSFW?

I thought we were going to see programmed porn.

2

u/ImStifler Dec 17 '18

This probably speaks to alot of programers on a spiritual level

3

u/IrishLimey Dec 17 '18

Here's a global version that will output the correct line number in the console as well:

(typeof global !== 'undefined' ? global : window)['print'] = (function() { return Function.prototype.bind.call(console.log, console); })();

1

u/senocular Dec 17 '18

aaaaand now I can't print my page.

1

u/IrishLimey Dec 18 '18

Meh, print is dead.

1

u/tredditr Dec 17 '18

How is this not safe for work?

1

u/Kwantuum Dec 17 '18

Print already works like console.log on firefox.

1

u/prof_hobart Dec 17 '18

I once worked with someone who hadn't quite got over the change curve from Pascal to C, so he had a header file full of things like

#define BEGIN {
#define END }

Unfortunately he was the boss, so this was what we were all expected to use.

1

u/enricojr Dec 18 '18

I love the little 'nsfw' tag on this post hahaha

1

u/cdxgqvuoqifnmfsytuwm Dec 22 '18

const trace = console.log;

If you come from ActionScript 3.

1

u/[deleted] Nov 09 '23

Print could refer to anything.😢 How about "len", globally defined shortened naming is horrible.

1

u/spacejack2114 Dec 17 '18

If you use GJS (Gnome/GTK Spidermonkey engine) there is a print global function but no console.*. Unlike Python it also has a printerr function.

0

u/[deleted] Dec 16 '18

[deleted]

-10

u/FormerGameDev Dec 17 '18

Really you should be using something other than console log overall. At least that's most pros advice.