0% found this document useful (0 votes)
6 views30 pages

Wednesday 9 - 04 - 24

Uploaded by

kritagyakumra777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views30 pages

Wednesday 9 - 04 - 24

Uploaded by

kritagyakumra777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

CS 5220

- Advanced Topics in Web Programming -


Prof. Cydney Auman
AGENDA

01 JavaScript Control Flow


03 Strings and Arrays

02 JavaScript Functions
04 Objects
01
JAVASCRIPT
CONTROL
FLOW
Conditionals
Conditional execution is created with the if keyword in JavaScript. In the simple case, we want some code to be
executed if a certain condition holds. Often times your code needs to handle the other cases. You can use the else if
and else keyword to create alternative execution paths.

const unknown = 'xyz';

if (typeof unknown === 'string') {


console.log('value is a string');
} else if (typeof unknown === 'number') {
console.log('value is a number');
} else {
console.log('value is not a number or string');
}
Ternary Conditional
JavaScript supports a conditional known as the Ternary, because it operates on three values.

A ternary will begin with a conditional which is followed by a ?. After the ? is the truth statement. After the truth
statement there is a : which is followed by the false statement.

If the conditional is evaluated to true, then the statement directly right of the ? executes. If the conditional is
evaluated to false, then the statement directly right of the : executes.

// conditional ? true statement : false statement


const degreesCelsius = 2;
const H2O = degreesCelsius > 0 ? 'liquid' : 'solid';
For Loop
A "for loop" is a control flow structure in programming that allows for repeating a block of code a specific number of
times. It consists of three parts:

● Initialization: It initializes a loop control variable to an initial value.

● Condition: It specifies the condition that is checked before each iteration. If the condition is true, the loop
continues. If it's false, the loop terminates.

● Iteration: It defines how the loop control variable is changed or modified after each iteration.

for (let number = 1; number < 10; number++) {


console.log(number);
}
continue and break
Inside the for loop we can use "continue" and "break" statements to provide more control over the flow. This allows to
customize how code behaves under certain conditions.

● continue
○ This statement is used within a loop to skip the current iteration and move to the next one. It's typically used
when we want to bypass some code execution for a given condition but continue with the rest of the loop.

● break
○ This statement is used to exit a loop early. It's often used when a specific condition is met and we need to
stop the loop from continuing.
02
JAVASCRIPT
FUNCTIONS
Functions
Functions are fundamental in JavaScript. They enable modular and organized code by abstracting complex logic
into reusable modules. Functions also promote code reusability and maintainability.

Functions have their own scopes and thus reduce variable conflicts. Furthermore, they play an important role in
both event handling and asynchronous operations.

JavaScript provides several ways to define functions, including function declarations, function expressions and
arrow functions.
Function Declaration
● Syntax
○ Function declarations start with the function keyword followed by a function name and then optional
arguments. The function body is enclosed in curly braces.

● Hoist
○ Function declarations are hoisted. This means they are moved to the top of their containing scope. And can be
called anywhere in your code before it's defined.

add(1, 2); // no error because hoisted


function add(a, b) {
const sum = a + b;
return sum;
}
add(2, 3);
Function Expression
● Syntax
○ Function expressions define the function as values and are assigned to variables. They are anonymous
functions as they do not require a function name.

● Hoist
○ Function expressions are not hoisted. This means you can only call the function expression after it is defined.
This is considered a best practice. Because the behavior follows the logical code flow - the function is
defined and then called.

const add = function (a, b) {


const sum = a + b;
return sum;
};
add(2, 3);
Arrow Functions
● Syntax
○ Introduced in ES6. These are also considered an expression. And for the most part are a compact alternative
to a traditional function expressions seen in the slide above. The difference is arrow functions don't have
their "this" binding and instead inherit the "this" value from their surrounding context.

● Hoist
○ Arrow function are not hoisted. This means you can only call the function expression after it is defined. This is
also considered a best practice.

const add = (a, b) => {


const sum = a + b;
return sum;
};
add(2, 3);
First Class Functions
First Class functions in a programming language are functions that are treated like any other data type such as
numbers or strings. This means functions can be assigned to variables, passed as arguments to other
functions, returned from functions as values and stored in data structures like arrays or objects.

One of the benefits with using First Class functions is that it enables developers to write more expressive and
flexible code. This facilitates modular design, code reusability and the creation of more elegant and concise
solutions to complex problems.
03
STRINGS
ARRAYS
String Iterating

Strings in JavaScript can be iterated using either the for loop or the for...of loop.

Here we can use a for loop to iterate over the characters of a string by accessing each character by their index
position.

const str = 'Hello World';

for (let i = 0; i < str.length; i++) {


const letter = str[i];
console.log(letter);
}
Basic String Properties & Methods
JavaScript provides many methods on strings. A comprehensive list can be found at:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

Property
length
● property of a String that will return the length of the String

Methods
charAt(index)
● returns the character String at the index position specified
includes(value)
● determines whether the String includes the specified value and returns a boolean
split(value)
● divides a String into list of substrings , puts these into an array and return the array
toLowerCase()
● method returns the calling String value converted to lowercase
toUpperCase()
● method returns the calling String value converted to uppercase
Mutation
A value is mutable if it can be altered without creating a new value. Therefore, mutation is the act of
changing or modifying the state or content of an object or array. Mutation typically involves altering
the value or properties of these data structure.

JavaScript primitive types are immutable - they cannot change their values or properties. Any
operation that appears to modify a primitive type actually creates a new value and re-assigns it.

Arrays and Objects in JavaScript are considered mutable. We can change the contents of these data
structures.

The keywords const and let only control whether a variable can be re-assigned and have nothing to do
with mutation of properties.
Arrays
JavaScript provides a data type called an array specifically for storing sequences of values. An array is written as a
list of values between square brackets, separated by commas. When declaring an array there is no need to use the
new keyword.

const alpha = ['a', 'b', 'c', 'd'];

● Elements in the array can be accessed by index. The first index of an array is zero. So the first element is retrieved
with alpha[0] which return the value 'a'.
● Javascript arrays also have a length property. This tells us how many elements it has inside the array.
alpha.length will return 4.

*The contents of an array in JavaScript can be almost anything and in fact JavaScript arrays can have mixed data types.
Array Iterating
Arrays can be iterated using either the for loop or the for...of loop.

The for...of loop was introduced in ES6. It is primarily used to iterate over the values in arrays and strings. It
provides a convenient way to access the values of an iterable, one at a time.

*It does not iterate over object properties but instead the elements or values contained within it. Thus the for...of
loop is typically not used with object literals.

const courses = [3220, 4220, 5220]

for (const course of courses) {


console.log(course);
}
Basic Array Methods
JavaScript provides many methods on arrays. A comprehensive list can be found at:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#

push(value)
● adds one or more elements to the end of an array.
pop()
● removes the last element from an array and returns that element.
unshift(value)
● adds one or more elements to the beginning of an array.
shift()
● removes the first element from an array and returns that element.
reverse()
● reverses an array in place. The first array element becomes the last, and the last array element becomes the first
concat(array)
● merges two or more arrays - this method does not change the existing arrays, but instead returns a new array
join(value)
● returns a String concatenating the elements in the array by the value specified
includes(value)
● determines whether the array includes the specified value and returns a boolean
sort()
● sorts the elements of an array in place and returns the sorted array - the default sort order is ascending.
Higher Array Methods
JavaScript provides many methods on arrays. A comprehensive list can be found at:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#

forEach(fn)
● method iterates and executes the provided function once for each element in the array. does not return.
map(fn)
● method creates and returns a new array populated with the results of executing the provided function on every element in the original
array.
filter(fn)
● method creates and returns new array with all elements that pass the filter expression implemented in the provided function
find(fn)
● method returns the first element in the provided array that satisfies the condition in the provided function
findIndex(fn)
● method returns the index of the element in the provided array that satisfies the condition in the provided function. If no elements
satisfy the testing function, -1 is returned.
04
OBJECTS
Object Literals
An object is a collection of related data consisting of key/value pairs. These key/value pairs can be added or removed at
anytime.

One way to create an object is by using a curly brace notation. An object like this is referred to as an object literal — we are
writing out the object contents as we create it. The object literal syntax is used for creating objects directly in our code,
without the need for a class or constructor function.

To create an object literal, you only need to declare a variable and then set it equal to {}. Because this is object literal
notation, properties and values can be added on declaration. The key/property is on the left side of the : and the value for
that key is on the right side.

const course = {
department: 'Computer Science',
number: 5220
};
Objects Access
There are two ways to access properties/keys from an object - dot notation and bracket notation.

dot notation
● specify the object name followed by a dot and then by the property/key name.

bracket notation
● specify the object name, then a bracket followed by a variable or string which represents the property/key name and then
close the bracket.

const course = {
department: 'Computer Science',
number: 5220
};
// uses dot notation to access the department property
console.log(course.department)

// uses bracket notation with string to access the department property


console.log(course['department'])
Bracket Notation
In JavaScript bracket notation is used for both array access using the index OR object access by using
the key.

As we start working with both objects and arrays - it is important to keep in mind when using bracket
notation which data structure we are working with.

Arrays will use the index in order to access a value inside an array.
const arr = ['mercury', 'venus', 'earth']
console.log(arr[0]) // mercury

Objects will use the key in order to access the value inside the object.
const course = {
department: 'Computer Science',
number: 5220
};
console.log(course['department']) // Computer Science
Objects Add & Remove Properties/Keys
Adding Properties/Keys
To add properties to an object the format is generally the object name followed by a dot and then by the
key name. Alternatively, bracket notation can be used as well.

course.room = 'SH162';
course['startTime'] = '7:25pm';

Removing Properties/Keys
To remove properties from an object use the keyword delete followed by the object name dot key.
Alternatively, bracket notation can be used as well.

delete course.room;
delete course['startTime'];
Objects Iterating
A for...in loop is used to iterate over the properties of an object. This is used when we need to loop through the
keys or property names of an object.

The for...in loop iterates the properties of an object in an arbitrary order. Therefore this loop should not be used
with Arrays anytime index order is important.

const course = {
department: 'Computer Science',
number: 5220
};

for (const key in course) {


console.log(key);
console.log(course[key]);
}
Object Methods
JavaScript provides many methods on objects. A comprehensive list can be found at:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

assign(target, source)
● copies all properties from one or more source objects to a target object. This method returns the target object.

entries()
● returns an array of a given object's properties as an array of [key, value] pairs

keys()
● returns an array of a given object's property names

values()
● returns an array of a given object's values
Quiz
● Due Sunday 09/08 @ 11:59pm

Review

● Review Slides
● Review Code Examples
● Ensure you can run the demo_9_04.js file

Next Week
● Advanced ES6 Syntax
● Intro to Async JavaScript
○ Promises, Callbacks, Async/Await
REFERENCES
● JavaScript Control Flow
○ https://javascript.info/ifelse
○ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling
○ https://javascript.info/while-for
○ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

● JavaScript Functions
○ https://github.com/lukehoban/es6features
○ https://javascript.info/function-basics
○ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

● JavaScript Arrays and Objects


○ https://javascript.info/array
○ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
○ https://javascript.info/object
○ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

You might also like