Skip to content

Instantly share code, notes, and snippets.

@SoxFace
Forked from robinsonlam/JSStructure.md
Created November 13, 2015 01:58
Show Gist options
  • Save SoxFace/6d4712ed66a8889b251e to your computer and use it in GitHub Desktop.
Save SoxFace/6d4712ed66a8889b251e to your computer and use it in GitHub Desktop.
Structuring your code in Javascript - Notes for WDI students to help with syntax

Code Structure

Here are some notes I've made to help you guys with your syntax. Think of it like a "cheatsheet". Some tips to remember:

  • Keep an eye on semicolons, usually control flow blocks (if blocks, for, while loops etc.) do not need a semicolon.
  • Keep an eye on your opening and closing brackets ( { & } ).
  • Be careful when using assignment operators ( = ) and equality operators ( == and === ). Assignment is for setting, equality is for comparing.
  • Keep an eye on quotation marks. Match doubles with doubles ( " ), singles with singles ( ' ).
    • Also: Watch when you're using apostrophes inside strings: var sentence = "You're weird";.
      Make sure you don't do this: var sentence = 'You're weird'; This will give you errors.
  • When checking conditions with logical operators ( &&, ||, ! ), you cannot combine your conditions.
    • Incorrect: if ( chicken === yummy && tasty )
    • Correct: if ( (chicken === yummy) && (chicken === tasty) )
  • Arrays and Objects:
    • Think of an Array like a shoe closet, it holds many different shoes.
    • An Object is like a shoe closet, except each shoe has a shoebox with labels stuck on them. (Analogy from Lucy Bain. @lucykbain)

Variables

var variableName = value;                  // Numbers, Booleans
var variableName = "value";                // Strings

var variableName = [element, element];     // Arrays

var variableName = {                       // Objects
  key: value,
  key: value
};  

variableName: The name for your variable. value: The value you want to assign to your variable.

Arrays:
element: The item you want to put into the array (collection).

Objects:
key: The "label" you wish to give to your item. This can also be a string e.g.( "9", "chicken nugget" ). value: The actualy item you want to put in your object.

Example:

var age = 32;             // 1.
var firstName = "Zac";    // 2.
var isWeird = true;       // 3.

var catchPhrases = ["Cya insertlastnamehere.", "Rob's the best."]; // 4.

var zacharyFraser = {     // 5.
  name: firstName,
  age: age,
  isWeird: true,
  catchPhrases: ["Cya insertlastnamehere.", "Rob's the best."]
};
  1. This creates a variable named age with a number value of 32.
  2. This creates a variable named firstName with a string value of Zac.
  3. This creates a variable named isWeird with a boolean value of true.
  4. This creates an array named catchPhrases with string elements: "Cya insertlastnamehere." and "Rob's the best."
  5. This creates an object named zacharyFraser which contains his:
  • name: which is using our variable firstName that was created on line 2.
  • age: which is using our variable age that was created on line 1.
  • isWeird: that we have set to true ourselves.
  • catchPhrases: which is an array of all his favourite catchphrases.
    Note: We have not used any semicolons when defining these elements, this is because they are seperated just like an array, with commas. (Refer back to the shoebox analogy located in the tips above.)

Functions

var functionName = function(argument, argument) {
  doStuff();
  
  return stuffToReturn;
}

functionName: The function's name.
argument: These are variables you will use in your function, when you call your function you will pass/put in these variables.
return: This is what the function will spit out after it's done, in a way the function will equal this. It will be clarified in the example.
Example:

var beersHad = 0;

var drink = function() {
  beersHad = beersHad + 1;
};

drink(); // beersHad is now 1

var speak = function(amountOfBeers) {
  if (amountOfBeers >= 8) {
    return "I can't feel my face.";
  } else if (amountOfBeers >= 5 && amountOfBeers < 8) {
    return "I'm not drunk! I swear!";
  } else if (amountOfBeers >= 1 && amountOfBeers < 5) {
    return "I'm fiiiiine.";
  } else {
    return "Where the drinks at?";
  }
}

console.log( speak(8) ); // instead we put in 8

Okay so here we have a really crappy example that I will probably change later.
First we have defined a function named drink that takes 0 arguments, then we tell it to increment beersHad by 1 every time the function is run.
We don't specify anything to return because we don't need this function to give us back anything.

We then call our function drink() without passing any arguments (you must include the parentheses () even with no arguments) and it will increment our beersHad by 1.

Then we have defined another function named speak that takes 1 argument: amountOfBeers.
We then tell it to return a string of text depending on how many beers we've had.

If we pass in anything between 1 and 4 will give us "I'm fiiiiine.",

anything between 5 and 7, he will lie and say "I'm not drunk! I swear!"

and anything equal or greater than 8 and this guy will need a taxi.

If we specify 0 drinks, it will default to our final else and give us "Where the drinks at?".

We then call our function speak, passing it the number 8 ( speak(8) ).
It will go through the function and give us back a string "I can't feel my face.".
To use this string we can use it in console.log() and it will print out "I can't feel my face." to our console!

Note: console.log() is a function too! The argument you pass in is what you want to output!

Control Flow Statements

If Statement

if (condition) {
  doWhatever();
}

condition: What you are checking.
doWhatever;: What you want to do if the check is true.

If & Else Statement

if (condition) {
  doWhatever();
} else {
  doThisInstead();
}

If & ElseIf & Else Statement

if (condition) {
  doWhatever();
} else if (condition2) {
  doWhateverInstead();
} else {
  doThisInstead();
}

Example:

var trafficLight = "red";
if (trafficLight === "green") {
  drive();
} else if (trafficLight === "orange") {
  speedUp();
} else if (trafficLight === "red") {
  brakeHard();
} else { // if the trafficLight isn't green, orange or red.
  ask("Why is the traffic light not working?"); 
}

Loops

For loop

for ( initalize ; conditiontoloop ; lastexpression ) {
  doStuff();
}

Example:

for ( x = 0 ; x < 10 ; x++ ) {
  console.log("We are on loop: " + (x + 1));
}

Here we start x at 0, this will loop while x is less than or equal to (<=) 10.
Each time the loop goes through it will call console.log("We are on loop: " + (x+1));
which outputs:
"We are on loop: 1" the first time because x is 0 and we have specified it to show x + 1.
Then it will increment x as we have specified earlier ( x++ ).

This loop should output:
We are on loop: 1
We are on loop: 2
...
We are on loop: 9
We are on loop: 10

While loop

while ( condition ) {
  doStuff();
}

Example:

var x = 0;
while ( x < 10 ) {
  console.log("We are on loop: " + (x+1));
  x++;
}

We first define x as 0.
We then create our while loop, specifying that x needs to be less than 10 to run this loop ( x < 10 ).
As the loop runs, it will call console.log("We are on loop: " + (x+1));.
We also need to add something that will eventually make our condition return false, so we increment x by 1 every time the loop runs, which will eventually make x greater than or equal to 10, stopping our loop.

This loop should output:
We are on loop: 1
We are on loop: 2
...
We are on loop: 9
We are on loop: 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment