Skip to content

Instantly share code, notes, and snippets.

@akirap3
Last active May 21, 2020 20:16
Show Gist options
  • Save akirap3/fbec02391b2205b6a8c4fabf5f91c3c4 to your computer and use it in GitHub Desktop.
Save akirap3/fbec02391b2205b6a8c4fabf5f91c3c4 to your computer and use it in GitHub Desktop.

Basic JavaScript: Comment Your JavaScript Code

Best Practice

  • As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code—both for others and for your future self.

There are two ways to write comments in JavaScript:

  • Using // will tell JavaScript to ignore the remainder of the text on the current line:
// This is an in-line comment.
  • You can make a multi-line comment beginning with /* and ending with */:
/* This is a
multi-line comment */

Basic JavaScript: Declare JavaScript Variables

  • JavaScript provides seven different data types which are undefined, null, boolean, string, symbol, number, and object.
  • Variables allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the seven data types may be stored in a variable.
  • We tell JavaScript to create or declare a variable by putting the keyword var in front of it, like so:
var ourName;

creates a variable called ourName. In JavaScript we end statements with semicolons. Variable names can be made up of numbers, letters, and $ or_, but may not contain spaces or start with a number.

Basic JavaScript: Storing Values with the Assignment Operator

  • Assignment always goes from right to left. Everything to the right of the = operator is resolved before the value is assigned to the variable to the left of the operator.
  • This assigns 5 to myVar and then resolves myVar to 5 again and assigns it to myNum.
myVar = 5;
myNum = myVar;

Basic JavaScript: Initializing Variables with the Assignment Operator

It is common to initialize a variable to an initial value in the same line as it is declared.

var myVar = 0;

Basic JavaScript: Understanding Uninitialized Variables

  • When JavaScript variables are declared, they have an initial value of undefined. If you do a mathematical operation on an undefined variable your result will be NaN which means "Not a Number". If you concatenate a string with an undefined variable, you will get a literal string of "undefined".

Basic JavaScript: Understanding Case Sensitivity in Variables

  • In JavaScript all variables and function names are case sensitive. This means that capitalization matters.
  • Best Practice
    • Write variable names in JavaScript in camelCase. In camelCase, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.
  • Examples:
var someVariable;
var anotherVariableName;
var thisVariableNameIsSoLong;

Basic JavaScript: Increment a Number with JavaScript

You can easily increment or add one to a variable with the ++ operator.

i++;

is the equivalent of

i = i + 1;

Basic JavaScript: Decrement a Number with JavaScript

You can easily decrement or decrease a variable by one with the -- operator.

i--;

is the equivalent of

i = i - 1;

Basic JavaScript: Create Decimal Numbers with JavaScript

  • We can store decimal numbers in variables tmoo. Decimal numbers are sometimes referred to as floating point numbers or floats.
  • Not all real numbers can accurately be represented in floating point. This can lead to rounding errors. Details Here.

Basic JavaScript: Finding a Remainder in JavaScript

  • The remainder operator % gives the remainder of the division of two numbers.
  • Note: The remainder operator is sometimes incorrectly referred to as the "modulus" operator. It is very similar to modulus, but does not work properly with negative numbers.
  • Example:
5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)
  • Usage:
    • In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by 2.
17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)

Basic JavaScript: Compound Assignment With Augmented Addition/ Subtraction/ Multiplication/ Division

  • In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:

  • myVar = myVar + 5;

  • to add 5 to myVar. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.

  • One such operator is the += operator.

var myVar = 1;
myVar += 5;
console.log(myVar); // Returns 6

Basic JavaScript: Declare String Variables

var myName = "your name";
  • "your name" is called a string literal. It is a string because it is a series of zero or more characters enclosed in single or double quotes.

Basic JavaScript: Escaping Literal Quotes in Strings

  • In JavaScript, you can escape a quote from considering it as an end of string quote by placing a backslash (\) in front of the quote.
var sampleStr = "Alan said, \"Peter is learning JavaScript\".";
// Alan said, "Peter is learning JavaScript".

Basic JavaScript: Quoting Strings with Single Quotes

  • String values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote.

Basic JavaScript: Escape Sequences in Strings

  • Quotes are not the only characters that can be escaped inside a string. There are two reasons to use escaping characters:
    1. To allow you to use characters you may not otherwise be able to type out, such as a carriage return.
    2. To allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean.

\' single quote

\" double quote

\\ backslash

\n newline

\r carriage return

\t tab

\b word boundary

\f form feed

Basic JavaScript: Concatenating Strings with Plus Operator

  • In JavaScript, when the + operator is used with a String value, it is called the concatenation operator. You can build a new string out of other strings by concatenating them together.
  • Example:
var ourStr = "I come first. " + "I come second.";
// ourStr is "I come first.  I come second."

Basic JavaScript: Concatenating Strings with the Plus Equals Operator

  • We can also use the += operator to concatenate a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.
  • Note: Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
  • Example:
var ourStr = "I come first. ";
ourStr += "I come second.";
// ourStr is now "I come first. I come second."

Basic JavaScript: Constructing Strings with Variablesc

  • By using the concatenation operator (+), you can insert one or more variables into a string you're building.
  • Example:
var ourName = "freeCodeCamp";
var ourStr = "Hello, our name is " + ourName + ", how are you?";
// ourStr is now "Hello, our name is freeCodeCamp, how are you?"

Basic JavaScript: Appending Variables to Strings

  • Just as we can build a string over multiple lines out of string literals, we can also append variables to a string using the plus equals (+=) operator.

  • Example:

var anAdjective = "awesome!";
var ourStr = "freeCodeCamp is ";
ourStr += anAdjective;
// ourStr is now "freeCodeCamp is awesome!"

Basic JavaScript: Find the Length of a String

  • You can find the length of a String value by writing .length after the string variable or string literal.
    • "Alan Peter".length; // 10

Basic JavaScript: Use Bracket Notation to Find the First Character in a String

  • Bracket notation is a way to get a character at a specific index within a string.

  • Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as Zero-based indexing.

  • Example:

var firstName = "Charles";
var firstLetter = firstName[0]; // firstLetter is "C"

Basic JavaScript: Understand String Immutability

  • In JavaScript, String values are immutable, which means that they cannot be altered once created.
  • For example, the following code:
var myStr = "Bob";
myStr[0] = "J";
  • cannot change the value of myStr to "Job", because the contents of myStr cannot be altered.
  • The only way to change myStr would be to assign it with a new string, like this:
var myStr = "Bob";
myStr = "Job";

Basic JavaScript: Use Bracket Notation to Find the Last Character in a String

  • In order to get the last letter of a string, you can subtract one from the string's length.
  • Example:
var firstName = "Charles";
var lastLetter = firstName[firstName.length - 1]; // lastLetter is "s"

Basic JavaScript: Use Bracket Notation to Find the Nth-to-Last Character in a String

  • You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.
  • Example:
var firstName = "Charles";
var thirdToLastLetter = firstName[firstName.length - 3]; // thirdToLastLetter is "l"

Basic JavaScript: Store Multiple Values in one Variable using JavaScript Arrays

  • You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:
var sandwich = ["peanut butter", "jelly", "bread"].

Basic JavaScript: Nest one Array within Another Array

[["Bulls", 23], ["White Sox", 45]]

Basic JavaScript: Access Array Data with Indexes

  • arrays use zero-based indexing, so the first element in an array has an index of 0.
  • Example:
var array = [50,60,70];
array[0]; // equals 50
var data = array[1];  // equals 60

Basic JavaScript: Modify Array Data With Indexes

  • Unlike strings, the entries of arrays are mutable and can be changed freely.
  • Note: There shouldn't be any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
  • Example:
var ourArray = [50,40,30];
ourArray[0] = 15; // equals [15,40,30]

Basic JavaScript: Access Multi-Dimensional Arrays With Indexes

  • Example:
var arr = [
  [1,2,3],
  [4,5,6],
  [7,8,9],
  [[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11

Basic JavaScript: Manipulate Arrays With push()

  • .push() takes one or more parameters and "pushes" them onto the end of the array.
  • Example:
var arr1 = [1,2,3];
arr1.push(4);
// arr1 is now [1,2,3,4]

var arr2 = ["Stimpson", "J", "cat"];
arr2.push(["happy", "joy"]);
// arr2 now equals ["Stimpson", "J", "cat", ["happy", "joy"]]

Basic JavaScript: Manipulate Arrays With pop()

  • .pop() is used to "pop" a value off of the end of an array. We can store this "popped off" value by assigning it to a variable.
  • In other words, .pop() removes the last element from an array and returns that element.
  • Example:
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]

Basic JavaScript: Manipulate Arrays With shift()

  • it removes the first element instead of the last.
  • Example:
var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift();
// removedFromOurArray now equals "Stimpson" and ourArray now equals ["J", ["cat"]].

Basic JavaScript: Manipulate Arrays With unshift()

  • unshift() adds the element at the beginning of the array.
  • Example:
var ourArray = ["Stimpson", "J", "cat"];
ourArray.shift(); // ourArray now equals ["J", "cat"]
ourArray.unshift("Happy");
// ourArray now equals ["Happy", "J", "cat"]

Basic JavaScript: Write Reusable JavaScript with Functions

  • In JavaScript, we can divide up our code into reusable parts called functions.
  • You can call or invoke this function by using its name followed by parentheses, like this: functionName();
function functionName() {
  console.log("Hello World");
}

Basic JavaScript: Passing Values to Functions with Arguments

  • Parameters are variables that act as placeholders for the values that are to be input to a function when it is called.
  • When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or "passed") into a function when it is called are known as arguments.
  • Example:
function testFun(param1, param2) {
  console.log(param1, param2);
}

Basic JavaScript: Global Scope and Functions

  • In JavaScript, scope refers to the visibility of variables.
  • Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.
  • Variables which are used without the var keyword are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.

Basic JavaScript: Local Scope and Functions

  • Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.
  • Example:
function myTest() {
  var loc = "foo";
  console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined

Basic JavaScript: Global vs. Local Scope in Functions

  • It is possible to have both local and global variables with the same name.
  • When you do this, the local variable takes precedence over the global variable.
  • Example: The function myFun will return "Head" because the local version of the variable is present.
var someVar = "Hat";
function myFun() {
  var someVar = "Head";
  return someVar;
}

Basic JavaScript: Return a Value from a Function with Return

  • We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.

  • Example:

function plusThree(num) {
  return num + 3;
}
var answer = plusThree(5); // 8

Basic JavaScript: Understanding Undefined Value returned from a Function

  • A function can include the return statement but it does not have to. In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is undefined.
var sum = 0;
function addSum(num) {
  sum = sum + num;
}
addSum(3); // sum will be modified but returned value is undefined

Basic JavaScript: Stand in Line

  • In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.

  • Write a function nextInLine which takes an array (arr) and a number (item) as arguments.

  • Add the number to the end of the array, then remove the first element of the array.

  • The nextInLine function should then return the element that was removed.

Solution:

function nextInLine(arr, item) {
  arr.push(item);
  var removed = arr.shift();
  return removed; 
}

// Setup
var testArr = [1,2,3,4,5];

// Display code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));

Code, Explanation:

  • Push item at the end of arr.
  • Call the shift() method on arr to get the first item and store it in removed.
  • Return removed.

Basic JavaScript: Understanding Boolean Values

  • Another data type is the Boolean. Booleans may only be one of two values: true or false.
  • Boolean values are never written with quotes. The strings "true" and "false" are not Boolean and have no special meaning in JavaScript.

Basic JavaScript: Use Conditional Logic with If Statements

  • Pseudocode
if (condition is true) {
  statement is executed
}
  • Example:
function test (myCondition) {
  if (myCondition) {
     return "It was true";
  }
  return "It was false";
}
test(true);  // returns "It was true"
test(false); // returns "It was false"

Basic JavaScript: Comparison with the Equality Operator

  • The most basic operator is the equality operator ==. The equality operator compares two values and returns true if they're equivalent or false if they are not.
  • Example:
function equalityTest(myVal) {
  if (myVal == 10) {
     return "Equal";
  }
  return "Not Equal";
}
  • In order for JavaScript to compare two different data types (for example, numbers and strings), it must convert one type to another. This is known as "Type Coercion". Once it does, however, it can compare terms as follows:
1   ==  1   // true
1   ==  2   // false
1   == '1'  // true
"3" ==  3   // true

Basic JavaScript: Comparison with the Strict Equality Operator

  • Strict equality (===) is the counterpart to the equality operator (==).
  • However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.
  • Example:
3 ===  3   // true
3 === '3'  // false

Basic JavaScript: Practice comparing different values

  • Note: In JavaScript, you can determine the type of a variable or a value with the typeof operator, as follows:
typeof 3   // returns 'number'
typeof '3' // returns 'string'

Basic JavaScript: Comparison with the Inequality Operator

  • The inequality operator (!=) is the opposite of the equality operator.
  • It means "Not Equal" and returns false where equality would return true and vice versa.
  • Like the equality operator, the inequality operator will convert data types of values while comparing.
  • Example:
1 !=  2     // true
1 != "1"    // false
1 != '1'    // false
1 != true   // false
0 != false  // false

Basic JavaScript: Comparison with the Strict Inequality Operator

  • The strict inequality operator (!==) is the logical opposite of the strict equality operator.
  • It means "Strictly Not Equal" and returnsfalse where strict equality would return true and vice versa.
  • Strict inequality will not convert data types.
3 !==  3   // false
3 !== '3'  // true
4 !==  3   // true

Basic JavaScript: Comparison with the Greater Than(>)/ Greater Than Or Equal To(>=)/ Less Than(<)/ Less Than Or Equal To(<=) Operator

  • Greater Than(>)/ Greater Than Or Equal To(>=)/ Less Than(<)/ Less Than Or Equal To(<=) operator will convert data types while comparing.

Basic JavaScript: Comparisons with the Logical And Operator

  • The logical and operator (&&) returns true if and only if the operands to the left and right of it are true.
  • Example:
if (num > 5 && num < 10) {
  return "Yes";
}
return "No";

Basic JavaScript: Comparisons with the Logical Or Operator

  • The logical or operator (||) returns true if either of the operands is true. Otherwise, it returns false.

  • The logical or operator is composed of two pipe symbols: (||).

Basic JavaScript: Introducing Else Statements

  • Example:
if (num > 10) {
  return "Bigger than 10";
} else {
  return "10 or Less";
}

Basic JavaScript: Introducing Else If Statements

  • Example:
if (num > 15) {
  return "Bigger than 15";
} else if (num < 5) {
  return "Smaller than 5";
} else {
  return "Between 5 and 15";
}

Basic JavaScript: Logical Order in If Else Statements

  • Order is important in if, else if statements.

  • The function is executed from top to bottom so you will want to be careful of what statement comes first.

Basic JavaScript: Golf Code

  • In the game of golf each hole has a par meaning the average number of strokes a golfer is expected to make in order to sink the ball in a hole to complete the play. Depending on how far above or below par your strokes are, there is a different nickname.

  • Your function will be passed par and strokes arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):

Strokes Return
1 "Hole-in-one!"
<= par - 2 "Eagle"
par - 1 "Birdie"
par "Par"
par + 1 "Bogey"
par + 2 "Double Bogey"
>= par + 3 "Go Home!"

Solution 1:

function golfScore(par, strokes) {
  
  if (strokes == 1) {
    return "Hole-in-one!";
  } else if (strokes <= par - 2) {
    return "Eagle";
  } else if (strokes == par - 1) {
    return "Birdie";
  } else if (strokes == par) {
    return "Par";
  } else if (strokes == par + 1) {
    return "Bogey";
  } else if (strokes == par + 2) {
    return "Double Bogey";
  } else {
    return "Go Home!";
  }
  
}
// Change these values to test
golfScore(5, 4);

Solution 2:

var names = [
  "Hole-in-one!",
  "Eagle",
  "Birdie",
  "Par",
  "Bogey",
  "Double Bogey",
  "Go Home!"
];
function golfScore(par, strokes) {
  
  if (strokes == 1) {
    return names[0];
  } else if (strokes <= par - 2) {
    return names[1];
  } else if (strokes == par - 1) {
    return names[2];
  } else if (strokes == par) {
    return names[3];
  } else if (strokes == par + 1) {
    return names[4];
  } else if (strokes == par + 2) {
    return names[5];
  } else {
    return names[6];
  }
  
}

// Change these values to test
golfScore(5, 4);

Solution 3:

function golfScore(par, strokes) {
  return strokes == 1
    ? names[0]
    : strokes <= par - 2
    ? names[1]
    : strokes == par - 1
    ? names[2]
    : strokes == par
    ? names[3]
    : strokes == par + 1
    ? names[4]
    : strokes == par + 2
    ? names[5]
    : strokes >= par + 3
    ? names[6]
    : "Change Me";
}

Basic JavaScript: Selecting from Many Options with Switch Statements

  • If you have many options to choose from, use a switch statement.
  • A switch statement tests a value and can have many case statements which define various possible values.
  • Statements are executed from the first matched case value until a break is encountered.
  • case values are tested with strict equality (===). The break tells JavaScript to stop executing statements. If the break is omitted, the next statement will be executed.
  • Example:
switch(lowercaseLetter) {
  case "a":
    console.log("A");
    break;
  case "b":
    console.log("B");
    break;
}

Basic JavaScript: Adding a Default Option in Switch Statements

  • You can add the default statement which will be executed if no matching case statements are found. Think of it like the final else statement in an if/else chain.

  • A default statement should be the last case.

switch (num) {
  case value1:
    statement1;
    break;
  case value2:
    statement2;
    break;
...
  default:
    defaultStatement;
    break;
}

Basic JavaScript: Multiple Identical Options in Switch Statements

  • If you have multiple inputs with the same output, you can represent them in a switch statement like this:
switch(val) {
  case 1:
  case 2:
  case 3:
    result = "1, 2, or 3";
    break;
  case 4:
    result = "4 alone";
}

Basic JavaScript: Replacing If Else Chains with Switch

  • If you have many options to choose from, a switch statement can be easier to write than many chained if/else if statements. The following:
if (val === 1) {
  answer = "a";
} else if (val === 2) {
  answer = "b";
} else {
  answer = "c";
}
  • can be replaced with:
switch(val) {
  case 1:
    answer = "a";
    break;
  case 2:
    answer = "b";
    break;
  default:
    answer = "c";
}

Basic JavaScript: Returning Boolean Values from Functions

  • Sometimes people use an if/else statement to do a comparison, like this:
function isEqual(a,b) {
  if (a === b) {
    return true;
  } else {
    return false;
  }
}
  • But there's a better way to do this. Since === returns true or false, we can return the result of the comparison:
function isEqual(a,b) {
  return a === b;
}

Basic JavaScript: Return Early Pattern for Functions

  • When a return statement is reached, the execution of the current function stops and control returns to the calling location.
  • Example:
function myFun() {
  console.log("Hello");
  return "World";
  console.log("byebye")
}
myFun();
  • The above outputs "Hello" to the console, returns "World", but "byebye" is never output, because the function exits at the return statement.

Basic JavaScript: Counting Cards

  • In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called Card Counting.

  • Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.

Count Change Cards
+1 2, 3, 4, 5, 6
0 7, 8, 9
-1 10, 'J', 'Q', 'K', 'A'
  • You will write a card counting function. It will receive a card parameter, which can be a number or a string, and increment or decrement the global count variable according to the card's value (see table). The function will then return a string with the current count and the string Bet if the count is positive, or Hold if the count is zero or negative. The current count and the player's decision (Bet or Hold) should be separated by a single space.

  • Example Output

    • -3 Hold
    • 5 Bet

Solution 1:

function cc(card) {

  switch (card) {
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
      count++;
      break;
    case 10:
    case "J":
    case "Q":
    case "K":
    case "A":
      count--;
      break;
  }
  if (count > 0) {
    return count + " Bet";
  } else {
    return count + " Hold";
  }

}

Solution 2:

function cc(card) {
  // Only change code below this line
  var regex = /[JQKA]/;
  if (card > 1 && card < 7) {
    count++;
  } else if (card === 10 || String(card).match(regex)) {
    count--;
  }

  if (count > 0) return count + " Bet";
  return count + " Hold";

  // Only change code above this line
}

Solution 2, Code Explanation:

  • The function first evaluates if the condition card is a value greater than 1 and lower than 7, in which case it increments count by one.
  • Then if the card is 10 or higher it decrements count by one.
  • The variable regex is a regular expression representing values (letters) for the higher cards.
  • The else statement checks those values with the || (logical OR) operator; first for 10 and then for any string that matches the regular expression using String.match()

Basic JavaScript: Build JavaScript Objects

  • Objects are useful for storing data in a structured way, and can represent real world objects.
  • Here's a sample cat object:
var cat = {
  "name": "Whiskers",
  "legs": 4,
  "tails": 1,
  "enemies": ["Water", "Dogs"]
};
  • However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:
var anotherObject = {
  make: "Ford",
  5: "five",
  "model": "focus"
};
  • However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.

Basic JavaScript: Accessing Object Properties with Dot Notation

  • There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array.

  • Dot notation is what you use when you know the name of the property you're trying to access ahead of time.

  • Here is a sample of using dot notation (.) to read an object's property:

var myObj = {
  prop1: "val1",
  prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2

Basic JavaScript: Accessing Object Properties with Bracket Notation

  • The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.
  • However, you can still use bracket notation on object properties without spaces.
  • Note that property names with spaces in them must be in quotes (single or double).
  • Here is a sample of using bracket notation to read an object's property:
var myObj = {
  "Space Name": "Kirk",
  "More Space": "Spock",
  "NoSpace": "USS Enterprise"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
myObj["NoSpace"];    // USS Enterprise

Basic JavaScript: Accessing Object Properties with Variables

  • Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.

  • Here is an example of using a variable to access a property:

var dogs = {
  Fido: "Mutt",  Hunter: "Doberman",  Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
  • Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
var someObj = {
  propName: "John"
};
function propPrefix(str) {
  var s = "prop";
  return s + str;
}
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // "John"
  • Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name.

Basic JavaScript: Updating Object Properties

  • Example:
    • Here's how we update his object's name property: ourDog.name = "Happy Camper"; or ourDog["name"] = "Happy Camper"; Now when we evaluate ourDog.name, instead of getting "Camper",
var ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
};

Basic JavaScript: Add New Properties to a JavaScript Object

  • Example:
var ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
};

ourDog.bark = "bow-wow";

Basic JavaScript: Delete Properties from a JavaScript Object

  • Example:
var ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"],
  "bark": "bow-wow"
};

delete ourDog.bark;
  • After the last line shown above, ourDog looks like:
{
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
}
*/

Basic JavaScript: Using Objects for Lookups

  • Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to "lookup" values rather than a switch statement or an if/else chain. This is most useful when you know that your input data is limited to a certain range.

  • Here is an example of a simple reverse alphabet lookup:

var alpha = {
  1:"Z",
  2:"Y",
  3:"X",
  4:"W",
  ...
  24:"C",
  25:"B",
  26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"

var value = 2;
alpha[value]; // "Y"

Basic JavaScript: Testing Objects for Properties

  • Sometimes it is useful to check if the property of a given object exists or not. We can use the .hasOwnProperty(propname) method of objects to determine if that object has the given property name. .hasOwnProperty() returns true or false if the property is found or not.
  • Example:
var myObj = {
  top: "hat",
  bottom: "pants"
};
myObj.hasOwnProperty("top");    // true
myObj.hasOwnProperty("middle"); // false

Basic JavaScript: Manipulating Complex Objects

  • Sometimes you may want to store data in a flexible Data Structure. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of strings, numbers, booleans, arrays, functions, and objects.
  • Note: You will need to place a comma after every object in the array, unless it is the last object in the array.
  • Here's an example of a complex data structure:
var ourMusic = [
  {
    "artist": "Daft Punk",
    "title": "Homework",
    "release_year": 1997,
    "formats": [ 
      "CD", 
      "Cassette", 
      "LP"
    ],
    "gold": true
  }
];

Basic JavaScript: Accessing Nested Objects

  • Example:
var ourStorage = {
  "desk": {
    "drawer": "stapler"
  },
  "cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  }
};
ourStorage.cabinet["top drawer"].folder2;  // "secrets"
ourStorage.desk.drawer; // "stapler"

Basic JavaScript: Accessing Nested Arrays

  • Example:
var ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"

Basic JavaScript: Record Collection

  • You are given a JSON object representing a part of your musical album collection. Each album has several properties and a unique id number as its key. Not all albums have complete information.

  • Write a function which takes an album's id (like 2548), a property prop (like "artist" or "tracks"), and a value (like "Addicted to Love") to modify the data in this collection.

  • If prop isn't "tracks" and value isn't empty (""), update or set the value for that record album's property.

  • Your function must always return the entire collection object.

  • There are several rules for handling incomplete data:

  • If prop is "tracks" but the album doesn't have a "tracks" property, create an empty array before adding the new value to the album's corresponding property.

  • If prop is "tracks" and value isn't empty (""), push the value onto the end of the album's existing tracks array.

  • If value is empty (""), delete the given prop property from the album.

Solution:

var collection = {
  2548: {
    album: "Slippery When Wet",
    artist: "Bon Jovi",
    tracks: [
      "Let It Rock",
      "You Give Love a Bad Name"
    ]
  },
  2468: {
    album: "1999",
    artist: "Prince",
    tracks: [
      "1999",
      "Little Red Corvette"
    ]
  },
  1245: {
    artist: "Robert Palmer",
    tracks: [ ]
  },
  5439: {
    album: "ABBA Gold"
  }
};


function updateRecords(id, prop, value) {
  if(value === "") delete collection[id][prop];
  else if(prop === "tracks") {
    collection[id][prop] = collection[id][prop] || [];
    collection[id][prop].push(value);
  } else {
    collection[id][prop] = value;
  }

  return collection;
}

Code, Explanation:

  • First checks if prop is equal to tracks AND if value isn’t a blank string. If both tests pass, value is pushed into the tracks array.
  • If that first check doesn’t pass, it next checks only if value isn’t a blank string. If that test passes, either a new key (prop) and value (value) are added to the object, or an existing key is updated if the prop already exists.
  • If both these checks fail (meaning value must be an empty string), then the key (prop) is removed from the object.

Basic JavaScript: Iterate with JavaScript While Loops

  • The first type of loop we will learn is called a while loop because it runs "while" a specified condition is true and stops once that condition is no longer true.
  • Example:
var ourArray = [];
var i = 0;
while(i < 5) {
  ourArray.push(i);
  i++;
}

Basic JavaScript: Iterate with JavaScript For Loops

  • You can run the same code multiple times by using a loop.

  • The most common type of JavaScript loop is called a for loop because it runs "for" a specific number of times.

  • For loops are declared with three optional expressions separated by semicolons:

    • for ([initialization]; [condition]; [final-expression])
  • The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.

  • if condition starts as false, your loop will never execute.

  • The final-expression is executed at the end of each loop iteration, prior to the next condition check and is usually used to increment or decrement your loop counter.

var ourArray = [];
for (var i = 0; i < 5; i++) {
  ourArray.push(i);
}

Basic JavaScript: Iterate Odd Numbers With a For Loop

  • Example:
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
  ourArray.push(i);
}

Basic JavaScript: Count Backwards With a For Loop

  • Example:
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
  ourArray.push(i);
}

Basic JavaScript: Iterate Through an Array with a For Loop

  • A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a for loop. This code will output each element of the array arr to the console:
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}

Basic JavaScript: Nesting For Loops

  • If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:
var arr = [
  [1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
  for (var j=0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}

Basic JavaScript: Iterate with JavaScript Do...While Loops

  • It is called a do...while loop because it will first do one pass of the code inside the loop no matter what, and then continue to run the loop while the specified condition evaluates to true.
var ourArray = [];
var i = 0;
do {
  ourArray.push(i);
  i++;
} while (i < 5);

Basic JavaScript: Replace Loops using Recursion

  • Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first n elements of an array to create the product of those elements. Using a for loop, you could do this:
  function multiply(arr, n) {
    var product = 1;
    for (var i = 0; i < n; i++) {
        product *= arr[i];
    }
    return product;
  }
  • However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]. That means you can rewrite multiply in terms of itself and never need to use a loop.
  function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }
  • Note: Recursive functions must have a base case when they return without calling the function again (in this example, when n <= 0), otherwise they can never finish executing.

Basic JavaScript: Profile Lookup

  • We have an array of objects representing different people in our contacts lists.

  • A lookUpProfile function that takes name and a property (prop) as arguments has been pre-written for you.

  • The function should check if name is an actual contact's firstName and the given property (prop) is a property of that contact.

  • If both are true, then return the "value" of that property.

  • If name does not correspond to any contacts then return "No such contact".

  • If prop does not correspond to any valid properties of a contact found to match name then return "No such property".

Solution 1:

// Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["JavaScript", "Gaming", "Foxes"]
    }
];


function lookUpProfile(name, prop) {
for (var x = 0; x < contacts.length; x++) {
    if (contacts[x].firstName === name) {
        if (contacts[x].hasOwnProperty(prop)) {
            return contacts[x][prop];
        } else {
            return "No such property";
        }
    }
}
return "No such contact";
}

lookUpProfile("Akira", "likes");

Solution 2:

function lookUpProfile(name, prop) {
  for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === name) {
      if (prop in contacts[i]) {
        return contacts[i][prop];
      } else return "No such property";
    }
  }
  return "No such contact";
}

lookUpProfile("Akira", "likes");

Basic JavaScript: Generate Random Fractions with JavaScript

  • Random numbers are useful for creating random behavior.

  • JavaScript has a Math.random() function that generates a random decimal number between 0 (inclusive) and not quite up to 1 (exclusive). Thus Math.random() can return a 0 but never quite return a 1

  • Example: Change randomFraction to return a random number instead of returning 0.

function randomFraction() {
  var result = 0;
  // Math.random() can generate 0. We don't want to return a 0,
  // so keep generating random numbers until we get one that isn't 0
  while (result === 0) {
    result = Math.random();
  }

  return result;
  // Only change code above this line.
}

Basic JavaScript: Generate Random Whole Numbers with JavaScript

  • It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.

    1. Use Math.random() to generate a random decimal.
    2. Multiply that random decimal by 20.
    3. Use another function, Math.floor() to round the number down to its nearest whole number.
  • Remember that Math.random() can never quite return a 1 and, because we're rounding down, it's impossible to actually get 20. This technique will give us a whole number between 0 and 19.

  • Putting everything together, this is what our code looks like:

    • Math.floor(Math.random() * 20);
  • We are calling Math.random(), multiplying the result by 20, then passing the value to Math.floor() function to round the value down to the nearest whole number.

Basic JavaScript: Generate Random Whole Numbers within a Rang

  • To do this, we'll define a minimum number min and a maximum number max.

  • Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:

  • Math.floor(Math.random() * (max - min + 1)) + min

  • Example: Create a function called randomRange that takes a range myMin and myMax and returns a random number that's greater than or equal to myMin, and is less than or equal to myMax, inclusive.

Solution:

function randomRange(myMin, myMax) {
  return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}

Code Explanation:

  • Math.random() generates our random number between 0 and ≈ 0.9.

  • Before multiplying it, it resolves the part between parenthesis (myMax - myMin + 1) because of the grouping operator ( ).

  • The result of that multiplication is followed by adding myMin and then “rounded” to the largest integer less than or equal to it (eg: 9.9 would result in 9)

  • If the values were myMin = 1, myMax= 10, one result could be the following:

    1. Math.random() = 0.8244326990411024
    2. (myMax - myMin + 1) = 10 - 1 + 1 -> 10
    3. a * b = 8.244326990411024
    4. c + myMin = 9.244326990411024
    5. Math.floor(9.244326990411024) = 9

Basic JavaScript: Use the parseInt Function

  • The parseInt() function parses a string and returns an integer. Here's an example:

    var a = parseInt("007");

  • The above function converts the string "007" to an integer 7. If the first character in the string can't be converted into a number, then it returns NaN.

Basic JavaScript: Use the parseInt Function with a Radix

  • The parseInt() function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36.

  • The function call looks like:

    • parseInt(string, radix);
  • And here's an example:

    • var a = parseInt("11", 2);
  • The radix variable says that "11" is in the binary system, or base 2. This example converts the string "11" to an integer 3.

Basic JavaScript: Use the Conditional (Ternary) Operator

  • The conditional operator, also called the ternary operator, can be used as a one line if-else expression.

  • The syntax is:

    • condition ? statement-if-true : statement-if-false;
  • The following function uses an if-else statement to check a condition:

function findGreater(a, b) {
  if(a > b) {
    return "a is greater";
  }
  else {
    return "b is greater";
  }
}
  • This can be re-written using the conditional operator:
function findGreater(a, b) {
  return a > b ? "a is greater" : "b is greater";
}

Basic JavaScript: Use Multiple Conditional (Ternary) Operators

  • In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions.

  • The following function uses if, else if, and else statements to check multiple conditions:

function findGreaterOrEqual(a, b) {
  if (a === b) {
    return "a and b are equal";
  }
  else if (a > b) {
    return "a is greater";
  }
  else {
    return "b is greater";
  }
}
  • The above function can be re-written using multiple conditional operators:
function findGreaterOrEqual(a, b) {
  return (a === b) ? "a and b are equal" 
    : (a > b) ? "a is greater" 
    : "b is greater";
}

Basic JavaScript: Use Recursion to Create a Countdown

  • Example: count up
function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
  • Example: count down

Solution 1:

function countdown(n) {
  if (n < 1) {
    return [];
  } else {
    const arr = countdown(n - 1);
    arr.unshift(n);
    return arr;
  }
}

Solution 2:

function countdown(n) {
  if (n < 1) {
    return [];
  } else {
    const arr = countdown(n - 1);
    arr.splice(0, 0, n);
    return arr;
  }
}

Solution 3:

function countdown(n){
   return n < 1 ? [] : [n].concat(countdown(n - 1));
}

Solution 4:

function countdown(n){
   return n < 1 ? [] : [n, ...countdown(n - 1)];
}

Basic JavaScript: Use Recursion to Create a Range of Numbers

  • Example:
    • We have defined a function named rangeOfNumbers with two parameters. The function should return an array of integers which begins with a number represented by the startNum parameter and ends with a number represented by the endNum parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both startNum and endNum are the same.

Solution 1:

function rangeOfNumbers(startNum, endNum) {
  if (endNum - startNum === 0) {
    return [startNum];
  } else {
    var numbers = rangeOfNumbers(startNum, endNum - 1);
    numbers.push(endNum);
    return numbers;
  }
}

Solution 2:

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : rangeOfNumbers(startNum, endNum - 1).concat(endNum);
}

Solution 3:

function rangeOfNumbers(startNum, endNum) {
  return startNum === endNum
    ? [startNum]
    : [...rangeOfNumbers(startNum, endNum - 1), endNum ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment