Category Archives: geekery

TIL 27: javascript 8

Standard
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
Advertisements

TIL 23: javascript 7

Standard

For loops:

  • loops allow the same bit of code to be run multiple times
  • For loops are the most common kind in javascript
  • the declaration format is: for ([initialisation]; [condition]; [final-expression])
  • the initialisation step only executes once, before the loop starts. Generally it is used to set up the loop variable
  • the condition statement is evaluated at the start of every loop, and the loop is only executed if this condition evaluates to true
  • the final-expression is executed at the end of each loop, before the next condition check, and usually increments or decrements the loop counter
  • e.g. for(var i = 0; i < 5; i+=2) { myArray.push(i)];} would result in [0, 2, 4]
  • For loops are often used to iterate through arrays, e.g. for(var i = 0; i < 5; i++) {console.log myArray[i]; }
  • nested for loops are used to loop through multi-dimensional arrays, e.g.

code

While loops:

  • as the name suggests, runs ‘while’ a specified condition is true
  • var i = 0; while (i < 5) { myArr.push(i); i++ }
  • note that the counter variable, i, has to be declared outside of the loop – while (var i < 5) would try to redeclare it on every loop
  • also note the need to increment the counter within the loop – if you forget this you’ll enter an infinite loop!

TIL 20: javascript 6

Standard

Objects (continued):

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

code

  • 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.

code

  • 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.

TIL 16: javascript 5

Standard

Start at the beginning, or see previous post.

JavaScript Objects:
code

  • useful for storing data in a structured way
  • can represent real world objects
  • objects are similar to arrays, but instead of indexes, data in objects is accessed via properties

Accessing object properties:

  • there are two ways to access the properties of an object: bracket notation, or the dot operator
  • the dot operator is used when you know the name of the property you’re trying to access e.g. myObj.prop1
  • bracket notation can also be used – and must be, if the property name has a space in it e.g. myObj[“Space Name”] (note the quote marks, also)
  • bracket notation also allows accessing a property using a variable – this is useful for iterating through the properties, for example

code

Updating object properties:

  • after the object has been created, the properties can be updated at any time like any other variable. Either the dot or bracket notation can be used. E.g. myObj.prop1 = “new”;

Add new properties:

  • adding new properties works in the same way as modifying existing ones e.g. myObj.newProp = “more new”;
  • again, either dot or bracket notation can be used

Deleting properties:

  • use the delete keyword e.g. delete myObj.newProp;

 

TIL 13: javascript 4

Standard

Pressing on with freeCodeCamp! Start at the beginning here or previous installment.

Booleans:

  • true or false
  • nb NOT “true” and “false”

Conditional logic:

code

  • ‘myCondition’ above could also be a comparison operate that equates to true or false. E.g. if(myVal == 10); where ‘==’ is the equality operator (nb do not use assignment ‘=’ by mistake!) or if(thatVal > 9);
  • note that javascript will attempt to convert data types. Thus, 1 == ‘1’ and “3” == 3
  • to get past this conversion, use strict equality to test for value and type equality e.g. 3 === 3 is true, but 3 === ‘3’ is false
  • the inequality operator is ‘!=’, and likewise ‘!==’ for strict inequality
  • logical AND operator ‘&&’ allows two conditions to be tested, with a ‘true’ result requiring both to be met
  • logical OR operator ‘||’ returns true if either condition is met
  • else statements allow for alternate code paths to be triggered e.g. if x do y; else do z;
  • else if allows the chaining of multiple if statements e.g. if a do x, else if b do y, else do z;

Switch statements:

code

  • tests a value and can have many case statements defining various outcomes
  • can be easier to write than chained if/else if statements
  • cases are tested with strict (===) equality
  • a default option can/should be provided for when none of the cases are true
  • multiple cases can evaluate to the same outcome by omitting a break statement, e.g. case 1: case 2: case 3: result = “1, 2 or 3”; break;

Returning Boolean Values (e.g. from Functions):

  • instead of if (a === b) {return true }; else {return false}; you can simply write return a === b; since this returns true or false automatically

TIL 9: javascript 3

Standard

Following on from posts on the basics and arrays, another short bit of refresher from freeCodeCamp.

Functions:

function

  • reusable bits of code
  • called or invoked using the function’s name and parentheses, e.g. functionName();
  •  parameters or  arguments can be passed in (as per pic above)

Scope:

  • i.e. visibility of variables
  • Global variables are declared outside of the function block and can be ‘seen’ by the rest of the code
  • omitting the var keyword when declaring a variable automatically makes it global – this can cause unintentional errors!
  • Local variables are those declared within the function, including the function parameters, and are not accessible outwith the function
  • you can create local and global variables with the same name; the local one will take precedence. Again – this can cause many errors for the unwary!
  • use the return keyword to send a value back out of a function
  • the return value of a function can be assigned to a variable, e.g. var solution = functionName(8);

TIL 6: javascript 2

Standard

Following on from my javascript 1 post, still refreshing the basics via freeCodeCamp.

Working with arrays:

  • arrays store several pieces of data in a single element
  • array declaration e.g. var myArr = [“some text”, 23, “hello”];
  • you can nest arrays within other arrays e.g. var ages = [[“Jon”, 28], [“Bob”, 43]];
  • access array elements using zero-based indexing, e.g. myArr[0] is “some text”
  • array entries are mutable, unlike strings
  • multidimensional arrays also use indexes to access elements e.g. ages[0][1] is 28
  • append data to the end of an array using the push() function e.g. myArr.push(“world”);
  • remove the last value on an array using the pop() function e.g. myArr.pop() would undo the above push. Further, if we’d said var removed = myArr.pop(), removed would store the value “world”.
  • .shift() removes the first element, rather than the last
  • .unshift() adds an element to the start of an array

Short one for today. Next, functions!