r/javascript • u/chroner • Dec 16 '18
Coming from Python to JS NSFW
const print = console.logI found my safe space.
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
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
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
41
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
Dec 16 '18
...where is the global?
19
u/joelangeway Dec 16 '18
Iirc that works in node.js like
windowworks in the browser, in that it’s synonymous with the global scope.4
6
u/nickbreaton Dec 17 '18
If you're interested, there is an ECMAScript proposal to add
globalThisso the same variable can be used for both node and the browser (or whatever JS environment you're in).1
6
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
Dec 16 '18
That's why it's marked NSFW!
54
2
4
u/kchoudhury Dec 17 '18
He aliased a function and it is amply obvious what it does. What standard did he violate?
5
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
1
1
1
1
0
Dec 17 '18
[deleted]
26
u/placidified Dec 17 '18
console.log(error) // eslint-disable-line no-console
cries in legacy code
3
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
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
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
0
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
Dec 16 '18
[deleted]
16
u/Earhacker Dec 17 '18
forloops are for dirty Python casuals. Over here in JavaScript we use Array.prototype.forEach.(but sure, we use your
fornumloop sometimes too)4
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
Dec 17 '18
[deleted]
8
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
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
1
0
Dec 16 '18
[deleted]
26
5
u/killchain Dec 16 '18
Almost like
npm isntallis a default alias fornpm install.8
u/GabrielChiconiDev Dec 17 '18
Why doesn't everybody
npm ithough?4
u/killchain Dec 17 '18
I do. At one point I was so lazy that I even had
nialias 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
0
2
5
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
I think you only need the
.bindifconsole.logwere to usethisin its implementation15
0
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
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
Dec 17 '18
[deleted]
3
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
Dec 17 '18
A non-exhaustive list of reasons this would be a bad idea in the workplace:
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.
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')?
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
3
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
2
2
2
2
2
2
2
2
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
1
1
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
1
1
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
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.
3
337
u/Pavlo100 Dec 16 '18
Here is the Java implementation for those who want to make their life harder