1 of 106

Intro to Javascript

Basic Training

Session 2

2 of 106

2

As a community, we will...

Be present, physically and mentally

Actively build an inclusive community and space

Practice curiosity and adopt a learning mindset

Ask for help when we need it

Keep our cameras on

3 of 106

Your TA today

3

Harvey Zhao

(He/Him)

4 of 106

Course Expectations

5 minutes

5 of 106

Course Overview

This lecture, we will cover topics including…

  • Javascript Variables
  • Javascript Functions
  • Javascript Objects
  • Javascript Control Flow
  • Using JS to edit webpage

5

Programming Language

Python 3 | Java 8

6 of 106

Session Goals

At the end of this class you will be able to...

  • improve proficiency and confidence in writing javascript code
  • Understand how to add an event listener to your webpage
  • Know where to look for next

6

7 of 106

Policies: Attendance

  • All homework are optional. However, doing them will help you a lot with the project and getting an internship this cycle!
  • Please be present at all times during this class and beyond. I promise that you will get enough breaks in between!
  • Zoom session link- https://ucla.zoom.us/j/98078299544?pwd=VGt5N28yNnE3RHE5YjdMcW9Pb2dUdz09

7

8 of 106

Breakout Rooms

  • We’ll split up into breakout rooms during this session
  • You work in a group of 3-6 students
  • Breakout sessions will comprise of solving problems and pair programming

8

9 of 106

IceBreaker!

10 min

10 of 106

15 mins

  1. Introduce yourself! Answer one of the icebreaker questions
    • Name
    • Where are you located?
    • Name One thing that made you happy and another thing that made you angry today.
  2. Spend 5 mins sharing out your ideas and determining 1-2 funny ones that you want to share with the class.

10

Breakout Rooms

Questions? Post on Slack and tag:

11 of 106

Javascript Basics

120 minutes

12 of 106

What is Javascript?

  • JavaScript is a lightweight interpreted scripting/programming language that is heavily used in Web Applications and even beyond them!

  • Despite JavaScript being the most commonly used programming language in the world, developers have a love-hate relationship with it.

12

13 of 106

Hello World

  • JavaScript is heavily used within Web Applications. In fact, we can even insert JavaScript into our HTML files with the script tag!

13

14 of 106

Hello World

  • The script tag executes javascript code in the browser, but it can get really messy to have one giant file with both HTML and JS.

  • we can put our separate JavaScript code within a separate JavaScript file with the .js extension.

  • We can link back to it in our code with the src property of our script tag!

14

15 of 106

Node.js�

  • there are actually other ways to execute JS code without your browser.
  • Node is a JavaScript runtime which is a way to execute your javascript code files without using your browser, and you can run a file by simply calling

  • However, we mainly use its built-in package manager, npm. It allows us to run a build of our website:

15

16 of 106

Variables & Primitive Types!

17 of 106

Variables�

  • To declare variables:

  • Unlike other statically typed languages like C++, Java, JavaScript is dynamically typed which means that the types of variables, return values of functions, etc are all evaluated at runtime. In statically typed languages, you have to declare the type of the variable when you make it. But in JavaScript, you just have to say let, and the browser figures out what type it is.

  • JavaScript still has types to it! In JavaScript, everything is either a primitive data type or an object,

17

18 of 106

Variable Scope

  • JS Variables have "function scope". They are visible in the function where they're defined:

  • A variable with "local" scope:

18

19 of 106

Variable Scope

  • A variable with "global" scope:

19

20 of 106

Variable Scope: var vs const vs let

  • It can get confusing, but here is a general guideline:
    • Use const by default
    • Use let if you have to rebind a variable to another value
    • Use var to signal untouched legacy code.

20

21 of 106

Question Break

5 min

22 of 106

Primitive Types�

  • Six primitive data types:

    • String
    • Number
    • Bigint
    • Boolean
    • Null
    • undefined

22

23 of 106

Primitive types are immutable�

  • In memory, primitive types are represented with their actual value in memory, and their values are immutable.

23

24 of 106

Variable Exercise

5 minutes

25 of 106

10 minutes

  • Decide in your pods which platform you want to use.
    • We suggest using Replit or Collabedit
  • Assign roles for each question so everyone can participate

25

Breakout Rooms

Questions? Post on Slack and tag:

26 of 106

The Age Calculator

Want to find out how old you'll be? Calculate it!

  • Store your birth year in a variable.
  • Store a future year in a variable.
  • Calculate your 2 possible ages for that year based on the stored values.
  • For example, if you were born in 1988, then in 2026 you'll be either 37 or 38, depending on what month it is in 2026.
  • Output them to the screen like so: "I will be either NN or NN in YYYY", substituting the values.

26

27 of 106

Solution

const birthYear = 1984;

const futureYear = 2012;

const age = futureYear - birthYear;

console.log('I will be either ' + age + ' or ' + (age - 1));

27

28 of 106

Question Break

2 min

29 of 106

Type Coercion & Operators

30 of 106

For fun - Type Coercion: equal or not equal?

  • In JavaScript, there are actually two ways to compare values.

  • How is this difference significant, you may ask!

  • Type coercion is not always desirable, especially when we do web development!

30

31 of 106

Type Coercion: equal or not equal?

  • Values that are coerced to false are the following:
    • 0
    • null
    • undefined
    • "" (empty string)
    • NaN
  • This is really helpful because in our code, we can make sanitizers like this super clean:

31

32 of 106

Comparison Operators

  • Use these operators to compare two values for equality, inequality, or difference.

32

33 of 106

Logical Operators

  • These are typically used in combination with the comparison operators:

33

34 of 106

Short-circuit Eval

  • JS evaluates logical operators from left to right and stops evaluating as soon as it knows the answer.

  • (false && anything) => false
  • (true || anything) => true

34

35 of 106

Question Break

5 min

36 of 106

Functions

37 of 106

Important! JavaScript Functions

  • Javascript is a functional programming language. By the sound of that, functions are probably pretty important. They look pretty C-like to us:

37

38 of 106

JavaScript Functions

  • You start by writing the keyword function, function name(parameters) either an explicit return statement, or an implicit empty return (return;)
  • Note that there are no explicit return types here! This can actually make things quite confusing.

38

39 of 106

Function: Arguments

  • Functions can accept any number of named arguments:

  • You can also pass variables:

39

40 of 106

Functions: Return Values

  • The return keyword returns a value to whoever calls the function (and exits the function):

  • You can use function calls in expressions:

40

41 of 106

JavaScript Functions

  • In this case, we’d want to coerce values inside the function to our desired return type.

  • you often have to write code like this when interfacing with other libraries, as guaranteeing types is tricky!

41

42 of 106

Beware: Circular Dependencies�

42

43 of 106

Question Break

2 min

44 of 106

Function Exercises

25 min

45 of 106

The Lifetime Supply Calculator

Ever wonder how much a "lifetime supply" of your favorite snack is? Wonder no more!

  • Write a function named calculateSupply that:
  • takes 2 arguments: age, amount per day.
  • calculates the amount consumed for rest of the life (based on a constant max age).
  • outputs the result to the screen like so: "You will need NN to last you until the ripe old age of X"
  • Call that function three times, passing in different values each time.

45

46 of 106

Solution

  • function calculateSupply(age, numPerDay) {

var maxAge = 100;

var totalNeeded = (numPerDay * 365) * (maxAge - age);

var message = 'You will need ' + totalNeeded + ' cups of tea to last you until the ripe old age of ' + maxAge; console.log(message);

}

calculateSupply(28, 36);

calculateSupply(28, 2.5);

calculateSupply(28, 400);

46

47 of 106

The Calculator

  • Write a function called squareNumber that will take one argument (a number), square that number, and return the result. It should also log a string like "The result of squaring the number 3 is 9."
  • Write a function called halfNumber that will take one argument (a number), divide it by 2, and return the result. It should also log a string like "Half of 5 is 2.5.".
  • Write a function called percentOf that will take two numbers, figure out what percent the first number represents of the second number, and return the result. It should also log a string like "2 is 50% of 4."
  • Write a function called areaOfCircle that will take one argument (the radius), calculate the area based on that, and return the result. It should also log a string like "The area for a circle with radius 2 is 12.566370614359172."
  • Write a function doCrazyStuff that will take one argument (a number) and perform the following operations, using functions you wrote earlier1:

1. Take the half of the number and store the result.

2. square the result of #1 and store that result.

3. Calculate the area of a circle with the result of #2 as the radius.

4. Calculate what percentage that area is of the squared result (#3).

47

48 of 106

Solution

48

49 of 106

Solution

49

50 of 106

JavaScript Functions Review

  • In the following code, name the data types used, describe the scope for the variables, and spot the: statement, variable, expression, operator, function, argument, and return value.

50

51 of 106

Biggggg Break

10 min

52 of 106

For fun - Javascript Functions: first-class citizens

  • Functions are treated like any other data type. In this case, that means that... functions are objects too!

52

53 of 106

Javascript Functions: first-class citizens

  • Wow! That's not something you'll see often. The lack of type annotations makes this a little tricky to understand, but we're basically pointing greeter to the "function body" of saySomething!

  • Every time you use the name of the function without parentheses or its parameters, it's the reference to the function - just like any other variable!

  • Let’s practice with 2 examples.

53

54 of 106

For fun - Anonymous Functions

  • You'll find higher order functions often in React apps when you need to generate lists of components from data.

  • Anonymous function is just a compostable function!
  • Let's say we wanted to double all elements of the nums array again, but we only need to really do this operation once. It wouldn't make sense to write a whole function, so we'd like for a slightly more disposable medium.

54

55 of 106

DS: Array

56 of 106

Array Data Type

An array is a type of data-type that holds an ordered list of values, of any type:

  • Key takeaways of arrays:
    • Arrays in JS can have multiple types in them
    • They can be used as stacks/queues.
    • Arrays are Objects

56

57 of 106

Array Access

  • You can access items with "bracket notation". The index starts at 0.

57

58 of 106

Changing Arrays

  • You can also use bracket notation to change the item in an array:

  • Or to add to an array:

58

59 of 106

Question Break

2 min

60 of 106

Conditionals & Loop

61 of 106

Conditionals

  • Just like in other languages, we can make loops and do conditionals! I won't bore you with the syntax, but here's some quick examples:

  • If-else statement

61

62 of 106

The if/else if/else statement�

  • You can use else if if you have multiple exclusive conditions to check:

62

63 of 106

Loops: while loop

  • The while loop tells JS to repeat statements until a condition is true:

63

64 of 106

Loops: For Loop

  • For loop

64

65 of 106

Loops: For Loops – other ways to do it

65

66 of 106

Using for loops with arrays and strings

  • Use a for loop to easily process each item in an array:

  • Or a string:

66

67 of 106

The break statement�

  • To prematurely exit a loop, use the break statement:

67

68 of 106

Question Break

2 min

69 of 106

Arrays + conditionals Exercises

30 min

70 of 106

1. The Grade Assigner

  • Write a function named assignGrade that:
  • takes 1 argument, a number score.
  • returns a grade for the score, either "A", "B", "C", "D", or "F".
  • Call that function for a few different scores and log the result to make sure it works.

70

71 of 106

2. The Grade Assigner +

  • Check the results of your assignGrade function from the conditionals exercise by logging every value from 60 to 100: your log should show "For 88, you got a B. For 89, you got a B. For 90, you got an A. For 91, you got an A.", etc., logging each grade point in the range.

71

72 of 106

3. Your top choices

  • Create an array to hold your top choices (colors, presidents, whatever).
  • For each choice, log to the screen a string like: "My #1 choice is blue."
  • Bonus: Change it to log "My 1st choice, "My 2nd choice", "My 3rd choice", picking the right suffix for the number based on what it is.

72

73 of 106

The Grade Assigner: Solution

73

74 of 106

The Grade Assigner + Solution

74

75 of 106

Your top choices: solution

75

76 of 106

Question Break

2 min

77 of 106

Big Break!

10 min

78 of 106

For fun: Anonymous Functions

  • Let's break down the syntax a little. Just like Python, we have:
    • Indication of the start of a function with the keyword
    • The parameter list or arguments to the function (the part in ())
    • The body of the function (in our case, the part in {})

78

79 of 106

For fun: Objects vs Primitives: Array

  • Everything not a primitive is an object!
    • Memory storage: primitives are directly represented, objects store references to addresses.
    • Let’s see how an array is stored in memory:

79

80 of 106

For fun: Objects vs Primitives: Array

  • First, let's take a look at the const keyword.
  • The reason why we can change the value of arr[2] even though it's declared const is because the const keyword defines a constant reference to a value for objects.
  • Referential equality is used for nested data types. (Nested data types are objects with {}, arrays with [], or anything that's not the five primitive types we covered above).

80

81 of 106

For fun: Spread Operator: real copy object

  • Just like with primitive types, === compares the value associated with each variable. However, here we can see that the value actually corresponds to a corresponding address in memory where the Object is stored!

  • If we want to create a new object in memory that's based off of the previous one, we have to use the spread operator.

81

82 of 106

For fun: Spread Operator: real copy object

  • The spread operator passes in the values within the object, but creates a new reference to a new object in memory!

82

83 of 106

Question Break

2 min

84 of 106

Objects

85 of 106

Objects: mother of every data type

  • That's right, this array was an object.
  • Under the hood, when we called let arr, we "called the constructor for an array" (not... entirely true).
  • Then, when we do things like .length or .push(), we're accessing variables or using class functions respectively!

  • Every type, Even primitive types, stem from one "class" (not entirely true) called Object, which has a wide variety of predefined properties and methods.

85

86 of 106

Object: Mother of all data types

  • Objects are kind of like dicts in Python, with key-value pairs holding all the data. Let's see the syntax here!

  • As you can see, you can declare the "shape" of the object with the key on the left, and you can specify its value on the right! And to access values within your object, you simply can call the key of it.

86

87 of 106

Object

  • Object can also take objects or other data structures as values!

87

88 of 106

Objects: Access

  • Access properties using "dot notation":

  • Or using "bracket notation" (like arrays):

  • Non-existent properties will return undefined:

  • Properties can also be accessed with variable keys

88

89 of 106

Changing Objects

  • Use dot or bracket notation with the assignment operator to change objects.
  • Change existing properties:

  • Or add new properties:

  • You can also delete properties:

89

90 of 106

Arrays of Objects�

  • Since arrays can hold any data type, they can also hold objects:

90

91 of 106

Objects as Arguments

  • Just like other data types, objects can be passed into functions:

91

92 of 106

Object Methods

  • Object properties can also be functions. Object functions are called "methods".

  • Call object methods using dot notation:

92

93 of 106

Question Break

2 min

94 of 106

The Reading List

Keep track of which books you read and which books you want to read!

  • Create an array of objects, where each object describes a book and has properties for the title (a string), author (a string), and alreadyRead (a boolean indicating if you read it yet).
  • Iterate through the array of books. For each book, log the book title and book author like so: "The Hobbit by J.R.R. Tolkien".
  • Now use an if/else statement to change the output depending on whether you read it yet or not. If you read it, log a string like 'You already read "The Hobbit" by J.R.R. Tolkien', and if not, log a string like 'You still need to read "The Lord of the Rings" by J.R.R. Tolkien.'

94

95 of 106

The Reading List: Solution

95

96 of 106

JS in action

97 of 106

Using JS to manipulate DOM

  • What is DOM? It is just a fancy word for our webpage. Link

97

98 of 106

Using JS to manipulate DOM

  • Let's focus in a little bit on this: document.getElementById(...) .... If you're looking for a direct example of the DOM in JS, here it is: the literal document object! This is the native JavaScript representation of the current webpage.

  • Next, we call getElementById() on it, with argument "button". This should be pretty self explanatory as to what it does, but let's take a look at what it actually looks like in our console:

98

99 of 106

Using JS to manipulate DOM

  • This is the crux of the DOM. Every tag in our document is representable as an object in native JavaScript (notice the properties classList or attributes?). We call each of these tags a node on our page. Why a node?

  • Going back to the tree structure of HTML documents, we can see where this is useful in JavaScript. Every tag is a node on our webpage, with a parent node and children nodes - notice the inclusion of the children field.

99

100 of 106

addEventListener(string eventName, function callBack)

  • Each node also has a variety of member functions that can be called. In our example, we call addEventListener.

  • This is an absolutely essential function to working with the DOM. If we want a particular function to be called each time an event occurs on the webpage with respect to a certain portion of said document, we can do so with this function.

100

101 of 106

addEventListener(string eventName, function callBack)

  • Each node also has a variety of member functions that can be called. In our example, we call addEventListener

  • This is an absolutely essential function to working with the DOM. If we want a particular function to be called each time an event occurs on the webpage with respect to a certain portion of said document, we can do so with this function.

101

102 of 106

Callback function

  • With that out of the way, let's talk about our callback function:������
  • We declare a variable to be the element on our page with ID "clicks", cast the contents of its HTML (the .innerHTML field) to a Number, then set its .innerHTML field to said number + 1. That is, it increments the numerical value of the innerHTML of clicks.

102

103 of 106

Question Break

2 min

104 of 106

Event Listener Exercises

25 min

105 of 106

Wrap Up

10 minutes

106 of 106

Before you leave...

  • Complete the Session Survey [2 min]
  • https://forms.gle/zoTZuy5wGjTuC5448
  • Next session is Thursday, 6pm - 9pm! We will cover UI/UX.
  • Assignment for those interested to get proficient in javascript:
    • Freecodecamp’s javascript challenge → Link
    • Project-based assignments → Link

106