Introduction

JavaScript is a programming language primarily used for web development, but it is a great introduction to programming in general. It allows for you to write instructions for a computer to follow, creating programs that can perform various tasks. In this learning activity, we will introduce you to programming concepts using JavaScript, starting with how to write and run simple programs. This will build a foundation for understanding the core principles of programming that can be applied in many different contexts.

What is JavaScript

JavaScript is commonly used to make websites interactive by responding to user actions such as clocks or keypresses. It runs directly in a web browser, making it easy to test and implement on any website. This ability to interact with users allows developers to manipulate web content, such as changing text, images, and videos on a page. In addition to enhancing user experience on the front end, JavaScript is a versatile language that extends beyond web development. It can also be used for backend programming and mobile app development, making it an essential tool in modern software development.

JavaScript Basics

Ok, so let’s actually write a "program". A simple program would be on that just says hello back, so let’s do that!

console.log("Hello")

Now when you run the code (click the play button in the upper right corner of the code block), we should see the output "Hello". So what’s actually going on then and how does this work? Well, that’s what the rest of this lesson will teach you! For now, try changing the code, re-running the program, and see what happens.

Syntax

To start your Javascript learning adventure, let’s take a look at the most basic program we can write: A program that prints out the words Hello World

console.log("Hello")

console.log() is one of the most frequently used operations in javascript, and it is used to print out information from our program. It prints whatever lies inside of the brackets. In our case, its the text Hello World. We wrap the text in quotes to indicate that it is text and not code, which in Javascript is called a string.

There are quite a few data types in javascript, but the 3 main ones are numbers, strings, and booleans.

Strings, like the Hello World above, are essentially lines of text, represented by the quotations. Single quotes or double quotes can be used to represent a string.

Numbers are, well, numbers. They can just be written as one would type out a number (ex: 5) Booleans are values that are always true or false. These are represented with the keywords true and false.

The last core concept to understand is code comments, denoted with a //. Comments are for writing things in our file without having our computer think its supposed to be code. Comments are often used to describe what certain code does or provide other background information on the code.

console.log("Hello World")
// Prints the text "Hello World"

Variables

In JavaScript, variables are used to store data that we want to re use or change in our program. You can think of a variable as a container or a box, which we can open and look inside whenever we want, or change what's in the box. There are 2 ways to declare a variable in Javascript: the let and const keywords. Variables can be used to hold numbers, strings (text) or boolean values (true/false)

This variable can be changed later on

let var1 = "Hello World"

This variable can not be changed later on due to the const keyword

const var2 = 3

If we want to use these variables later on in our code, we can simply write the variable and it will act as the value stored in it

let userName = "Alice"
const userAge = 20
let isMember = true

console.log(userName) // Outputs: "Alice"
console.log(userAge) // Outputs: 20
console.log(isMember) // Outputs: true

userName = "Bob"
console.log(userName) // Outputs "Bob"

userAge = 30 // not allowed since the variable is a const
             // try changing "userAge" to a "let" variable

Math

Doing math in javascript is just about as simple as doing math with a pen and paper. The four main operators in javascript are represented as follows

OperationSymbol
Addition+
Subtraction-
Multiplication*
Division/

Using the operators is also about as simple as one would imagine it would be

console.log(2 + 2) // This outputs "4"

In most cases, when we want to do math in our javascript programs, it will be with a dynamic value that the user inputs, represented by a variable. Applying what we just learned about variables, let's look at some examples using variables to both hold the numbers and store the result

const number1 = 10
const number2 = 4

const sum = number1 + number2
console.log(sum) // Outputs: 14 c

const difference = number1 - number2
console.log(difference) // Outputs: 6

const product = number1 * number2
console.log(product) // Outputs: 40

const quotient = number1 / number2
console.log(quotient) // Outputs: 2.5

There are two more operators that are quite common: ++ and --. These are shorthand for incrementing or decrementing a variable by 1, which is very useful when doing things like loops (not covered in this lesson)

The lines of code shown in the two examples below are equivalent

let total = 0
total = total + 1
console.log(total) // Outputs 1
let total = 0
total++
console.log(total) // Outputs 1

The same is true for the decrementation operator

let total = 10
total = total - 1
console.log(total) // Outputs 9
let total = 10
total--
console.log(total) // Outputs 9

One final thing to note is that all math done using JavaScript follows the standard order of operations, Where math in parentheses/brackets is executed first, then multiplication and division, then addition and subtraction.

Functions

When writing javascript code, you might find that you want to execute the same line or lines of code multiple times. Functions are a tool that allows us to write our code once, and then use it as many times as we want in our code.

To create a function we use the function keyword, followed by a name and 2 brackets, which hold any arguments for the function. The code to be executed in the function is wrapped in curly braces.

Let’s take a look at an example function and break it down piece by piece:

function squareNumber(num) {
	return num * num;
}

function: declaring that we are starting a function
squareNumber: the name of the function
(num): num is the variable that we are passing to the function, which we need to run the code inside of it return num * num: This is the line of code we actually want to execute. The return keyword sends the result of the function back to wherever it was called from.

To use a function, you simply call the name of the function, with the value you want to input for the argument in brackets. Expanding on the example above we have the following code:

function squareNumber(num) {
	return num * num
}

const result = squareNumber(4)
console.log(result) // Outputs 16
console.log(squareNumber(5)) // Outputs 25

Functions can be extremely useful to help organize code, and shorten the length of your code by saving yourself from repeating. Functions can also take any number of arguments (including 0), and do not have a limit to the # of lines of code you can put in them.

Example Program

Combining variables, math, and functions lets you start building useful programs. The following will calculate both the area and circumference of a circle given a radius:

const pi = 3.14

function calculateCircleArea(radius) {
	return pi * radius * radius
}

function calculateCircleCircumference(radius) {
	return 2 * pi * radius
}

function printDataForCircle(radius) {
	const area = calculateCircleArea(radius)
	const circumference = calculateCircleCircumference(radius)

	console.log("For a circle with radius:")
	console.log(radius)
	console.log("Area:")
	console.log(area)
	console.log("Circumference:")
	console.log(circumference)
	console.log("")
}

printDataForCircle(1)
printDataForCircle(2)
printDataForCircle(4)

Notice that because of the use of functions, to calculate the area and circumference of a circle with radius = 11, only one more line of code is required:

printDataForCircle(11)

Try editing or adding more functionality to this program!

Exercise

Now that you’re familiar with the basics of programming in JavaScript, it’s time for you to try writing your first larger program. Your task is given a temperature in celsius, convert it to both Fahrenheit and Kelvin and then use console.log to output your answer. Remember to use variables, math, and functions in your solution. Good luck!

// Convert this temperature into Fahrenheit and Kelvin
const temperatureInCelsius = 27

// Now write the rest of your code below here…

Advanced

Now it's time to start working on more advanced concepts like arrays, control flow, and loops. Here's a quick example of what's to come:

grades = [72, 89, 41, 97, 85]

for (let i = 0; i < grades.length; i++) {
    let grade = grades[i]

    if (grade >= 80) {
        console.log(grade)
    }
}

Arrays

An array in Javascript is a collection of items that are all stored in a single variable, very similar to a list. Arrays can hold any type of data, including strings numbers, or even other arrays. An array is defined using square brackets [], with a comma in between each value in the array.

const fruits =["apple", "banana", "orange"]

To access values inside of an array, you can use their index, or their position in the array. In JavaScript (and nearly all programming languages), indexing for arrays starts at 0. You can see how this works in the example below:

console.log(fruits[0]) // Outputs: "apple"
console.log(fruits[1]) // Outputs: "banana"
console.log(fruits[2]) // Outputs: "orange"

Arrays, like other variables, can also be edited. You can change the element at any array just like how you would update a regular variable, or you can add to and delete elements from the end of the array with the push() and pop() functions

fruits[1] = "blueberry" // Replace "banana" with "blueberry"
console.log(fruits) // Outputs: ["apple", "blueberry", "orange"]

fruits.push("pear") // Adds "pear" to the end of the array
console.log(fruits) // Outputs: ["apple", "blueberry", "orange", "pear"]

fruits.pop() // Removes the last element ("pear")
console.log(fruits) // Outputs: ["apple", "blueberry", "orange"]

Arrays are incredibly useful in JavaScript as they allow us to store collections of data efficiently, rather than having to store every piece of data in its own variable. They’re particularly useful when used with loops, which are covered in the following section.

Control Flow

The if and else keywords are some of the most useful in Javascript, as they allow our program to have conditional logic. They let our program do different things based on the value of an expression, which is often checking the value of a variable. To create an if statement, you start with the keyword if, followed by brackets () that surround the condition that you’re checking is true, followed by curly brackets {} with the code to be executed inside of them. Optionally, you can have an else following the curly brackets for the if statement, and the code in the else block will execute if the condition is false.

const age = 18

if (age >= 18) {
	console.log("You are an adult")
} else {
	console.log("You are a minor")
}

When writing if statements, we need to be able to write conditional statements that evaluate to true or false, as seen in the example above. The common operators are shown in the table below (with the true or false coming from the assumption that let x = 10)

OperatorDescriptionExample
===Equalsx === 10 (true)
!==Not equalsx !== 10 (false)
>Greater thanx > 10 (false)
<Less thanx < 10 (false)
>=Greater than or equal tox >= 10 (true)
<=Less than or equal tox <= 10 (true)

Loops

Loops are another of the most fundamental concepts in javascript programming. A very common scenario when programming is needing to execute the same line or lines of code numerous times. Rather than typing the same code out repeatedly, we can use a loop to execute the same code multiple times. There are 2 main types of loops, for and while loops. For loops will execute their code a specific amount of times, whereas while loops will execute their code until their specified condition is false.

Let’s take a look at a for loop first and break down its parts:

for (let i = 0; i < 10; i++) {
    console.log(i)
}

The for loop has 3 parts: Initialization (let i = 1): Sets the starting point for the loop Condition (i < 10): Determines how many times the loop runs Increment (i++): Updates the counter after each loop

For loops can be particularly useful when looking at arrays. If we wanted to print out each variable in an array, we could do so as follows using a loop:

const fruits= ["apple", "banana", "orange"]
for(let i = 0; i < array.length; i++) {
    console.log(fruits[i])
}

The second kind of loop is a while loop. While loops are similar to for loops except they only have a condition in their brackets, and the incrementation needs to be done within the code in the loop. It’s important to always include the incrementation step in the loop, as its easily possible to get stuck with a program repeating forever if you forgot it.

let count = 0

while (count < 10) {
    console.log(count)
    count++
}

Recap Quiz

Advanced Program

Lets revisit our previous example and use loops to print data for multiple circles at the same time

const pi = 3.14

function calculateCircleArea(radius) {
	return pi * radius * radius
}

function calculateCircleCircumference(radius) {
	return 2 * pi * radius
}

function printDataForCircle(radius) {
	if(radius < 0) {
        console.log("radius cannot be negative");
        console.log("");
        return;
    }

	const area = calculateCircleArea(radius)
	const circumference = calculateCircleCircumference(radius)

	console.log("For a circle with radius:")
	console.log(radius)

	console.log("Area:")
	console.log(area)

	console.log("Circumference:")
	console.log(circumference)

	console.log("")
}

const radii = [-1, 1, 2, 4, 8, 16];

for (let i = 0; i < radii.length; i++) {
	printDataForCircle(radii[i])
}

Project

For your final project, your task is to create a program that can convert an array of weekly temperatures in celsius to an array of temperatures in fahrenheit. If you will need to wear a jacket on any of the days (if the temperature is below 50 degrees fahrenheit), your program should also print out a message saying "You might need to wear a jacket!"). Make sure that your program only outputs this once, even if there’s multiple cold days. Try and apply as many of the concepts that we learned about as you can in your solution (hint: It might be useful to turn your code from the previous exercise into a function)

let temperatures = [-10, 0, 10, 20, 100];

function convertTemperatures(temperatures) {
	let needJacket = false
	// Write your code here
	//…
	// console.log() your answer when you’re finished
}

convertTemperatures(temperatures);

If your solution is correct, it should output:

[14, 32, 50, 68, 212]
You might need to wear a jacket!

Assignment #4 - Group H8

Interactive Learning Resource

Megan FraserMax ThomsonScott KenningKacey Friesen

University of VictoriaEDCI 335
Jess MitchellDec 2, 2024

Definition on chosen topic

This learning resource is crafted to provide a foundational understanding of programming through JavaScript, a versatile and widely-used language in web development. Effective learning in introductory programming necessitates an interactive and practical approach. Research indicates that students gain more from writing, testing, and revising code compared to merely reviewing lecture notes or memorizing information (Moraes et al., 2023). Engaging in hands-on activities is crucial for bridging the gap between theoretical concepts and their real-world applications, which in turn enhances learners' engagement and comprehension (Li et al., 2013). This module is designed to build learners' confidence in coding by showing that programming proficiency develops with practice. By engaging in structured, interactive coding exercises, learners will see the immediate results of their efforts, reinforcing the idea that programming is both a powerful and accessible skill with practical applications across a multitude of domains.

Learning Context and Learners:

This resource is designed for high school students (ages 15-18) with little or no prior programming experience. Basic computer literacy, including web browsing and typing is assumed. Their diverse interests will likely include a general curiosity about technology and problem solving. Their lifestyles involve significant interaction with technology through social media, online games, and mobile apps, providing a relevant context for learning JavaScript. The resource’s design is adaptable to varying levels of motivation and prior knowledge, recognizing that some students may prefer hands-on activities while others thrive in more structured settings.

Learning Theory: Constructivism

This learning resource utilizes constructivist learning theory, recognizing that learners actively build knowledge through experiences and interactions (Ertmer & Newby, 2013). This approach aligns well with the hands-on nature of programming. Constructivism views learning not as a passive absorption of facts, so instead of simply memorizing rules, you’ll learn by doing. Learners will experiment with interactive coding exercises, receive immediate feedback (right or wrong), and refine their understanding as they go. Project-based learning, culminating in a final project, provides evidence of learning while also providing empowerment by showing them they have the ability to create useful programs. The students’ final reflection will determine their understanding and insight on their coding experience, detailing their learning challenges faced and strategies used to overcome those challenges.

Learning Design: Project-Based/ Direct Instruction Learning

While emphasizing active learning, we recognize the importance of providing structure and guidance, particularly for novice programmers. This resource implements direct instruction to introduce fundamental concepts, giving learners a solid foundation. Clear explanations, examples and demonstrations will guide the students through the initial stages of learning (Carraba, C., & Farmer, A., 2018). Building on this foundation, the resource uses project-based learning. The learners will engage in increasingly complex interactive coding practice, culminating in a final project. This approach allows students to apply their knowledge meaningfully, seeing how concepts connect to create functional and practical applications. This approach is intended to facilitate problem solving skills by tackling challenges, while also expressing creativity through the final project. Taking the direct instruction and project-based approach will foster deeper engagement with the material and caters to the intended audience.

Designing for Inclusion (UDL and CAST Principles)

This resource is designed with a commitment to Universal Design for Learning (UDL), creating a flexible and supportive learning environment. Leveraging the CAST framework (Multiple Means of Representation, Action and Expression, and Engagement) it provides options and choices throughout the learning experience. Multiple means of representation are addressed through varied formats, combining clear and concise text with visuals, including syntax highlighting for enhanced code readability (CAST, 2024). Complex topics are chunked into manageable units with clear headings, supporting comprehension. Interactive exercises provide instruction, and learners can easily revisit prior material. Multiple means of action and expression are facilitated through interactive learning with editable code blocks, offering opportunities for experimentation, immediate feedback, and refinement. Learners demonstrate their understanding through coding, written reflections accompanying the final project, and visual representations of code functionality. Multiple means of engagement connect JavaScript to real-world applications, building learner confidence by addressing common coding misconceptions. Project choices cater to individual interests, promoting intrinsic motivation. Finally, upon completing the final project, reflection prompts encourage learners to analyze their learning progress, the challenges they encountered, and the strategies they employed.

Rationale for our Choice of Technology

This learning resource prioritizes accessibility and ease of use. Equipping learners with even basic coding skills empowers them to solve problems creatively, and engage critically with the technology that shapes our lives. Learners only need a device with a modern web browser, either Firefox or Chrome and internet access. While a laptop is recommended, a tablet or smartphone will also suffice, ensuring broad accessibility. The interactive learning environment utilizes MdBook, an open-source platform ideal for interactive content. This tailored MdBook includes integrated quizzes for self-assessment and a built-in JavaScript execution environment, allowing users to write, run, and test their code directly within the learning resource. This setup will maximize engagement by providing immediate feedback and a straightforward learning experience.

Learning Objectives

  1. Understand and explain basic programming concepts such as variables, data types, and syntax. Establishing a strong grasp of fundamental programming concepts is critical for learners to write and interpret simple code. It provides learners with the vocabulary and understanding needed to explore more complex topics.
  2. Write and debug a JavaScript program that uses conditional statements and loops. Conditional statements and loops are the backbone of logical flow in programming. Through this, learners practice breaking problems into smaller, testable pieces and learn iterative problem-solving.
  3. Apply JavaScript to solve real-world problems by creating interactive, user-driven programs. By focusing on practical applications, learners see how programming relates to everyday life. Creating interactive programs fosters engagement and motivation.
  4. Analyze and correct common coding errors to improve code readability and functionality. Debugging is a key skill in programming. It reinforces a constructive approach to learning, as mistakes are treated as opportunities to deepen understanding.
  5. Design and implement a final project that integrates multiple JavaScript concepts, such as variables, programming arithmetic, loops, functions, etc. A culminating project allows learners to synthesize what they've learned and demonstrate their skills. It fosters creativity, problem-solving, and confidence in applying programming knowledge.

These objectives are designed to:

  • Build foundational knowledge incrementally.
  • Provide opportunities for practice and immediate feedback.
  • Encourage active learning and problem-solving, consistent with the constructivist approach.
  • Connect abstract programming concepts to tangible outcomes.
  • Empower learners to see programming as an accessible and valuable skill.
  • Learners will demonstrate the ability to identify and correct poor coding practices, ensuring the code is clean, readable, and maintainable.
  • Learners will gain confidence in explaining their code.

References

Carrabba, C., & Farmer, A. (2018). The Impact of Project-based Learning and Direct Instruction on the Motivation and Engagement of Middle School Students. Language Teaching and Educational Research, 1(2), 163-174.

CAST. “Universal Design for Learning Guidelines.” CAST, 2024, udlguidelines.cast.org/. Accessed 2 Dec. 2024.

Ertmer, P. A., & Newby, T. J. (2013). Behaviorism, cognitivism, constructivism: Comparing critical features from an instructional design perspective. Performance Improvement Quarterly, 26(2), 43-71.

Li, T., Liu, W., Mao, X., & Zhou, H. (2013). Introduction to programming. Proceedings of the 18th ACM Conference on Innovation and Technology in Computer Science Education, 324–324. https://doi.org/10.1145/2462476.2462512

Moraes, M. C., Lionelle, A., Ghosh, S., & Folkestad, J. E. (2023). Teach students to study using quizzes, study behavior visualization, and reflection: A case study in an introduction to programming course. The 15th International Conference on Education Technology and Computers, 26, 409–415. https://doi.org/10.1145/3629296.3629362