- 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.
- 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 */
- JavaScript provides seven different data types which are
undefined
,null
,boolean
,string
,symbol
,number
, andobject
. - 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.
- 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
tomyVar
and then resolvesmyVar
to5
again and assigns it tomyNum
.
myVar = 5;
myNum = myVar;
- When JavaScript variables are declared, they have an initial value of
undefined
. If you do a mathematical operation on anundefined
variable your result will beNaN
which means "Not a Number". If you concatenate a string with anundefined
variable, you will get a literal string of"undefined"
.
- 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;
- 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.
- 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
.
- In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by
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
tomyVar
. 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
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.
- 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".
- 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.
- Quotes are not the only characters that can be escaped inside a string. There are two reasons to use escaping characters:
- To allow you to use characters you may not otherwise be able to type out, such as a carriage return.
- To allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean.
- In JavaScript, when the
+
operator is used with aString 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."
- 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."
- 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?"
-
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!"
- You can find the length of a String value by writing .length after the string variable or string literal.
"Alan Peter".length; // 10
-
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"
- 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 ofmyStr
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";
- 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"
- 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"
- 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"].
[["Bulls", 23], ["White Sox", 45]]
- 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
- 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]
- 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
.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"]]
.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]
- 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"]].
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"]
- 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");
}
- 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);
}
- 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 theglobal
scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.
- 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
- 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 thelocal
version of the variable is present.
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}
-
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
- A function can include the
return
statement but it does not have to. In the case that the function doesn't have areturn
statement, when you call it, the function processes the inner code but the returned value isundefined
.
var sum = 0;
function addSum(num) {
sum = sum + num;
}
addSum(3); // sum will be modified but returned value is undefined
-
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.
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));
- 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.
- Another data type is the Boolean.
Booleans
may only be one of two values:true
orfalse
. Boolean
values are never written with quotes. Thestrings
"true"
and"false"
are notBoolean
and have no special meaning in JavaScript.
- 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"
- The most basic operator is the equality operator
==
. The equality operator compares two values and returnstrue
if they're equivalent orfalse
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
- 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
- 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'
- The inequality operator (
!=
) is the opposite of the equality operator. - It means "Not Equal" and returns
false
where equality would returntrue
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
- The strict inequality operator (
!==
) is the logical opposite of the strict equality operator. - It means "Strictly Not Equal" and returns
false
where strict equality would returntrue
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.
- The logical and operator (
&&
) returnstrue
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";
-
The logical or operator (
||
) returnstrue
if either of the operands istrue
. Otherwise, it returnsfalse
. -
The logical or operator is composed of two pipe symbols: (
||
).
- Example:
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
- Example:
if (num > 15) {
return "Bigger than 15";
} else if (num < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 15";
}
-
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.
-
In the game of golf each hole has a
par
meaning the average number ofstrokes
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 belowpar
yourstrokes
are, there is a different nickname. -
Your function will be passed
par
andstrokes
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!" |
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);
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);
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";
}
- 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 abreak
is encountered. case
values are tested with strict equality (===
). Thebreak
tells JavaScript to stop executing statements. If thebreak
is omitted, the next statement will be executed.- Example:
switch(lowercaseLetter) {
case "a":
console.log("A");
break;
case "b":
console.log("B");
break;
}
-
You can add the
default
statement which will be executed if no matchingcase
statements are found. Think of it like the finalelse
statement in anif/else
chain. -
A
default
statement should be the last case.
switch (num) {
case value1:
statement1;
break;
case value2:
statement2;
break;
...
default:
defaultStatement;
break;
}
- 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";
}
- If you have many options to choose from, a
switch
statement can be easier to write than many chainedif/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";
}
- 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
===
returnstrue
orfalse
, we can return the result of the comparison:
function isEqual(a,b) {
return a === b;
}
- 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 thereturn
statement.
-
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 globalcount
variable according to the card's value (see table). The function will then return a string with the current count and the stringBet
if the count is positive, orHold
if the count is zero or negative. The current count and the player's decision (Bet
orHold
) should be separated by a single space. -
Example Output
- -3 Hold
- 5 Bet
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";
}
}
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
}
- The function first evaluates
if
the conditioncard
is a value greater than 1 and lower than7
, in which case it incrementscount
by one. - Then if the card is
10
or higher it decrementscount
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 for10
and then for any string that matches the regular expression usingString.match()
- 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.
-
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
- 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
-
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.
- Example:
- Here's how we update his object's name property:
ourDog.name = "Happy Camper";
orourDog["name"] = "Happy Camper";
Now when we evaluateourDog.name
, instead of getting "Camper",
- Here's how we update his object's name property:
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
- Example:
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
ourDog.bark = "bow-wow";
- 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!"]
}
*/
-
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 anif/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"
- 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()
returnstrue
orfalse
if the property is found or not. - Example:
var myObj = {
top: "hat",
bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
- 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
}
];
- 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"
- 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"
-
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
(like2548
), a propertypro
p (like"artist"
or"tracks"
), and avalue
(like"Addicted to Love"
) to modify the data in this collection. -
If
prop
isn't"tracks"
andvalue
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"
andvalue
isn't empty (""
), push thevalue
onto the end of the album's existingtracks
array. -
If value is empty (
""
), delete the givenprop
property from the album.
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;
}
- 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.
- 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++;
}
-
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 asfalse
, your loop will never execute. -
The
final-expression
is executed at the end of each loop iteration, prior to the nextcondition
check and is usually used to increment or decrement your loop counter.
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
- Example:
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
ourArray.push(i);
}
- Example:
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
- 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 arrayarr
to the console:
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
- 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]);
}
}
- 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 loopwhile
the specified condition evaluates totrue
.
var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
- 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 afor
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 rewritemultiply
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.
-
We have an array of objects representing different people in our contacts lists.
-
A
lookUpProfile
function that takesname
and a property (prop
) as arguments has been pre-written for you. -
The function should check if
name
is an actual contact'sfirstName
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 matchname
then return"No such property"
.
// 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");
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");
-
Random numbers are useful for creating random behavior.
-
JavaScript has a
Math.random()
function that generates a random decimal number between0
(inclusive) and not quite up to1
(exclusive). ThusMath.random()
can return a0
but never quite return a1
-
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.
}
-
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.
- Use
Math.random()
to generate a random decimal. - Multiply that random decimal by
20
. - Use another function,
Math.floor()
to round the number down to its nearest whole number.
- Use
-
Remember that
Math.random()
can never quite return a1
and, because we're rounding down, it's impossible to actually get20
. This technique will give us a whole number between0
and19
. -
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 toMath.floor()
function to round the value down to the nearest whole number.
-
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 rangemyMin
andmyMax
and returns a random number that's greater than or equal tomyMin
, and is less than or equal tomyMax
, inclusive.
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}
-
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:Math.random() = 0.8244326990411024
(myMax - myMin + 1) = 10 - 1 + 1 -> 10
a * b = 8.244326990411024
c + myMin = 9.244326990411024
Math.floor(9.244326990411024) = 9
-
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
.
-
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.
-
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";
}
-
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";
}
- 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
function countdown(n) {
if (n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
}
function countdown(n) {
if (n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.splice(0, 0, n);
return arr;
}
}
function countdown(n){
return n < 1 ? [] : [n].concat(countdown(n - 1));
}
function countdown(n){
return n < 1 ? [] : [n, ...countdown(n - 1)];
}
- 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 thestartNum
parameter and ends with a number represented by theendNum
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 bothstartNum
andendNum
are the same.
- We have defined a function named
function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
}
function rangeOfNumbers(startNum, endNum) {
return startNum === endNum
? [startNum]
: rangeOfNumbers(startNum, endNum - 1).concat(endNum);
}
function rangeOfNumbers(startNum, endNum) {
return startNum === endNum
? [startNum]
: [...rangeOfNumbers(startNum, endNum - 1), endNum ];
}