Skip to content
Swizec Teller - a geek with a hatswizec.com

Discovered a cool javascript property

Yesterday I was playing around with javascript trtying to find the cleanest way to implement callbacks in functions. Primarily I wanted a readable way to make certain the last argument passed is a callback, withut having to rely on knowing how many arguments there are and so on.

Instead I stumbled upon a pretty cool feature of how javascript handles function arguments. But let's look at some code.

This is the usual way people use functions, it's nicely standard and works pretty much the same way in most languages

function example(arg1, arg2, arg3) {
return arg1 + arg2 == arg3;
}
example(1, 2, 3);

Nothing too spectacular here, but javascript has another way to access function arguments - the magical arguments object; granted, a lot of languages have something like this, but it's always a less than obvious feature people often forget about:

function example() {
console.log(arguments);
// prints { '0': 1, '1': 2, '2': 3 }
}
example(1, 2, 3);

Ok, nothing too major, perhaps the biggest surprise is that arguments is an object, not a list or an array and strangely enough that the keys are strings despite being just numbers. Also pretty cool is that you don't have to specify any arguments at all, it just magically works. In python for example you at least have to say *args or something like that.

But things really start to heat up when we mix both ways of using function arguments in javascript:

function example(arg) {
console.log(arguments);
// prints { '0': 1, '1': 2, '2': 3 }
arg = 5;
console.log(arguments);
// prints { '0': 5, '1': 2, '2': 3 }
var arg = "new";
console.log(arguments);
// prints { '0': 'new', '1': 2, '2': 3 }
var notArg = arg;
notArg = "old";
console.log(arguments);
// prints { '0': 'new', '1': 2, '2': 3 }
arguments[1] = arg;
console.log(arguments);
// prints { '0': 'new', '1': 'new', '2': 3 }
arg = 5;
console.log(arguments);
// prints { '0': 5, '1': 'new', '2': 3 }
}
example(1, 2, 3);

The slightly strange thing here is that arguments the function takes explicitly are only references to the positions in the arguments object rather than variables of their own. Trying to make them a new variable doesn't work unless you give them a different name.

However despite these being just pointers, you can't make them cross-reference each other because when you assign them to the arguments object a copy is performed and further changes are not reflected in both arguments properties.

But is it a deep or a shallow copy? Let's try:

function isitdeep(arg1, arg2) {
console.log(arguments);
// prints { '0': { a: { b: 'c' }, d: { e: 'f' } },
// '1': { g: 'h' } }
arg1.a.b = "f";
console.log(arguments);
// prints { '0': { a: { b: 'f' }, d: { e: 'f' } },
// '1': { g: 'h' } }
arg2 = arg1;
console.log(arguments);
// prints { '0': { a: { b: 'f' }, d: { e: 'f' } },
// '1': { a: { b: 'f' }, d: { e: 'f' } } }
arg1.a.b = "c";
console.log(arguments);
// prints { '0': { a: { b: 'c' }, d: { e: 'f' } },
// '1': { a: { b: 'c' }, d: { e: 'f' } } }
arg1 = "hello world";
console.log(arguments);
// prints { '0': 'hello world',
// '1': { a: { b: 'c' }, d: { e: 'f' } } }
}
isitdeep({ a: { b: "c" }, d: { e: "f" } }, { g: "h" });

Interesting, turns out it's a shallow copy and you can still poke arguments in strange ways ... but maybe/probably that's just how javascript performs in general, the = operator being a shallow copy mechanism.

Anyhow, I'm sure this knowledge will come in handy some day, I'm just nicely tickled by having found it. Actually ... it's kind of horrible, this sort of obscure language features should never be used in production code :)

Enhanced by Zemanta

Did you enjoy this article?

Published on April 16th, 2011 in Argument, Callback, Function (mathematics), JavaScript, Languages, Programming, Uncategorized

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works 👇

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet 📖right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet 📖

Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️