Learning Objectives: JavaScript
Overview
Learners will be able to…
Create and print out the contents of the following
variable types:
string
number
boolean
object
Convert a repeating task into a loop statement
Differentiate between JavaScript and TypeScript
info
Limitations
This assignment will only provide an overview of select topics that are
relevant to the development of the final todo app.
Data Types & Variables
In JavaScript, data types are classifications of data that determine how
they can be used in a program. The three fundamental data types you need
to understand in this assignment are string, number, and boolean. Note
that these types of data are typically stored inside a variable.
String
A string is a sequence of characters, used to represent and manipulate text.
They are important because they allow you to work with and store textual
data in your programs, such as names, sentences, or any other text-based
information. Strings are typically created using double quotes (" ") or
single quotes (' ').
For example, I can store the string value Alice inside the variable name and
then print the content of that variable like this:
var name = "Alice";
[Link](name);
Go ahead and copy the code above into the text editor to your left (specified
as 1 in the image below). Then, click the TRY IT button to see what gets
printed to the console (specified as 2 in the image below).
Click here to enlarge the image above.
You should see that clicking the button produces a pop-out that reads Alice.
This means that the program ran and produced the output successfully.
challenge
Try this:
Change var name = "Alice" in the text editor to var name = "Bob",
then click on the TRY IT button.
Then, change Bob to Carol@123 and click TRY IT again.
You should see Bob printed to the console followed by Carol@123.
Number
The number data type is used to represent numeric values, including
integers (whole numbers) and floating-point numbers (decimals). They are
essential for performing calculations, comparisons, and other
mathematical operations in your code.
For example, I can have two variables with each storing a different number
(e.g. 10 and 15). Then print certain operations performed using those
variables:
var num1 = 10;
var num2 = 15;
[Link](num1 + num2);
If you tried the code above, you should see 25 printed to the console.
challenge
Try each of these with the TRY IT button:
Change the + operator in the text editor to the - operator.
Change the operator to /.
You should see -5 printed to the console followed by
0.6666666666666666. Note that / represents the division operator.
Boolean
A boolean data type represents true or false values, which are important
for controlling the flow of your program based on conditions. They are
often used in decision-making structures, such as loops and conditional
statements, to help determine the outcome of a particular situation.
Booleans will make more sense later on in the assignment. For now, just
remember that booleans can only be expressed as true or false.
var bool1 = true;
var bool2 = false;
[Link](bool1);
[Link](bool2);
The typeof Operator
There is a special kind of operator called typeof in JavaScript. If you ever
encounter any issue with figuring out the data type of a particular variable,
you can use typeof on that variable to determine what data type it is. Note
that typeof does not by default print to the console so you will need to
place typeof inside [Link]() if you want it to explicitly tell you what
the data type is. Try this example below:
var str = "Hello, world!";
var num = 42;
var bool = true;
[Link](typeof str);
[Link](typeof num);
[Link](typeof bool);
The console will explicitly tell you the data types of str, num, and bool
respectively (i.e. string, number, and boolean).
Objects
In JavaScript, objects are a fundamental data type that allows you to store
and organize complex data structures. They are important because they let
you group related data and functions together, making it easier to manage
and manipulate data in your programs. An object is essentially a collection
of key-value pairs called properties. The keys are usually strings, while the
values can be any data type, including other objects, functions, or any of
the fundamental data types covered in the previous lesson.
Creating Objects
There are several ways to create objects in JavaScript. One common way is
to use the object literal syntax, which uses curly braces { } to define the
object and its properties. Here’s an example:
var person = {
firstName: "Alice",
lastName: "Smith",
age: 18,
isStudent: true
};
[Link](person);
The example above creates an object called person with four key
properties: firstName, lastName, age, and isStudent. The values of these
properties are a mix of strings, numbers, and booleans. Notice how
printing an object results in their properties (separated by commas) being
outputted to the console.
challenge
Try this:
Add a new property email to the person object with the value
"[Link]@[Link]", then click on the TRY IT button. Be sure
to add a comma , before the email property!
You should see something like the following printed now:
{
firstName: 'Alice',
lastName: 'Smith',
age: 18,
isStudent: true,
email: '[Link]@[Link]'
}
Accessing Object Properties
Let’s say you didn’t want to have all of the properties of person printed at
once and only want to print a particular property. You can access certain
properties of an object using either the dot notation or the bracket notation.
Here is an example of both:
var person = {
firstName: "Alice",
lastName: "Smith",
age: 18,
isStudent: true,
email: "[Link]@[Link]"
};
[Link]([Link]); // dot notation
[Link](person["firstName"]); // bracket notation
Dot notation is more concise and easier to read, but bracket notation allows
you to use variables and property names that might not be valid identifiers
in dot notation.
challenge
Try each of these with the TRY IT button:
Use dot notation to print the age property of the person object.
Use bracket notation to print the isStudent property of the person
object.
Sample Solutions
[Link]([Link]);
[Link](person["isStudent"]);
You should see 18 and then true printed to the console.
Adding and Modifying Object Properties
You can add new properties or modify existing properties of an object
using the assignment operator (=). Here’s an example:
var person = {
firstName: "Alice",
lastName: "Smith",
age: 18,
isStudent: true,
email: "[Link]@[Link]"
};
[Link] = "[Link]@[Link]", // modifying an existing
property
[Link] = 2027; // adding a new property
[Link](person);
You should see the output as something like this:
{
firstName: 'Alice',
lastName: 'Smith',
age: 18,
isStudent: true,
email: '[Link]@[Link]',
class: 2027
}
Notice how the assignment operator = is able to both create a new property
as well as modify an existing one.
challenge
Try this with the TRY IT button:
Modify the email property of the person object to the value of
"asmith2027@[Link]", then print the email property using either
dot notation or bracket notation.
Sample Solutions
var person = {
firstName: "Alice",
lastName: "Smith",
age: 18,
isStudent: true,
email: "[Link]@[Link]"
};
[Link] = "asmith2027@[Link]";
[Link]([Link]);
You should see the updated email property printed to the console
as asmith2027@[Link].
Arrays
In JavaScript, arrays are a fundamental data type that allows you to store
and organize lists of values. They are important because they provide a
way to store and manage multiple values in a single variable, making it
easier to work with collections of data in your programs. An array can
store any data type, including other arrays, objects, or any of the
fundamental data types covered in previous lessons.
Creating Arrays
There are several ways to create arrays in JavaScript. The most common
way is to use the array literal syntax, which uses square brackets [ ] to
define the array and its elements (or values). Here’s an example:
var fruits = ["apple", "banana", "orange"];
[Link](fruits);
The example above creates an array called fruits with three elements, all
of which are strings and separated by commas ("apple", "banana",
"orange").
challenge
Try each of these with the TRY IT button:
Add a new element with the value of "grape" to the fruits array.
Add a new element with the value of 4 to the fruits array.
Add a new element with the value of true to the fruits array.
Sample Solutions
var fruits = ["apple", "banana", "orange", "grape"];
[Link](fruits);
var fruits = ["apple", "banana", "orange", "grape", 4];
[Link](fruits);
var fruits = ["apple", "banana", "orange", "grape", 4,
true];
[Link](fruits);
You should see the updated fruits array with the new respective
elements as specified above in the following order:
[ 'apple', 'banana', 'orange',
'grape' ]
[ 'apple', 'banana', 'orange',
'grape', 4 ]
[ 'apple', 'banana', 'orange',
'grape', 4, true ]
Unlike some other programming languages, you are allowed to have mixed
data types within a JavaScript array (i.e. var fruits = ["apple",
"banana", "orange", "grape", 4, true]).
Accessing Array Elements
You can access the elements of an array using their index, which is a zero-
based integer value representing the position of the element in the array.
What this means is that the first element’s index in the array starts at 0. The
second element’s index is 1 and so on and so forth. Here’s an example:
var fruits = ["apple", "banana", "orange"];
[Link](fruits[0]); // Output: "apple" (the first element)
[Link](fruits[1]); // Output: "banana" (the second element)
Adding and Modifying Array Elements
You can add new elements or modify existing elements in an array using
the assignment operator (=) and the index of the element. Here’s an
example:
var fruits = ["apple", "banana", "orange"];
fruits[3] = "grape"; // Add a new element called grape to index
3
[Link](fruits);
fruits[1] = "pear"; // Modify the element at index 1 to pear
[Link](fruits);
challenge
Try this with the TRY IT button:
Given this array:
var fruits = ["apple", "banana", "orange"];
Add the following lines of code after the array above:
fruits[5] = "watermelon";
[Link](fruits);
You should see the following printed:
[ 'apple', 'banana', 'orange', <2 empty items>,
'watermelon' ]
Because index 5 is the 6th element in the array, the system
automatically fills in index 3 and 4 with empty items which is
why you see <2 empty items> printed as part of the array.
To modify empty array elements (or items), you can assign values to the
indices that have these empty elements. For example:
var fruits = ["apple", "banana", "orange"];
fruits[5] = "watermelon";
[Link](fruits);
fruits[4] = "pineapple";
[Link](fruits);
fruits[3] = "grape";
[Link](fruits);
The code above will add "pineapple" as the 5th element, and then add
"grape" as the 4th element. This will then complete the array so that it has
no empty elements.
The push() Method
If you are not concerned about where specific elements are added to an
array, you can make use of the push() method. This method will
automatically add an elements to the end of the array. For example:
var fruits = ["apple", "banana", "orange"];
[Link]("watermelon");
[Link](fruits);
[Link]("pineapple");
[Link](fruits);
[Link]("grape");
[Link](fruits);
The push() method first adds "watermelon" to the end of the array, then
adds "pineapple", and finally adds "grape". This causes "watermelon",
"pineapple", and "grape" to become the 4th, 5th, and 6th elements,
respectively.
Removing Array Elements
You can remove elements from an array using various methods. One
common method is splice(), which allows you to remove all elements
from a specific index onwards. Here’s an example:
var fruits = ["apple", "banana", "orange", "watermelon",
"pineapple", "grape"];
[Link](2); // Removes all elements starting at index 2
[Link](fruits);
To remove a certain number of elements, you can provide a second
numerical value within the splice() method separated by a comma. For
example:
var fruits = ["apple", "banana", "orange", "watermelon",
"pineapple", "grape"];
[Link](3, 2); // Removes 2 elements starting at index 3
[Link](fruits);
Loops
In JavaScript, loops are used to repeatedly execute a block of code as long
as a specified condition is true. They are essential in programming because
they allow you to perform repetitive tasks efficiently, reducing the amount
of code you need to write.
for Loops
A for loop is a common type of loop in JavaScript. It consists of three parts:
the initialization, the condition, and the final expression, separated by
semicolons. Here’s the syntax:
for (initialization; condition; final_expression) {
// code to be executed
}
The initialization part usually involves a variable that starts at 0. This
variable essentially becomes the starting point at which you want your
loop to start.
The condition part tells your code to continue your loop as long as this
condition is satisfied. This part is required in order for you loop to
determine when it needs to end.
If the condition is met, the code to be executed part will run. Note that
this part will only run if the specified condition is true.
Lastly, the final expression involves some manipulation to your
initialization variable. This step is often necessary to move your loop
forward and prevent it from getting “stuck.”
Here’s an example:
for (var i = 0; i < 5; i++) {
[Link](i);
}
You’ll notice that the console prints integers starting from 0 through 4
counting up by a value of 1 every time. Let’s break down how this
happened:
1. First, we initialized our variable i to the value of 0. We are telling the
system that we would like our loop to start at 0.
1. Next, the system takes a look at our condition, which we set to i < 5. This
condition will be assessed based on what value our variable i is currently
at. Because we started i at 0 and because 0 is indeed less than 5, the
condition is satisfied and the loop will continue.
1. Since the loop continued, the code to be execute part will run, which in
our case is the command [Link](i). This command will then print out
the first value 0.
1. The final expression is i++ which means take the variable i and add 1 to
it. Thus, i which was 0 will now becomes 1.
1. Steps 1 through 4 will then repeat, however, instead of starting at i = 0,
i will now take on the value of 1.
challenge
Try this with the TRY IT button:
Modify the for loop with the following criteria:
i will now start at 5
The condition is now i > 0
The final expression is now i--
Sample Solution
for (var i = 5; i > 0; i--) {
[Link](i);
}
You should see something like the reverse happens where we
start at 5 and count backwards to 1 like this:
5
4
3
2
1
while Loops
A while loop executes a block of code as long as a specified condition is
true. The syntax is as follows:
initialization;
while (condition) {
// code to be executed
final_expression;
}
Converting from a for loop to while loop or vice versa can be done pretty
easily. Just inject the initialization, condition, and final_expression parts
from the for loop into the while (or vice versa). Here’s an example of both
of these loops together:
for (var i = 0; i < 5; i++) {
[Link](i);
}
var i = 0;
while (i < 5) {
[Link](i);
i++;
}
Note that unlike a for loop where the three parts (initialization, condition,
and final_expression) are required. The only thing that is necessary for a
while loop to run is the ++condition++. Thus something like this will work
and will run continuously until it times out.
while (true) { // condition is required
[Link](true);
}
Conditionals
In JavaScript, conditional statements are used to make decisions based on
specific conditions, and execute different blocks of code based on the
outcomes of those conditions. They are important in programming because
they allow you to control the flow of your program, ensuring that certain
code only runs when specific conditions are met.
if Statement
An if statement is a basic type of conditional statement in JavaScript. It
checks if a specified condition is true, and if so, it will execute a block of
code. Here’s an example:
var x = 10;
if (x > 5) {
[Link]("x is greater than 5");
}
In the example above, the variable x is assigned the value 10. The if
statement checks if x > 5. Because the condition is true, the code inside the
block will execute and print “x is greater than 5” to the console.
challenge
Try each of these with the TRY IT button:
Change the value of x to 3 and observe the output.
Change the condition in the if statement to x < 5 and observe the
output.
Change the condition in the if statement to x === 3 and observe
the output.
Change the print statement to [Link]("x is equal to 3")
Expected Outputs
Command was successfully executed.
x is greater than 5
x is greater than 5
x is equal to 3
NOTE: If you encounter the output of Command was successfully
executed., it means the code was execute successfully, but nothing was
printed to the console. In the first task when 3 was assigned to x, the
condition failed so the print statement was not executed.
else Statement
An else statement is used in conjunction with an if statement. If the
condition specified in the if statement is not met, the code block following
the else statement will execute. Here’s an example:
var x = 3;
if (x > 5) {
[Link]("x is greater than 5");
} else {
[Link]("x is not greater than 5");
}
In the example above, the if statement checks if x > 5. Since x is 3, the
condition is false so the code inside the else block will execute. This is why
you see “x is not greater than 5” printed to the console.
else if Statement
An else if statement can be used to test multiple conditions in a sequence.
If the previous condition is false, the else if statement checks the next
condition. If none of the conditions are met, the code block following the
else statement will execute. Note that like an else statement, an else if
statement also requires an initial if statement. Here’s an example:
var x = 5;
if (x > 10) {
[Link]("x is greater than 10");
} else if (x > 5) {
[Link]("x is greater than 5");
} else if (x === 5) {
[Link]("x is equal to 5");
} else {
[Link]("x is less than 5");
}
In the example above, the if statement checks if x > 10. Since x is 5, the
condition is false, so the code moves to the next else if statement, which
checks if x > 5. This condition is also false, so the code moves to the next
else if statement, which checks if x === 5. This condition is true, so the
code inside the block will execute, printing “x is equal to 5” to the console.
challenge
Try each of these with the TRY IT button:
Change the value of x to 15 and observe the output.
Change the value of x to 7 and observe the output.
Change the value of x to 2 and observe the output.
Expected Outputs
x is greater than 10
x is greater than 5
x is less than 5
With if, else if, and else statements, you can create complex decision-
making structures in your code. It’s important to remember that once a
condition is met, the code inside the corresponding block will execute, and
the rest of the conditions will not be checked. This allows you to create
efficient and organized code that responds to various conditions in a
specific order.
Functions
In JavaScript, various built-in functions help you manipulate and process
data more efficiently. You were already introduced to how useful functions
are back in the “Arrays” lesson when the push() method was covered.
push() is actually a built-in function. In JavaScript, the terms “methods”
and “functions” are often used interchangeably. In this lesson, we will
cover three additional functions: trim(), indexOf(), and map().
trim() Function
The trim() function is used to remove whitespace from both the beginning
and the end of a string. Here’s an example:
var str = " Hello, World! ";
var trimmedStr = [Link]();
[Link](trimmedStr);
In the example above, the variable str contains a string with extra
whitespace at the beginning and end. The trim() function removes this
whitespace, and the result is assigned to the variable trimmedStr. When you
print trimmedStr, you’ll see the output: “Hello, World!” without the extra
whitespace.
indexOf() Function
The indexOf() function is used to find the position of the first occurrence of
a specified value in a string or an array. If the value is not found, it returns
-1. Here’s an example:
var str = "Hello, World!";
var position = [Link]("World");
[Link](position);
In the example above, the variable str contains the string "Hello, World!".
The indexOf() function is used to find the position of the substring "World"
within str. The result is assigned to the variable position. When you print
position, you’ll see the output: 7, which is the starting index of the
substring "World" in the given string. Recall that indices start at 0, not at 1.
challenge
Try each of these with the TRY IT button:
Change the specified value in the indexOf() function to 'Z', a value
that does not exist in the string, and observe the output.
Change the specified value in the indexOf() function to 'H', a value
that occurs earlier in the string, and observe the output.
Expected Outputs
-1
map() Function
The map() function is used to create a new array by calling a specified
function on each element of an existing array. Here’s an example:
var numbers = [1, 2, 3, 4, 5];
var doubledNumbers = [Link](function (num) {
return num * 2;
});
[Link](doubledNumbers);
In the example above, the variable numbers contains an array of numbers.
The map() function is used to create a new array called doubledNumbers by
calling an anonymous function on each element of the numbers array. The
anonymous function doubles each number, and the new array will contain
the doubled values. When you print doubledNumbers, you’ll see the output:
[2, 4, 6, 8, 10].
challenge
Try each of these with the TRY IT button:
Change the anonymous function inside the map() function to
square each number and observe the output.
Change the anonymous function inside the map() function to add a
fixed value of 10 to each number and observe the output.
Expected Outputs
[1, 4, 9, 16, 25]
[11, 12, 13, 14, 15]
Sample Solutions
var numbers = [1, 2, 3, 4, 5];
var doubledNumbers = [Link](function (num) {
return num * num;
});
[Link](doubledNumbers);
var numbers = [1, 2, 3, 4, 5];
var doubledNumbers = [Link](function (num) {
return num + 10;
});
[Link](doubledNumbers);
These built-in functions, trim(), indexOf(), and map(), are valuable tools
when working with strings and arrays in JavaScript. They can help you
process and manipulate data more effectively, leading to cleaner and more
efficient code.
TypeScript
TypeScript is a programming language that is a superset of JavaScript. It
provides optional static typing, classes, and interfaces, making it a
powerful tool for building large-scale applications. In this lesson, we will
cover the basics of TypeScript, including types, interfaces, and classes.
Types
TypeScript has built-in support for several basic types, including number,
string, boolean, void, and null. You can also create custom types using the
type keyword or using interfaces.
Here’s an example of declaring a variable with a type:
let num: number = 5;
let str: string = "Hello, World!";
let bool: boolean = true;
let nul: null = null;
let u: undefined = undefined;
[Link](num, str, bool, nul, u);
In the example above, we’ve declared several variables with different
types. TypeScript will throw an error if you try to assign a value of the
wrong type to one of these variables. For example, try this modified code:
let num: number = 5;
let str: string = 10; // a number is assigned to a string
variable
let bool: boolean = true;
let nul: null = null;
let u: undefined = undefined;
[Link](num, str, bool, nul, u);
And an error message error TS2322: Type 'number' is not assignable to
type 'string'. will appear.
Interfaces
Interfaces are a way to define a structure for an object in TypeScript. They
allow you to specify the properties and their types that an object must
have. Here’s an example:
interface Person {
name: string;
age: number;
email?: string;
}
let person: Person = {
name: "John",
age: 30,
email: "john@[Link]",
};
[Link](person);
In the example above, we’ve defined an interface called Person, which
requires two properties: name of type string, and age of type number. We’ve
also added an optional property (denoted with the ? character), email,
which is of type string.
We then declared a variable called person of type Person and assigned an
object to it that satisfies the Person interface. The email property is
optional, so it’s okay to leave it out.
challenge
Try each of these with the TRY IT button:
Remove the line of code that reads email: "john@[Link]",
and observe the output.
Remove the line of code that reads age: 30, and observe the
output.
Expected Outputs
{ name: 'John', age: 30 }
error TS2741: Property 'age' is
missing in type '{ name: string; }'
but required in type 'Person'.
Classes
Classes are a way to define a blueprint for creating objects in TypeScript.
They allow you to define properties and methods that an object of that class
should have. Here’s an example:
class Animal {
name: string;
constructor(name: string) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a noise.`);
}
}
let dog = new Animal("Dog");
[Link]();
In the example above, we’ve defined a class called Animal with a
constructor that takes a name parameter and sets it as the name property of
the object. We’ve also defined a speak() method that logs a message to the
console.
We then created an instance of the Animal class called dog and called the
speak() method on it, which logs “Dog makes a noise.” to the console.
Classes can also inherit properties and methods from other classes using
the extends keyword, but we will not cover that in this lesson.
Conclusion
TypeScript is a powerful tool that provides static typing, interfaces, and
classes to help you build large-scale applications with more confidence and
efficiency. Note, however, that since our todo application is not a large-
scale application, we’ve only covered just the basics of TypeScript. For
more information of TypeScript, please visit:
[Link]