Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use parentheses, brackets, and curly braces in Javascript and jQuery [closed]

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.

like image 602
devhead Avatar asked Apr 22 '14 16:04

devhead


People also ask

Why do we use curly braces in JavaScript?

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.

What is the use of brackets in JavaScript?

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]);

What does curly braces mean in jQuery?

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.

What are {} used for in react?

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.


1 Answers

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.

like image 58
g.d.d.c Avatar answered Oct 22 '22 11:10

g.d.d.c