What Do Square Brackets Around a Property Name in an Object Literal Mean

TypeScript - what do square brackets in property name mean?

That is not a typescript feature but a javascript one. It's called a computed property. Here are the docs for it.

Additionally, it does not create a property with the key eventName, but instead creates a property with a key that is the value of the variable eventName. Eg, if eventName = "foo", then {[eventName]: "bar"} is the same as {foo: "bar"}.

Use of square brackets in objects

I'm guessing you want the value of jform[name] to a key in the object. You can't use variables as keys when declaring an object literal. You'll have to add this key as another statement.

Example:

var data = {
rules: {
}
};
data.rules[jform[name]]= {
required:true,
minlength:5,
maxlength:15
};

If you want the key to literally be jform[name], then you need to use quotes around the key.

rules: {
"jform[name]": {
required:true,
minlength:5,
maxlength:15
}
}

What do square brackets around an expression mean, e.g. `var x = a + [b]`?

Square brackets means new Array.

var ar=new Array("a","b");
var ar=["a","b"]; //Equal to the syntax above

in that situation there's no difference if you use square brackets or not because if it's an array it is converted to string, but if you delete the brackets it takes less time because it doesn't have to build a new array and convert it but it works with a simple string.

Why put an object key in square brackets (not destructuring)?

This is a computed property - it's the equivalent of:

let result = {}
result[CALL_API] = { ... };
return result;

Combining this with Symbol lets the library author create a protocol that will not collide with other protocols (e. g. if the protocol was a string "call" then it could collide with other libraries that use someObject.call for their (unrelated) protocols - as well as colliding with Function.prototype.call.)

What do the square brackets after ES6 function do?

It's not "after" the function, it is in the functions body. It could also be written as:

  const url  = category => {
const obj = {
'itemA': itemAService.getItemCategories(payload),
'itemB': itemBService.getItemCategories(payload),
};

return obj[category];
};

So this is basically just a dynamic property lookup in the object.

Javascript square brackets around method name

those are symbols, which is very similar to defining properties but gives different accessibility and testability functionality and they are completely unique,

you can read a lot more about metaprogramming here,
Metaprogramming in ES6: Symbols and why they're awesome



Related Topics



Leave a reply



Submit