Fun with JavaScript
I have a love/hate relationship with JS. I also feel a little bit like Carrie Bradshaw, sitting at my laptop, typing a word “relationship”.
It is an awesome scripting language. It is an awful programming language. In its defence, it was never meant to be used as the latter.
In no particular order, I’ll highlight a few interesting features. This article doesn’t contain any practical information, whatsoever.
Function
let add = new Function('a', 'b', '{ return a + b; }');
let x = add(2, 2) // x = 4So… you can create a function from array of strings, assuming they are valid JS code. Getting creative, you could make an object for holding functions:
let fn = {
name: 'add',
parameters: ['a', 'b'],
body: '{ return a + b; }'
}let add = new Function(...fn.parameters, fn.body);
add(2, 2);
You can serialize that object into JSON, and pass it around as a string parameter, then deserialize it, and make a function on the spot. You can store that object in the database! My next pet project is gonna involve getting 99% of HTML scripts from DB.
Get Bananica Bananica’s stories in your inbox
Join Medium for free to get updates from this writer.
This is obviously very stupid, but usefulness isn’t my goal.
Self “corrupting” functions
When you really want to go off the tracks, JS code can be self-modified. This is the proof that, one day, the malevolent AI which will nuke us into submission, is gonna be written in JavaScript.
function uhm(a, b) {
if(a === 7) {
uhm = (a) => console.log(a);
}
else {
return a + b;
}
}This function will sum two numbers, until you pass first parameter as 7. From that point on, it will become a one parameter function that just logs whatever it received. Sooo, this is valid:
uhm(2, 2); // returns 4
uhm(7, 0); // changes behaviour
uhm('pizza'); // prints pizzaDumb example, but the power of this should be self evident.
Crazy for-loops
I know that for-loops are viewed as cryptic, hard to read statements, only used by simpletons who don’t understand the absolute dominance of functional programming, but…
Say we have some array:
let vehicles = [
{ type: 'Car' },
{ type: 'Plane' },
{ type: 'Rocket' },
];Normal approach would be:
for (let i = 0; i < vehicles.length; i++) {
vehicles[i].type += 's';
}So we get the length of the array, compare it with the current value of iterator i , and perform some action on a specific index. Here is the different way:
for (let i = 0, item; item = vehicles[i]; i++) {
item += 's';
}Actually, to avoid repetition, Jason Knight has an absolutely bonkers article with in depth explanation on what you can actually cram in this expression. I highly recommend reading it.
I wanted to add a few more things, but they are actually useful in day to day development, so they don’t qualify.
Thanks for reading :)







