Week 2 Class Note
Week 2 Class Note
WEEK 02
INSTRUCTORS:
One of the very common things you’ll find amongst beginner developers, is a scenario
where they begin to stare at several lines of code written by them, yet not remembering
the exact purpose of certain aspects of the code. Although this is not the only reason to use
Comments are extra texts which sit within your code but are ignored by the compiler.
These comments have several uses, here we shall outline a few very common and
important ones.
Importance of Comments
Personal Recall: Comments help you the programmer remember exactly what certain
aspects of your code are meant for. Sometimes you can write code, and at the time of
But you could come back a few days later and simply not remember exactly why you wrote
those lines of code. At those times, comments are especially helpful. TODOs
Teamwork: Programmers don’t often work alone on projects, and if you plan on taking
your software development journey through to the end, then at some point in time, you’ll
work with a team. It is therefore important that your teammates understand what each
Comments are useful here, and you do not need to do too much talking, as your code and
carefully laid out to ensure that those who will make use of this official code fully grasp the
Prevent code execution: Oftentimes you might want to prevent some lines of your code
from executing but you also don't want to delete the lines of code. This can be done by
/*
This is a multi line comment
It can extend over several lines
*/
The numbers in an arithmetic operation are called operands, and the operation to be
Divide;
let x = 5;
let y = 2;
let z = x / y;
Remainder;
let x = 5;
let y = 2;
let z = x % y;
Increment;
let x = 5;
x++;
let z = x;
Add;
let x = 5;
let y = 2;
let z = x + y;
Subtract;
let x = 5;
let y = 2;
let z = x - y;
Multiply;
let x = 5;
let y = 2;
let z = x * y;
Decrement;
let x = 5;
x--;
let z = x;
Exponentiation;
let x = 6;
let z = x ** 2;
Operator Precedence
This describes the order in which operations are carried out in a compound arithmetic
expression.
let x = 100 + 50 * 3;
Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?
Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction
(-).
And (as in school mathematics) the precedence can be changed by using parentheses:
let x = (100 + 50) * 3;
When using parentheses, the operations inside the parentheses are computed first.
When many operations have the same precedence (like addition and subtraction), they are
Assignment Operators
Divide and Assign;
let x = 10;
x /= 5;
Normal Assignment;
let x = 10;
Comparison/Relational Operators
Given that x = 5; the following table explains the behavior of comparison operators.
These operators can be used in conditional statements to compare values and take some
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x = 6; and y = 3; the following table explains the behavior of logical
operators.
Type Operators
And there are 6 types of objects
Object
Date
Array
String
Number
Boolean
null
undefined
Data Types
string
number
boolean
object
function
You can use the typeof operator to find the data type of a JavaScript variable.
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"
Note that;
The data type of a variable that has not been assigned a value is also undefined *
conditions. The decision making capability of your program most of the time will be tied to
conditional statements.
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
If statement
The if Statement: Use the if statement to specify a block of JavaScript code to be executed if
a condition is true.
Syntax:
if (condition) {
// block of code to be executed if the condition is
true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript
error.
If statement examples
If else statements
Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
If else statements examples
If the hour is less than 18, create a "Good day" greeting, otherwise
"Good evening":
let hour = 17
let greeting;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
console.log(greeting); // result: Good day
If else if statements
Use the else if statement to specify a new condition if the first condition is false.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
If time is less than 10, create a "Good morning" greeting, if not, but time is less than 20,
JavaScript has some very weird rules concerning how you compare values or variables of
different types, as such it should be avoided as much as possible. To secure proper results,
variables should be converted to the proper type before comparison is carried out.
When comparing string with a number, JavaScript will convert the string to a number when
doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN
The following table explains this a little better by looking at a few scenarios or cases.
Example cases…
When comparing two strings, “2” will be greater than “12” because (alphabetically) 1 is less
than 2.
You can already begin to see how complicated and how difficult it can get, keeping track of
This operator can be especially useful, so keep an eye out for it as we go along. This
operator allows you assign a value to a variable based on some condition in a very neat
Syntax:
variablename = (condition) ? value1:value2
Usage:
let voteable = (age < 18) ? "Too young":"Old enough";
If the variable age is a value below 18, the value of the variable voteable will be "Too
Switch statement
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The switch statement, just like the if else statement, is used to perform different actions
The value of the expression is compared with the values of each case.
let dayOfWeekIndex = 3;
let day;
switch (dayOfWeekIndex) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
console.log(day);
// result: Wednesday
When JavaScript reaches a break keyword, it breaks out of the switch block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there
anyway.
Note: If you omit the break statement, the next case will be executed even if the evaluation
The default keyword specifies the code to run if there is no case match. The default case
JavaScript Strings
String Operations
let text = "John Doe";
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
To find the length of a string, use the built-in length property:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Because strings must be written within quotes, JavaScript will misunderstand this string;
let text = "We are the so-called "Vikings" from the north.";
The string will be chopped to "We are the so-called ".
The solution to avoid this problem is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
let str = "Apple, Banana, Kiwi";
let part = str.slice(7, 13);
JavaScript counts positions from zero.
First position is 0.
Second position is 1.
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
let str = "Apple, Banana, Kiwi";
let part = str.slice(-12, -6);
If you omit the second parameter, the method will slice out the rest of the string:
let part = str.slice(7);
The replace() method replaces a specified value with another value in a string:
let text = "Please visit medPlan!";
let newText = text.replace("medPlan", "Deebug");
let text = "Please visit medPlan and medPlan!";
let newText = text.replace("medPlan", "Deebug");
The replace() method does not change the string it is called on.
If you want to replace all matches, use a regular expression with the /g flag set. See
examples below.
To replace all matches, use a regular expression with a /g flag (global match):
let text = "Please visit medPlan and medPlan!";
let newText = text.replace(/medPlan/g, "Deebug");
The concat() method can be used instead of the plus operator. These two lines do the
same:
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
All string methods return a new string. They don't modify the original string.
An array is a special variable which can hold more than one value:
const cars = ["Saab", "Volvo", "BMW"];
Syntax:
const array_name = [item1, item2, ...];
const cars = ["Porsche", "Bugatti", "Rolls Royce"];
Spaces and line breaks are not important. A declaration can span multiple lines:
const cars = [
"Porsche",
"Bugatti",
"Rolls Royce"
];
You can also create an array, and then provide the elements:
const cars = [];
cars[0]= "Porsche";
cars[1]= "Bugatti";
cars[2]= "Rolls Royce";
The following example also creates an Array, and assigns values to it:
const cars = new Array("Porsche", "Bugatti", "Rolls Royce");
There is no need to use new Array().
For simplicity, readability and execution speed, use the array literal method.
Accessing Array Elements
You access an array element by referring to the index number:
const cars = ["Porsche", "Bugatti", "Rolls Royce"];
let car = cars[0];
Arrays are a special type of object. The typeof operator in JavaScript returns "object" for
arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
const person = ["John", "Doe", 46];
Array Properties & Methods
toString()
The JavaScript method toString() converts an array to a string of (comma separated) array
values.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.toString()); // Result: Banana,Orange,Apple,Mango
join()
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.join(" * ")); // Result: Banana * Orange * Apple *
Mango
pop()
push()
The push() method adds a new element to an array (at the end):
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Shift()
Shifting is equivalent to popping, but working on the first element instead of the last
The shift() method removes the first array element and "shifts" all other elements to a
lower index.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
The shift() method returns the value that was "shifted out":
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift();
unshift()
The unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
length
The length property provides an easy way to append a new element to an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";
delete
The concat() method creates a new array by merging (concatenating) existing arrays:
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);
The concat() method can take any number of array arguments:
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);
More on Arrays
JavaScript has a built in array constructor new Array().
These two different statements both create a new empty array named points:
const points = new Array();
const points = [];
These two different statements both create a new array containing 6 numbers:
const points = new Array(40, 100, 1, 5, 25, 10);
const points = [40, 100, 1, 5, 25, 10];
const points = new Array(40, 100, 1); // Create an array with three
elements:
const points = new Array(40, 100); // Create an array with two
elements:
Array.isArray(fruits);
Week 2 Completed
Arigato gozaimasu ;)