Punctuating in the Javascript language
25 April 2016
Every programming language has a bunch of different grouping characters to tell the computer how to treat a group of code.
Here are some of the grouping characters used in Javascript and all their possible uses.
Parentheses ( )
Parentheses are used before a function's body to take in parameters and before a loop orif
statement to determine whether the code will run.
- When writing a function, between the parentheses, parameters can receive values.
function averageScore (sumOfScores, numberOfScores) {...}
- Functions use parentheses to run with parameters e.g.
whichIsBigger(12.5, 12.459)
. - Just like in mathematics, they can be used to prioritise calculations.
(4 + 2) / 3 == 2
Brackets [ ]
Brackets are often used to store and retrieve items from lists (arrays).- Storing items in an array, the array is indicated by square brackets.
var myArray = [1, 2, 4, 8];
- Getting a value from an array uses square brackets.
myArray[0]
will return the number 2. - Similar to getting a value from an array, bracket notation gets properties from inside objects.
ourDog = {dogName: "Spark", breed: "Beagle"}; ourDog["dogName"]
returns "Spark"
Braces { }
Braces enclose blocks of code to be run for functions, loops andif
statements. They also group object literals.
- The
ourDog = {dogName: ..., ...}
object literal above is grouped by its braces - Braces enclose blocks of code for functions.
function bigCodeBlock () {/* do something important */}
'Single' and "doubles" quotes
A pair of single quotes 'content here' and double quotes "content here" can be used interchangeably with Javascript not noticing the difference.- Quotes surround simple text, e.g.
var myName = "Troy";
. - They can also be used to get values from an object literal - using bracket notation.
ourDog['dogName']