I'm a bit confused when using some of parentheses, brackets, and curly braces in Javascript and jQuery. Is there a simple way of understanding when to distinguish when to use these?
Example 1:
$("#theDiv").animate({width: "500px" }, 1000);
Example 2:
$("img").attr({src: "/images/hat.gif", title: "jQuery"});
Example 3:
$('a[rel="nofollow self"]')
Thanks.
Curly brackets are used to denote a block of code. These are generally used while writing control flow statements, loops, functions etc. Javascript object literal notation also uses curly brackets.
Brackets [] are typically mostly used for accessing the properties of an Object (or the elements of an Array), so mylist[3] fetches the fourth element in the Array. var mylist = [1,2,3,4]; alert(mylist[2]);
curly braces identify an Object like so: timObject = { property1 : "Hello", property2 : "MmmMMm", property3 : ["mmm", 2, 3, 6, "kkk"], method1 : function(){alert("Method had been called" + this. property1)} }; in jQuery they are used to provide an Object with options for your method.
You put curly braces when you want to use the value of a variable inside "html" (so inside the render part). It's just a way of telling the app to take the value of the variable and put it there, as opposed to a word.
Unfortunately, the best answer is "use them each as appropriate where necessary".
Parenthesis ()
in JavaScript are used for function calls, to surround conditional statements, or for grouping to enforce Order of Operations.
function myFunc() {
if (condition1) {
}
if ( (1 + 2) * 3) {
// very different from (1 + 2 * 3)
}
}
Braces {}
are used during the declaration of Object Literals, or to enclose blocks of code (function definitions, conditional blocks, loops, etc).
var objLit = {
a: "I am an Object Literal."
};
Brackets []
are typically mostly used for accessing the properties of an Object (or the elements of an Array), so mylist[3]
fetches the fourth element in the Array.
var mylist = [1,2,3,4];
alert(mylist[2]);
It doesn't help that you're trying to start with jQuery, which also uses its own Selector Grammar within Strings that are passed to function calls (which can make it look much more complicated than it actually is). This: $('a[rel="nofollow self"]')
is only a single function call, and the inner brackets are handled by jQuery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With