Tag Archives: code

TIL 27: javascript 8

Random numbers:
  • use Math.random() function to generate a random decimal number between 0 and 1 (0 can occur, but not 1)
  • random whole numbers can be generated with a combination of multiplication and Math.floor() to round the number down to the nearest whole number e.g. return Math.floor(Math.rand\rom() * 10);
  • to generate a whole number within a range, you can use something like: Math.floor(Math.random() * (max – min + 1)) + min
Regular expressions:
  • Regular expressions find patterns within strings
  • start and end a regular expression with ‘/’, with the pattern you want to find between, e.g. if you’re searching for the word ‘dog’, it’d be: /dog/
  • add g to the regex to make it global – ie will return all the matches in the string, not just the first one
  • add i to ignore case e.g. /dog/gi
  • there are many special selectors in regex, to select a type of value
  • \d is the digit selector – it would find one digit in a string e.g. /\d/g
  • after the selector (eg \d+) allows the matching of one or more
  • \s is the whitespace selector – this will find ” ” (space), \r (carriage return), \n (newline), \t (tab), and \f (linefeed)
  • invert a selector by using the uppercase letter e.g. \s selects whitespace, \S selects anything that is not whitespace

TIL 20: javascript 6


Objects (continued):

  • Objects can be thought of as key/value storage, like a dictionary
  • Objects can be used to store data as lookup tables


  • check if an object property exists with .hasOwnProperty(propertyName); which returns true or false
  • a javascript object is one way to handle flexible data, allowing for artbitrary combinations of different data types
  • complex data structures might be stored as objects inside an array
  • objects properties are key-value pairs, e.g. “artist”: “Beatles” is a property with key “artist” and value “Beatles”
  • objects can be nested e.g.


  • access the sub-properties of nested objects by chaining the dot or bracket notation, as shown above
  • nested arrays are accessed in a similar manner, e.g. arr1[1].arr2[0];
  • JSON (JavaScript Object Notation) is a related data interchange format used to store data.