What does this notation do? [duplicate] - javascript

This question already has answers here:
JavaScript square bracket function call
(5 answers)
Closed 4 years ago.
Sorry for the bad title, but I couldn't come up with something better.
I found the following line of code in a legacy project I have to maintain. However, I have ABSOLUTELY no idea what this does or how it works.
$('.js-legend-input')[operation]('chapter__inputs--hidden');
The variable operation is defined as the following:
const operation = active === 'chapter' ? 'addClass' : 'removeClass';
I can only suspect that this line executes the function addClass and removeClass on the .js-legend-input and works with the parameters in the parentheses. So is this notation just a "shorthand" for:
if(active === 'chapter') {
$('.js-legend-input').addClass('chapter__inputs--hidden');
} else {
$('.js-legend-input').removeClass('chapter__inputs--hidden');
}
Because I know sure as hell I have never seen that before.

You are absolutely correct. It's exactly what it does, plus:
If parameter values change, then you only need to update that one line in legacy code, instead of two in case of the ifs
$('.js-legend-input')[ operation ]( 'chapter__inputs--hidden' ) ;
If a new operation is possible, like for example toggleClass then you don't have to add another if, you can just call it with variable operation = 'toggleClass' . Neat, right?

Yeah you are right, this notation [operation] is called bracket notation and it is used to access object properties along with the dot notation (just having . followed by the property name). The bracket notation allows the usage of variables as property names this is why it is used in this scenario. The variable operation just replaces the name of the property with its value.

Related

Why do people write js like this? [duplicate]

This question already has answers here:
Why does any JavaScript code want to "cut the binding"?
(1 answer)
JavaScript syntax (0, fn)(args)
(2 answers)
Closed 2 years ago.
var type = (0, _reactIs.isMemo)(nodeOrComponent) ? nodeOrComponent.type.type : nodeOrComponent.type;
(0, _reactIs.isMemo) really confuse me. What's the meaning of this?
ps: I know (0, _reactIs.isMemo) this expression's value is _reactIs.isMemo
The comma operator there ensures that what's inside the parentheses is evaluated as an expression without a calling context.
To take a shorter example, if the code was:
var type = obj.fn(someArg);
then fn would be called with a calling context of obj. But the original untranspiled code, whatever it is, does not have such a calling context, so in order to be faithful to the original code, the calling context has to be removed, which can be done with the comma operator:
var type = (0, obj.fn)(someArg);
Another way of doing the same thing would be:
var fn = obj.fn;
var type = fn(someArg);
(but that takes more characters, so minifiers prefer the comma operator version)
This is a silly-looking minification trick that's often seen with imported modules. Usually, you'd only be looking at the source code, which won't have this sillyness.

Javascript syntax []() and ()() [duplicate]

This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
I'm having trouble understanding these javascript syntaxes. In the block of code below, on the second line. The square bracket is quickly followed by a round bracket or parentheses which I suspected is used to get arguments. I do not understand how this two is being chained to form an expression and what it means.
export const recipeCount = createReducer(0, {
[types.ADD_RECIPE](state, action){
return state + 1;
}
});
Also on this line, the connect method takes in two arguments, (state) => {return {}} and mapDispatchToProps . Then it is quickly follwed by () with an argument. At first, i though it was some of object casting in java but that doesn't make sense.
export default connect((state) => {return {}}, mapDispatchToProps)(AppContainer);
The code executes fine and produces expected result. I just don't understand what is going on. Pls Help, would be glad to get answersre accompanied with links to pages i can read for better understanding. Thanks.
Answers are in the comment to the question. Had to copy them out again, so i can mark the question as answered and close it.
"Not sure what's going on with the first one. For the second one, connect() is a function that returns a function so the second () is to immediately call that returned function." – Ouroborus
"The first one is a dynamic object literal property that is also an object method. I find this not readable at all. I would re-write that one. – Davin Tryon"
and also a link to Computed property names to make it clearer from – Denys Séguret
Thanks Guys.

Dynamically call function in javascript [duplicate]

This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?
You could use the bracket notation as property accessor.
globalClient[functionName]()
You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();

Javascript use variable name to thread a function? [duplicate]

This question already has answers here:
Use JavaScript variable as function name?
(5 answers)
Closed 7 years ago.
In GSC, you are able to make a variable become the name of a function that you thread. It looks like this:
variable = "pizza";
[[variable]]();
the engine then reads it like:
pizza();
my question is, is it possible to do that in javascript as easily or do I have to make if/else/switch statements for it?
my question is, is it possible to do that in javascript as easily or
do I have to make if/else/switch statements for it?
If you want to use the safe, fail-proof way, then you can access such variables only in two contexts.
If the variable is in global context, in the case of which, you can do window[variable]();
Else if the variable is a property of an object, in the case of which, you can do obj_name[variable](), basically anything that can be accessed via bracket notation. window is an object too.
Then there's always the dirty way:
You can use highly evil eval like eval(variable + "()") or you can use the Function constructor in the same way. Note however that both the methods can be misused and are highly advised against.

Usage of toString in JavaScript [duplicate]

This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 9 years ago.
I'm reading through Douglas Crockford's JavaScript: The Good Parts, and I'm at the point where he defines a fade function. Part of this code boils down to this:
var level = 1;
var hex = level.toString(16);
So I run this in my browser's console to see what I get....
var level = 1;
level.toString(16);
Hey, it returns "1"... Fabuloso! Wunderbar!
Then to be cheeky, I try this to see what I get...
1.toString(16);
And I get
SyntaxError: Unexpected token ILLEGAL
What the what? If level is a variable equal to 1, and running this method on level works fine, then why doesn't running this method on the actual number 1 work? I tried a similar experiment with the toPrecision() method and that worked fine in both cases. What's the issue here? Is this another one of those inherent flaws in the JavaScript implementation, or am I missing something? I am testing in Google Chrome.
Related: Stack Overflow question Why don't number literals have access to Number methods?.
It's just a language grammar limitation.
Since 1. is a legal literal number (and 1.t is not) the tokeniser will split this into the following tokens:
1.
toString
(
)
And that's an illegal sequence of tokens. It's object method, instead of object . method.
In the working versions in #Joey's answer, the braces prevent the tokenizer from treating the dot as part of the number literal instead of as a separate token, as does writing:
1.0.toString()
or
1..toString()
since the tokenizer knows that the second dot must be a token on its own, and not part of the number literal.
You need 1..toString or (1).toString to get the number literal
level is a variable (and thus an object).
1 is a literal. They are not objects and the interpreter thinks about them completely differently.
http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html#4

Categories

Resources