Accessing a JavaScript function of an object using [] instead of a dot (.)
Today's post is super short and simple and it's probably known to most developers. It's about accessing a function of an object using [] instead of dot (.)
Let's say you have a condition - if flag is true
then use max, if false
, use min.
let result, a = 5, b = 12, flag = true;
if (flag)
result = Math.max(a, b);
else
result = Math.min(a, b);
What if we could do this in one-line by accessing the function, which is a property, using square brackets ? We can access the function via Math['max'](a ,b)
and Math['min'](a ,b)
let a = 5, b = 12, flag = true;
let result = Math[flag ? 'max' : 'min'](a, b);