Wednesday, August 8, 2012

Browser console as a shell (or how to test code in a browser)

Recently I was asked by a friend to write a batch file that generates one thousand dummy email addresses of this format: nX@some.com (where X is a number from 1 to 1000). I could've of course write a batch file, or open a Linux shell in a virtual machine (I work on a Windows box). But being a web developer, the closet place where I can execute code is of course the browser console.


Running Simple Snippet
My favorite browser is Chrome, so all I had to do was press F12, click the Console button and put in some JavaScript code:



for(var i = 0; i < 5; i++) { console.log(i + " times cool");}

As you can see, I simply put in the code I want to run in the console's "command line" and run it.
The last line of the output will be the value that the code we ran returns. Because running a for loop doesn't return anything, we got a grayed out undefined there. If on the other hand we'd run 5+10 we'd be getting 15 in the output. Try it out, the console is right there!

Breaking Lines
The magic doesn't end here though. Let's say you want run a more complex multi-line code. You can do multi-line editing too. By pressing Shift+Enter the cursor will move to the next line without executing the code, and thus, you can write and execute more interesting stuff, in a cleaner way (you can of course write a long one-liner, whatever works best for you). Consider the same example with broken lines:








Declaring Variables and Functions
Now let's move to the really exciting stuff. The console remembers the code you write! So, if you want to declare a variable, or a function you do it in exactly the same manner.
I want to declare a function, and then pass a variable as an argument to that function. I'm gonna do exactly what I'm doing in my text-editor of choice, only it's going to happen in the console:





var someVar = 10;
function addFive(num) {
return num + 5;
}
addFive(someVar);

We've declared a variable (someVar), then a function (addFive) and then called the function with the variable as an argument. Finally we've received the result (15) in the console.
Have you noticed that the console auto-completes the vars and function names you've declared?

Hope I've introduced you to an easier way of executing super simple coding tasks and made them even easier :)

Happy coding!

1 comment: