csduarte
csduarte

Reputation: 191

What is the coding technique called? function[]()

I was doing some javascript exercises, I solved it. But in another solution I saw this...

this.queue(
    buf.toString()[
        nlines++ % 2 === 0? 'toUpperCase' : 'toLowerCase']() + '\n');

Where as I did this...

var line = buf.toString();
this.queue(lineCount % 2 === 0
        ? line.toLowerCase() + '\n'
        : line.toUpperCase() + '\n'
    );

Passing in the [] after the function, what that technique called?

I've seen something like that in swift, passing closures if they are the last parameter. I'm assuming it's the same, but can't quite find it on google cause I don't know the words. not even close

Upvotes: 1

Views: 56

Answers (2)

dfsq
dfsq

Reputation: 193311

This is bracket notation for accessing object properties. In your case buf.toString() is a string. All strings have bunch of properties coming from String.prototype like toUpperCase and toLowerCase. Usually you read those properties using dot-notation:

buf.toString().toUpperCase();

But you can always use bracket syntax too. Above is equivalent to

buf.toString()['toUpperCase']();

In your case bracket-notation comes very handy for conditional property names, as there can be an expression between brackets.

Probably you got a little confused by parenthesis after []. But it's easy to understand: String.prototype.toUpperCase property is a function, so you have all legal rights to invoke this function with () operator. No magic here.

Upvotes: 3

toniedzwiedz
toniedzwiedz

Reputation: 18563

The term you're looking for is a Property Accessor. In this case, you're looking at the bracket notation.

You can access various properties of JavaScript object using the [] operator. These properties include functions that can be called.

object["functionName"]()

One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of the object's properties. It's typical when speaking of an object's properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is simply a property that can be called, for example if it has a reference to a Function instance as its value.

Upvotes: 1

Related Questions