Escape Sequences in Strings

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 13

JavaScript

Data types:

undefined, null, boolean, string, symbol, bigint, number, and object

Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with
a number.

Escape Sequences in Strings:


Code Output
\' single quote
\" double quote
\\ backslash
\n newline
\r carriage return
\t tab
\b word boundary
\f form feed

JavaScript array variables


var sandwich = ["peanut butter", "jelly", "bread"]

var myArray = ["flute", 10];


var myArray = [["Barcelona", 2], ["Bayern München, 8"]];

.push() "pushes" parameters onto the end of the array.


.pop() is used to "pop" a value off of the end of an array.

.shift() works just like .pop(), except it removes the first element instead of the last.

.unshift() adds the element at the beginning of the array.

Reusable JavaScript with Functions


function functionName() {
console.log("Hello World");
}

Global vs. Local Scope in Functions


The local variable takes precedence over the global variable.

Stand in Line
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) {

  // Only change code below this line

  arr.push(item);

  return arr.shift();

  return item;

  // Only change code above this line

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.

Examples

1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false

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 returns false where strict equality would return true and vice versa. Strict
inequality will not convert data types.

Examples

3 !== 3 // false
3 !== '3' // true
4 !== 3 // true

Comparisons with the Logical And Operator


Sometimes you will need to test more than one thing at a time. The logical and operator (&&) returns
true if and only if the operands to the left and right of it are true.

The next code will only return "Yes" if num is greater than 5 and less than 10:

if (num > 5 && num < 10) {


return "Yes";
}
return "No";

Comparisons with the Logical Or Operator


The logical or operator (||) returns true if either of the operands is true. Otherwise, it returns false.
if (num > 10 || num < 5) {
return "No";
}
return "Yes";

Introducing Else If Statements


If you have multiple conditions that need to be addressed, you can chain if statements together with
else if statements.

if (num > 15) {


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

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.

function foo(x) {
if (x < 1) {
return "Less than one";
} else if (x < 2) {
return "Less than two";
} else {
return "Greater than or equal to two";
}
}

Selecting from Many Options with Switch Statements


Write a switch statement which tests val and sets answer for the following conditions:
1 - "alpha"
2 - "beta"
3 - "gamma"
4 - "delta"
function caseInSwitch(val) {
  var answer = "";
  // Only change code below this line
  switch (val) {
  case 1:
  return "alpha";
  break;
  case 2:
  return "beta";
  break;
  case 3:
  return "gamma";
  break;
  case 4:
  return "delta";
  }
    // Only change code above this line
  return answer;
}

caseInSwitch(1);

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.

// Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};

// Only change code below this line

var playerNumber = 16; // Change this line


var player = testObj[playerNumber]; // Change this line

Accessing Nested ObjectsPassed


The sub-properties of objects can be accessed by chaining together the dot or bracket notation.

// Setup
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};

var gloveBoxContents = myStorage.car.inside["glove box"]; // Change this line

Accessing Nested Arrays


As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar
to accessing nested objects, Array bracket notation can be chained to access nested arrays.

// Setup
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];

// Only change code below this line

var secondTree = myPlants[1].list[1]; // Change this line

Record Collection
You start with an updateRecords function that takes an object like collection, an id, a prop (like artist or
tracks), and a value. Complete the function using the rules below to modify the object passed to the
function.
• • Your function must always return the entire object.
• • If prop isn't tracks and value isn't an empty string, update or set that album's prop to
value.
• • If prop is tracks but the album doesn't have a tracks property, create an empty array and
add value to it.
• • If prop is tracks and value isn't an empty string, add value to the end of the album's
existing tracks array.
• • If value is an empty string, delete the given prop property from the album.

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

// Only change code below this line


function updateRecords(object, id, prop, value) {

if (value === "") {


delete object[id][prop];
}

else if (prop === 'tracks') {


object[id][prop] = object[id][prop] || [];
object[id][prop].push(value);
}

else object[id][prop] = value;

return object;
}

updateRecords(collection, 5439, 'artist', 'ABBA');

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]);
}

Remember that arrays have zero-based indexing, which means the last index of the array is length - 1.
Our condition for this loop is i < arr.length, which stops the loop when i is equal to length. In this case
the last iteration is i === 4 i.e. when i becomes equal to arr.length and outputs 6 to the console.
Declare and initialize a variable total to 0. Use a for loop to add the value of each element of the myArr
array to total.

// Setup
var myArr = [ 2, 3, 4, 5, 6];

// Only change code below this line


var total = 0;
for (var i = 0; i < myArr.length; i++) {
total += myArr[i];
}

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.
Modify function multiplyAll so that it returns the product of all the numbers in the sub-arrays of arr.

function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
product = product * arr[i][j];
}
}
// Only change code above this line
return product;
}

multiplyAll([[1,2],[3,4],[5,6,7]]);

Generate Random Fractions with JavaScriptPassed


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
a1

function randomFraction() {

// Only change code below this line

return Math.random();

// Only change code above this line


}

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 1. Use Math.random() to generate a random decimal.
2 2. Multiply that random decimal by 20.
3 3. Use another function, Math.floor() to round the number down to its nearest whole
number.
Putting everything together, this is what our code looks like:
Math.floor(Math.random() * 20);

function randomWholeNum() {

// Only change code below this line

return Math.floor(Math.random() * 10);


}

Generate Random Whole Numbers within a Range


Instead of generating a random whole number between zero and a given number like we did before, we
can generate a random whole number that falls within a range of two specific numbers.
To do this, we'll define a minimum number min and a maximum number max.
Math.floor(Math.random() * (max - min + 1)) + min

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

function randomRange(myMin, myMax) {


// Only change code below this line
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
// Only change code above this line
}

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.

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.

unction convertToInteger(str) {
return parseInt(str, 2)
}
convertToInteger("10011");
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";
}

Use Multiple Conditional (Ternary) Operators


function findGreaterOrEqual(a, b) {
    return (a === b) ? "a and b are equal"
        : (a > b) ? "a is greater"
        : "b is greater";
}

Use Recursion to Create a Range of Numbers


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.

function rangeOfNumbers(startNum, endNum) {


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

You might also like