0% found this document useful (0 votes)
15 views

Week 2 Class Note

The document covers JavaScript fundamentals, focusing on comments, operators, expressions, conditional statements, and string operations. It emphasizes the importance of comments for personal recall and teamwork, explains various types of operators, and details how to use conditional statements like if, else, and switch. Additionally, it discusses string manipulation methods and the significance of data types in JavaScript.

Uploaded by

ettolrahcava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Week 2 Class Note

The document covers JavaScript fundamentals, focusing on comments, operators, expressions, conditional statements, and string operations. It emphasizes the importance of comments for personal recall and teamwork, explains various types of operators, and details how to use conditional statements like if, else, and switch. Additionally, it discusses string manipulation methods and the significance of data types in JavaScript.

Uploaded by

ettolrahcava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

JavaScript Fundamentals & JavaScript Arrays

WEEK 02
INSTRUCTORS:

OFURUM CHIZITERE || [email protected]

Topics: Comments, Operators, Expressions, if statements, Ternary

Operators, Switch case, String operations, Arrays.


JavaScript Comments

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 when writing your code, it is as good a reason as any.

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

writing, you know exactly what each line of code does.

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

aspect of your code does.

Comments are useful here, and you do not need to do too much talking, as your code and

carefully laid out comments will do the bulk of the explanation.


Official documentation: When code has been written and is now accepted as official

code, in any particular programming language/framework/SDK, comments must be

carefully laid out to ensure that those who will make use of this official code fully grasp the

capabilities of these frameworks and SDKS.

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

“commenting out” the lines of code.

Single line comment vs. Multi line comment


// This is a single line comment
// This is also a single line comment, it will not be executed as
code

/*
This is a multi line comment
It can extend over several lines
*/

Operators & Expressions

Arithmetic Operators: These perform arithmetic on numbers (literals or variables)


Arithmetic with literals:
let sum = 100 + 50;

Arithmetic with variables:


let sum = num1 + num2;

Arithmetic with expressions:


let sum = (100 + 50) * num1;

The numbers in an arithmetic operation are called operands, and the operation to be

carried out is defined by the operator;

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?

Is the addition or the multiplication done first?

As in traditional school mathematics, the multiplication is done first.

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

computed from left to right:


let x = 100 + 50 - 3;

Assignment Operators
Divide and Assign;
let x = 10;
x /= 5;

Get remainder and Assign;


let x = 10;
x %= 5;

Normal Assignment;
let x = 10;

Add and Assign;


let x = 10;
x += 5;

Subtract and Assign;


let x = 10;
x -= 5;
Multiply and Assign;
let x = 10;
x *= 5;

Comparison/Relational Operators

Comparison operators are used in logical statements to determine equality or difference

between variables or values.

Given that x = 5; the following table explains the behavior of comparison operators.

Comparison Operators Usage

These operators can be used in conditional statements to compare values and take some

form of action depending on the result gotten from the operation;


if (age < 18) text = "Too young to vote";

Logical Operators

Comparison Operators Usage

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

And 2 data types that cannot contain values

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 NaN is number

The data type of an array is object

The data type of a date is object

The data type of null is object

The data type of an undefined variable is undefined *

The data type of a variable that has not been assigned a value is also undefined *

Conditional Branching (if statements)

Conditional statements allow you to perform different actions based on different

conditions. The decision making capability of your program most of the time will be tied to

conditional statements.

Conditional statements in JavaScript:

Use if to specify a block of code to be executed, if a specified condition is true

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

Use switch to specify many alternative blocks of code to be executed

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

Make a “Good day” greeting if the hour is less than 18


let hour = 15;
let greeting;

if (hour < 18) {


greeting = "Good day";
}
console.log(greeting); // result: Good day

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 else if statements examples

If time is less than 10, create a "Good morning" greeting, if not, but time is less than 20,

create a "Good day" greeting, otherwise a "Good evening":


let time = 6; let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
console.log(greeting); // result: Good morning

Comparing Variables & Values of different data types

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.

Consider the following;

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

(Not a Number) which is always false.

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

all of this JS weirdness.

Comparing Variables & Values of different types


let age = “10”;
// The statement below tries to convert age to a number type
// and if it cannot, it will return NaN (which is always false)
age = Number(age);
if (isNaN(age)) {
voteable = "Input is not a number";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}

JavaScript Ternary Operators

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

way; Assuming; let age = 23;

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

young", otherwise the value of voteable will be "Old enough".


JavaScript Switch Case

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

based on different conditions.

How the switch works.

The switch expression is evaluated once.

The value of the expression is compared with the values of each case.

If there is a match, the associated block of code is executed.

If there is no match, the default code block is executed.

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

The break and default keywords

When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution inside 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

does not match the case.

The default keyword specifies the code to run if there is no case match. The default case

does not have to be the last case in a switch block.

The break and default keywords


let dayOfWeekIndex = 3;
let text;
switch (dayOfWeekIndex ) {
default:
text = "Looking forward to the Weekend";
break;
case 6:
text = "Today is Wednesday";
break;
case 0:
text = "Today is Sunday";
}

JavaScript Strings

String Operations
let text = "John Doe";

You can use single or double quotes:


let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes

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;

String Operations, Escape Characters

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

The sequence \" inserts a double quote in a string:


let text = "We are the so-called \"Vikings\" from the north.";

The sequence \' inserts a single quote in a string:


let text= 'It\'s alright.';

The sequence \\ inserts a backslash in a string:


let text = "The character \\ is called backslash.";

String Operations, Escape Characters

Six other escape sequences are valid in JavaScript:


Extracting String Parts: There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)

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

or, counting from the end:

let part = str.slice(-12);

substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.


let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
If you omit the second parameter, substring() will slice out the rest of the string.

String Methods - Replacing String content

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");

By default, the replace() method is case sensitive.

Writing MEDPLAN (with upper-case) will not work:


let text = "Please visit medPlan!";
let newText = text.replace("MEDPLAN", "Deebug");

The replace() method does not change the string it is called on.

The replace() method returns a new string.

The replace() method replaces only the first match

If you want to replace all matches, use a regular expression with the /g flag set. See

examples below.

To replace case insensitive, use a regular expression with an /i flag (insensitive):


let text = "Please visit medPlan!";
let newText = text.replace(/MEDPLAN/i, "Deebug");
Regular expressions are written without quotes.

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");

String Methods - Upper and Lower Case

A string is converted to uppercase with toUpperCase():

A string is converted to lowercase with toLowerCase():


let text1 = "Hello World!";
let text2 = text1.toUpperCase();

let text1 = "Hello World!"; // String


let text2 = text1.toLowerCase(); // text2 is text1 converted to
lower

String Methods - concatenation

concat() joins two or more strings:


let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);

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.

Formally said:Strings are immutable: Strings cannot be changed, only replaced


JavaScript Arrays

An array is a special variable which can hold more than one value:
const cars = ["Saab", "Volvo", "BMW"];

Using an array literal is the easiest way to create a JavaScript Array.

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";

Using the JavaScript Keyword new

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

Changing an Array Element


This statement changes the value of the first element in cars:
const cars = ["Porsche", "Bugatti", "Rolls Royce"];
cars[0] = "Toyota";
Array indexes start with 0.

[0] is the first element. [1] is the second element.

Access the entire array


With JavaScript, the full array can be accessed by referring to the array name:
const cars = ["Porsche", "Bugatti", "Rolls Royce"];
console.log(cars);

Arrays are Objects

Arrays are a special type of object. The typeof operator in JavaScript returns "object" for

arrays.

But, JavaScript arrays are best described as 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

Popping & Pushing


When you work with arrays, it is easy to remove elements and add new elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.

pop()

The pop() method removes the last element from an array:


const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
The pop() method returns the value that was "popped out":
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.pop();

push()

The push() method adds a new element to an array (at the end):
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");

The push() method returns the new array length:


const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.push("Kiwi");

Shifting & Unshifting elements

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");

The unshift() method returns the new array length.


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

Array elements can be deleted using the JavaScript operator delete.

Using delete leaves undefined holes in the array.

Use pop() or shift() instead.


const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];

Merging (Concatenating) Arrays

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

The concat() method can also take strings as arguments:


const arr1 = ["Emil", "Tobias", "Linus"];
const myChildren = arr1.concat("Peter");

More on Arrays
JavaScript has a built in array constructor new Array().

But you can safely use [] instead.

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:

const points = [40];


is not the same as:
const points = new Array(40);

// Create an array with one element:


const points = [40];
// Create an array with 40 undefined elements:
const points = new Array(40);

How to Recognize an array


To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray():

Array.isArray(fruits);

The instanceof operator returns true if an object is created by a given constructor:


const fruits = ["Banana", "Orange", "Apple"];
fruits instanceof Array;

Week 2 Completed

Arigato gozaimasu ;)

You might also like