1 of 69

16. Introduction to JavaScript

MSER 521�Fall 2025

1

2 of 69

Outline

  1. Data Types
  2. Variables
  3. Operators
  4. Functions
  5. Selector Functions
  6. Events

2

3 of 69

Outline

  • Data Types
  • Variables
  • Operators
  • Functions
  • Selector Functions
  • Events

3

4 of 69

JavaScript Data Types

5 most important types in JavaScript:

4

number

For numbers of any kind: integer or floating-point

1.4, 33, 99999999

string

For strings (text). A string may have one or more characters, there’s no separate single-character type

‘hello world!’

boolean

for true/false.

true, false

null

for unknown values – has a single value null

null

object

for more complex data structures.

{ name: ‘ralph’, species: ‘dog’ }

5 of 69

Why do data types matter?

Each data type has its own abilities. For instance:

  • numbers are good for mathematical calculations
  • strings are good for doing text manipulations, e.g.:
    • convert to lowercase
    • check if a word is in a sentence
    • calculate the number of characters
  • booleans are good for figuring out whether to execute a code block (for conditional statements a and loops).
  • objects are good for grouping related data and/or functions together

5

6 of 69

Why do data types matter?

Try executing these two statements in the console and check out what’s different:

"2" + "2"

2 + 2

Takeaway: different data types have different powers

  • Numbers are good for doing math
  • Strings have functionality that allows you to format / manipulate text:
    • e.g., "hello".toUpperCase();
  • Booleans are good for logic (we’ll get into that more soon)!

6

7 of 69

Figuring out what data type you have

typeof 'hello world!';

typeof true;

typeof false;

typeof null;

typeof undefined;

typeof 23.4;

typeof 4500;

typeof [1, 3, 4, 6];

typeof { name: 'Lester', species: 'dog', age: 15};

7

js-introductory-exercises/00-building-blocks/data-types.js

8 of 69

Functions that convert between data types

// String(), Number(), Boolean()

console.log(Number('123')); // convert a string to a number

console.log(Boolean('true')); // convert a string to a boolean

console.log(String(123)); // convert a number to string

8

js-introductory-exercises/00-building-blocks/data-types.js

9 of 69

Takeaway

It’s important to know what data type you have in �order produce the result you want

9

10 of 69

Outline

  • Data Types
  • Variables
  • Operators
  • Functions
  • Selector Functions
  • Events

10

11 of 69

Variables

Used for temporary data storage and making things easier to read. Like ‘scratch paper.’ Consider the following code. Visualize it

// copy this code and run it in your browser console:

let x = 1;

let y = 6;

let z = 4;

x = 2;

z = x + y;

x = 4;

z = z + x;

console.log(x);

console.log(y);

console.log(z);

11

js-introductory-exercises/00-building-blocks/variables.js

12 of 69

Variables

  1. Variables are containers for storing and / or referencing data
  2. You assign values to variables using the assignment operator (equal sign)

=

12

13 of 69

Naming Variables: Case Sensitivity

JavaScript is case-sensitive.

let a = 3;

let A = 33;

console.log(a);

console.log(A);

13

14 of 69

Naming Variables

Although JavaScript doesn’t care what you name your variables (beyond the rules specified in the previous slide), there are some conventions that most people follow:�

  1. Ensure your variable names are mnemonic
  2. “camelCase” for functions and variable names
    1. let firstName = 'Erica';
    2. let lastName = 'Hernandez';
  3. Hyphens for file names: hello-world.js

14

15 of 69

Naming Variables: Camelcase

Functions

function divideTwoNums(num, denom) {� return num / denom;�}

function moveAvatarLeft(dog) {� dog.x -= 1;� dog.redraw();�}

Variables

let timeLeftTilEndOfClass = 35;

let firstName = 'Jazmin';

let lastName = 'Soltani';

Examples of camelcase variables and functions:

15

16 of 69

Naming Variables: Mnemonic

let x = 65;

let y = 3;�let z = x * y;�console.log(z);

let rate = 65;�let time = 3;�let distance = rate * time;�console.log(distance);

Which program is easier to read and reason about?

16

17 of 69

Naming Variables: Mnemonic

let x = 65;�let y = 3;�let z = x * x;�console.log(z);

let rate = 65;�let time = 3;�let distance = rate * rate;�console.log(distance);

Which program is easier to detect errors?

17

18 of 69

Variables

Turn the following statement into a sentence:

�let speed = 65; �

Create a new container called speed and put the number 65 into it

- or -

Create a new container called speed and assign the number 65 to it

18

19 of 69

Declaring versus assigning

In JavaScript, you need to declare your variables before you assign values to them. This can either be done all on one line...

let a = 3; // declares and assigns the value 3 to the variable “a”

or in two steps...

let a; // declares the variable “a” (allocates space in memory)

a = 3; // assigns the value 3 to the variable a

visualize it

19

20 of 69

Declaration keywords

In JavaScript, there are three keywords for declaring variables: let, const, and var

  • letMeans that the variable may be reassigned.
  • const�Means that the variable won't be reassigned. It’s immutable. Used in cases where you declare and assign once, but don’t change it afterwards.
  • var 🙁Avoid if possible. Old way to do things prior to ES6.

20

21 of 69

const and let demo (console)

21

variables.js

22 of 69

Outline

  • Data Types
  • Variables
  • Operators
  • Functions
  • Selector Functions
  • Events

22

23 of 69

Constants ~ Values

  • Constants are expressions that are already in their most “reduced” form
  • Constants do not need to be further evaluated�

3

2.5

‘Hello World’

true

23

24 of 69

Operators ~ a way to perform a simple computation

Operators are a type of expression that needs to be evaluated:

2 + 1 // expression that evaluates to 3

5 / 2 // expression that evaluates to 2.5

'Hello ' + 'World' // expression that evaluates to 'Hello World'

2 + 1 === 3 // expression that evaluates to true

The browser (interpreter) will evaluate these expressions until the result is a constant.

24

25 of 69

Example 1: Evaluate this expression (operator)

25

4 * 6

26 of 69

Example 1: Evaluate this expression (operator)

26

4 * 6

operand�(constant)

operand�(constant)

operator

27 of 69

Example 1: Evaluate this expression (operator)

27

4 * 6

4

operand�(constant)

6

operand�(constant)

*

operator

28 of 69

Example 1: Evaluate this expression (operator)

28

4 * 6

4

operand�(constant)

6

operand�(constant)

*

operator

24

29 of 69

Arithmetic Operators

29

+

Addition

Adds values on either side of the operator

-

Subtraction

Subtracts right hand operand from left hand operand

*

Multiplication

Multiplies values on either side of the operator

/

Division

Divides left hand operand by right hand operand

**

Exponent

Performs exponential (power) calculation on operators

%

Modulus

Divides left hand operand by right hand operand; returns remainder

++

Increment

Adds 1 to the number

--

Decrement

Subtracts 1 from the number

30 of 69

Operator Precedence

Python evaluates expressions as is done in mathematics (PEMDAS). After precedence rules, expressions are evaluated left to right.

30

1

()

Parenthesis

2

**

Exponentiation

3

*, /, %

Multiplication, division, remainder

4

+, -

Addition, subtraction

31 of 69

Order of Operations

let result = 16 - 2 * 5 / 3 + 1;

31

32 of 69

Order of Operations

let result = 16 - 2 * 5 / 3 + 1;

32

33 of 69

Order of Operations

let result = 16 - 2 * 5 / 3 + 1;

16 - 10 / 3 + 1;

33

34 of 69

Order of Operations

let result = 16 - 2 * 5 / 3 + 1;

16 - 10 / 3 + 1;

16 - 3.33 + 1;

34

35 of 69

Order of Operations

let result = 16 - 2 * 5 / 3 + 1;

16 - 10 / 3 + 1;

16 - 3.333 + 1;

12.666 + 1;

35

36 of 69

Order of Operations

let result = 16 - 2 * 5 / 3 + 1;

16 - 10 / 3 + 1;

16 - 3.333 + 1;

12.666 + 1;

result = 13.666;

36

37 of 69

Outline

  • Data Types
  • Variables
  • Operators
  • Functions
  • Selector Functions
  • Events

37

38 of 69

Before we get into the formalisms of functions, let’s look at one first!

38

39 of 69

Question: What is stored in result1?

// function definition:�function multiply(num1, num2) {

return num1 * num2

}

// function call:

const result1 = multiply(2, 3);

const result2 = multiply(4, 3);

const result3 = multiply(-1, 7);

39

40 of 69

Some things to notice...

// function definition:function multiply(num1, num2) {

return num1 * num2

}

// function call:

const result1 = multiply(2, 3);

40

For this function invocation:

num1=2

num2=3

Parameters allow you to pass data into a function so that you perform the same calculations with different data.

41 of 69

Some things to notice...

// function definition:function multiply(num1, num2) {

return num1 * num2

}

// function call:

const result1 = multiply(2, 3);

41

For this function call, the value 6 is returned and stored in result1.

A return value allow you to send the result back to the caller.

42 of 69

Practice: What is stored in result2?

function multiply(num1, num2) {

return num1 * num2

}

const result1 = multiply(2, 3);

const result2 = multiply(4, 3);

42

For this function invocation:

num1=4

num2=3

43 of 69

Practice: What is stored in result3?

function multiply(num1, num2) {

return num1 * num2

}

const result1 = multiply(2, 3);

const result2 = multiply(4, 3);

const result3 = multiply(result1, result2);

43

For this function invocation:

num1=6

num2=12

44 of 69

Practice: What is stored in result4?

function multiply(num1, num2) {

return num1 * num2

}

const result1 = multiply(2, 3);

const result2 = multiply(4, 3);

const result3 = multiply(result1, result2);

const result4 = multiply(multiply(2, 3), multiply(2, 3));

44

Solve the innermost parentheses before you solve the outermost ones.

45 of 69

Where do function definitions come from?

  • Some functions are part of the core JavaScript language. For instance:
    • document.querySelector(...)
    • console.log(...)
  • Functions can also be written by somebody else. For instance, you can download a set of functions from a library (e.g., p5.js, React, Vue) to make certain things easier to do.
  • You can also make your own functions (like we did in the previous slides and all last week)!

45

46 of 69

6 Things to Know About Functions

  1. They provide a way to encapsulate, organize, and reuse code
  2. They are similar to operators (+ - * /), but more flexible.
    • Think of data like nouns (things) and functions and operators like verbs (actions): “Do something with these things!”
  3. Functions must be defined before you run them
  4. You run a function by “calling” or “invoking” it
  5. They can have inputs (parameters/arguments)
  6. They can have an output (a return value)

46

47 of 69

Example: Annual Bonus Function Definition

How do you teach your computer how to calculate a bonus for employees in the company?

function calculateBonus(salary, score) {

let result = salary * score / 100;

return result;

}

47

48 of 69

You run a function by “calling” or “invoking” it

// function definition:

function calculateBonus(salary, score) {

let result = salary * score / 100;

return result;

}

// function calls / invocations:

const bonus1 = calculateBonus(60000, 3);

const bonus2 = calculateBonus(200000, 2);

48

49 of 69

Function scope

  • Variables and parameters that are created within functions cannot be accessed outside of a function.
  • The only way to access information that was created from within a function is to return it.

49

50 of 69

Example: Which variables are out of scope?

const z = 5;

function doStuff(a, b) {

const c = 123;

const d = 456;

return a + b + c + d;

}

const result = doStuff(3, 4);

console.log(result);

console.log(z);

console.log(a);

console.log(b);

console.log(c);

console.log(d);

50

Note that a, b, c, and d are local variables that are NOT accessible outside of the function.

Only the return value can be accessed after the function finishes executing.

51 of 69

Outline

  • Data Types
  • Variables
  • Operators
  • Functions
  • Selector Functions
  • Events

51

52 of 69

Selectors

Recall from CSS: selectors are ways of targeting elements in a web page so that we can apply styles to them.

Remember these...

52

53 of 69

...

1 <body>

2 <div class=”title-bar”>

3 <h1>Welcome, Malik</h1>

4 <img id=”profilesrc=images/pic.png” />

5 <hr>

6 </div>

7 <div>Right

8 <ul>

9 <li>list item 1</li>

10 <li>list item 2</li>

11 <li>list item 3</li>

12 </ul>

13 </div>

14 </body>

...

body {

color: grey;

}

h1, li {

text-transform: uppercase;

display: inline-block;

color: #999999;

}

.title-bar {

padding: 5px;

background-color: #EEEEEE;

}

#profile {

width: 100px;

float: left;

margin-right: 20px;

}

53

54 of 69

...

1 <body>

2 <div class=”title-bar”>

3 <h1>Welcome, Malik</h1>

4 <img id=”profilesrc=images/pic.png” />

5 <hr>

6 </div>

7 <div>Right

8 <ul>

9 <li>list item 1</li>

10 <li>list item 2</li>

11 <li>list item 3</li>

12 </ul>

13 </div>

14 </body>

...

body {

color: grey;

}

h1, li {

text-transform: uppercase;

display: inline-block;

color: #999999;

}

.title-bar {

padding: 5px;

background-color: #EEEEEE;

}

#profile {

width: 100px;

float: left;

margin-right: 20px;

}

54

55 of 69

...

1 <body>

2 <div class=”title-bar”>

3 <h1>Welcome, Malik</h1>

4 <img id=”profilesrc=images/pic.png” />

5 <hr>

6 </div>

7 <div>Right

8 <ul>

9 <li>list item 1</li>

10 <li>list item 2</li>

11 <li>list item 3</li>

12 </ul>

13 </div>

14 </body>

...

body {

color: grey;

}�

h1, li {

text-transform: uppercase;

display: inline-block;

color: #999999;

}�

.title-bar {

padding: 5px;

background-color: #EEEEEE;

}

�#profile {

width: 100px;

float: left;

margin-right: 20px;

}

55

56 of 69

...

1 <body>

2 <div class=”title-bar”>

3 <h1>Welcome, Malik</h1>

4 <img id=”profilesrc=images/pic.png” />

5 <hr>

6 </div>

7 <div>Right

8 <ul>

9 <li>list item 1</li>

10 <li>list item 2</li>

11 <li>list item 3</li>

12 </ul>

13 </div>

14 </body>

...

body {

color: grey;

}

h1, li {

text-transform: uppercase;

display: inline-block;

color: #999999;

}

.title-bar {

padding: 5px;

background-color: #EEEEEE;

}

#profile {

width: 100px;

float: left;

margin-right: 20px;

}

56

57 of 69

And once you target an element, you can change it...

57

Style Properties

document.querySelector("<selector>").style.<property> = "<value>";

  • e.g., document.querySelector(".box").style.color = "hotpink";

Attributes

document.querySelector("<selector>").<attribute> = "<value>";

  • e.g., document.querySelector(".pic").src = "beach.jpg";

Inner HTML

document.querySelector("<selector>").innerHTML = "<value>";

  • e.g., document.querySelector(".container").innerHTML = `Hello, <strong>Walter</strong!`;

58 of 69

Outline

  • Roadmap
  • What is JavaScript?
  • Selectors & element targeting
  • DOM manipulation
  • Demos

58

59 of 69

Summary of the Process of DOM Manipulation

Step 1: Target an element using one of the selector methods.

Step 2: Specify what you want to change about the element.

59

60 of 69

Step 1: Element Targeting

To target an element, use the document.querySelector method.

Examples:

document.querySelector("#profile");

document.querySelector("div");

document.querySelector(".title-bar");

document.querySelector("body");

...

1 <body>

2 <div class=”title-bar”>

3 <h1>Welcome, Malik</h1>

4 <img id=”profilesrc=images/pic.png” />

5 <hr>

6 </div>

7 <div>Right

8 <ul>

9 <li>list item 1</li>

10 <li>list item 2</li>

11 <li>list item 3</li>

12 </ul>

13 </div>

14 </body>

...

60

61 of 69

Step 2: Specify what you want to change

Once you target an element, you can change the element’s…

  • attributes (e.g., class, href, src, alt)
  • style properties (e.g., width, height, borderRadius, backgroundColor)
  • Inner HTML (what goes inside of the element)

61

62 of 69

2a. Attribute Manipulation

Examples of attributes you can manipulate…

62

Attribute

Example

className

myElement.className = “panel";

innerHTML

myElement.innerHTML = “hi!";

src (for images)

myElement.src = “some_image_url”

href (for links)

myElement.href = “http://site.com”;

...

...

63 of 69

2b. Style Property Manipulation

These are but a few. You can set any style property using JavaScript

63

Property

Example

width

myElement.style.width = "200px";

height

myElement.style.height = "200px";

background color

myElement.style.backgroundColor = "hotpink";

border width

myElement.style.borderWidth = "5px";

padding

myElement.style.padding = "10px";

display

myElement.style.display = "none";

...

...

64 of 69

Let’s do some exercises using the �DOM Manipulation Tester

65 of 69

Footnote: Other Selection Methods

There are also other selection methods you can also use! But querySelector is the most versatile!

65

Method

Example

Returns

querySelector()

document.querySelector("#my_element")

document.querySelector("p")

document.querySelector(“.my-announcements")

single element

querySelectorAll()

document.querySelectorAll("p")

list of elements

getElementById()

document.getElementById("my_element")

single element

getElementsByTagName()

document.getElementsByTagName("div")

list of elements

getElementsByClassName()

document.getElementsByClassName(".panel")

list of elements

66 of 69

Outline

  • Data Types
  • Variables
  • Operators
  • Functions
  • Selector Functions
  • Events

66

67 of 69

Events

A browser event is a signal that something has happened in the web browser. Your browser allows you to attach functionality to different events in order to support interactive functionality. Examples of events include:

  • click
  • mouseover
  • mouseout
  • focus
  • drag

67

68 of 69

Event Handler Example

An event handler is a function that you attach to an event. Here is an example:

<button onclick="sayHello()">Say Hello</button>

When the user clicks the button, the browser will run the sayHello() event.

68

69 of 69

Practice Time

69