2016-06-20 Easy Javascript logging

I’ve been doing some JavaScript coding recently. Before you run off screaming, let me tell you that JavaScript is not that bad. Yes, it has C-like, unlispy syntax, but at its heart it is quite a nice language. Today, though, I didn’t want to write about JS in general, but about one small detail. While debugging JavaScript code, it is often useful to sprinkle console.log statements in your code. Also, if you want to check the value of some more complicated variable, you need to JSON.stringify it first. Of course, writing repetitive pieces of code is not what an Emacs user would like to do, so I hacked this:

(defun js-insert-console-log ()
  "Insert a console.log statement in the line below.
If region is active, treat it as the variable to log."
  (let ((variable (if (use-region-p)
		      (buffer-substring-no-properties (region-beginning)
    (move-end-of-line 1)
    (if variable
	   (format "console.log(\"%s: \" + JSON.stringify(%s, null, '\\t'));"
      (insert "console.log();")
      (backward-char 2))))

Note that this is really only a quick hack – it doesn’t use js2-mode’s JS parsing capabilities, for instance (I’d like to understand them some day, but I’d have to learn about EIEIO first). After having used it quite intensely for a few days now, though, I haven’t noticed any problems.

(Of course, it is only a poor substitute for real debugging; this SO answer gives a few possibilities. I’ll look into this in some Free Time™.)

CategoryEnglish, CategoryBlog, CategoryEmacs, CategoryJavaScript