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);
About the author
- I am a web consultant from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in
Comments
Join the discussionNo comments yet. Be the first to comment.





