I encountered this snippet of code, but I'm having trouble reading it, I have never seen code written this way.
showMenuButton[isOpened ? "hide" : "show"]();
hideMenuButton[isOpened ? "show" : "hide"]();
isOpened ? container.removeClass("hideMenu") : container.addClass("hideMenu");
Is it the same as
if(isOpened="hide"){
showMenuButton();
}
else{
hideMenuButton();
}
Could someone explain what the code is doing and why they are writing this way? Is it simply because they are shorter? (I have never seen the [ ] in function calling).
Thank you.
Here is the full javascript code.
menuToggle = $("#menuToggle"),
showMenuButton = $(".menuToggle_show"),
hideMenuButton = $(".menuToggle_hide"),
toggleSideMenu = function (isOpened) {
showMenuButton[isOpened ? "hide" : "show"]();
hideMenuButton[isOpened ? "show" : "hide"]();
isOpened ? container.removeClass("hideMenu") : container.addClass("hideMenu");
}
3 Answers 3
Javascript has 2 ways of referring to objects/method calls - the dot-notation and the square-bracket notation. They are interchangable, and equivalent, so the following 2 lines will be identical
var x = someObject.someProperty;
// or
var x = someObject["someProperty"];
This also works for methods, so again the follwoing two both work (note the difference from the above is parentheses which call the method)
someObject.someFunction();
// or
someObject["someFunction"]();
Now, relating this back to your question, there is another trick at work; ternary operators:
var result = someCondition ? trueResult : falseResult
Putting this all together
showMenuButton[isOpened ? "hide" : "show"]();
hideMenuButton[isOpened ? "show" : "hide"]();
Equates to
if(isOpened){
showMenuButton["hide"](); // or, showMenuButton.hide();
hideMenuButton["show"](); // or, hideMenuButton.show();
}
else{
showMenuButton["show"](); // or, showMenuButton.show();
hideMenuButton["hide"](); // or, hideMenuButton.hide();
}
(Its basically toggling a show/hide button depending on whether it's currently in an opened state or not)
1 Comment
Those are objects storing functions:
var functions={
alertName:function(){
alert('My name is Angel');
},
alertLastName:function(){
alert('My last name is Cool');
},
alertMySite:function(){
alert('angelcool.net');
}
}
functions['alertMySite']();
Comments
Yes, it is exactly that, it is calling the functions hide() and show(), from the jQuery object, the ternary operators do make it more compact, the most friendly code to look, would go like:
if( isOpened ){
showMenuButton.hide();
hideMenuButton.show();
container.removeClass("hideMenu");
}else{
showMenuButton.show();
hideMenuButton.hide();
container.addClass("hideMenu");
}