Here you’ll learn how to use objects, arrays and functions. In addition, you will learn about the most common built-in methods, and the difference between undefined, null and empty strings. And you’ll explore both error handling and defensive programming. After completing this module, you will be able to:
Learning Objectives
- Build and use objects, arrays, and functions
- List some common built-in methods on built-in objects
- Describe handling bugs and errors using try, catch, throw, and defensive programming
- Explain the difference between undefined, null, and empty strings
- Demonstrate how to write basic code using arrays, objects, and functions
- Arrarys, Objects and Functions
- Video: Functions
- Video: Storing data in arrays
- Reading: Building and calling functions
- Reading: Exercise: Practicing with functions
- Reading: Solution: Practicing with functions
- Video: Introduction to objects
- Reading: Object Literals and the Dot Notation
- Reading: Object Literals and the Brackets Notation
- Reading: Arrays are Objects
- Reading: Math object cheat sheet
- Video: Math object
- Video: A closer look at strings
- Reading: String cheat sheet
- Reading: Creating arrays and objects (solutions)
- Error Handling
- Video: Bugs and errors
- Video: Try catch blocks
- Reading: Syntax, logical and runtime errors
- Video: Undefined, null and empty values
- Reading: Exercise: Error prevention
- Reading: Solution: Error prevention
- Reading: Exercise: Defensive programming
- Reading: Solution: Defensive programming
- Practice Quiz: Knowledge check: Error handling
- Video: Module summary: The Building Blocks of a Program
- Quiz: Module quiz: The Building Blocks of a Program
Arrarys, Objects and Functions
Video: Functions
Key Points:
- Functions avoid code repetition (DRY principle) by grouping related actions under a name.
- They can be called (invoked) multiple times with different values.
- Declaration:
function functionName(parameter1, parameter2) { ... }
- Call:
functionName(argument1, argument2)
- Parameters: Placeholder values inside the function definition.
- Arguments: Actual values passed when calling the function.
- Benefits:
- Reusable code.
- Cleaner and more efficient code.
- Flexible with different values.
Examples:
- Adding two numbers (
addTwoNums(10, 20)
) - Any custom logic with input values.
Overall:
This text emphasizes the importance of functions in JavaScript for writing efficient and reusable code. It clearly explains function declaration, parameters, arguments, and their benefits.
Functions are like mini-programs within your code that perform specific tasks. They’re essential for organizing, reusing, and simplifying your code.
Here’s a breakdown of key concepts:
1. Function Declaration:
- Use the
function
keyword, followed by the function name, parentheses (which can hold parameters), and curly braces for the code block:
JavaScript
function greetUser(name) {
console.log("Hello, " + name + "!");
}
2. Function Call:
- To execute a function, “call” or “invoke” it by using its name followed by parentheses (which can hold arguments):
JavaScript
greetUser("Alice"); // Output: Hello, Alice!
3. Parameters:
- Placeholders for values that the function expects when called.
- Define them within the parentheses in the function declaration:
JavaScript
function calculateArea(length, width) {
return length * width;
}
4. Arguments:
- Actual values passed to the function when it’s called:
JavaScript
const roomArea = calculateArea(5, 4); // Output: 20
5. Return Values:
- Functions can optionally return a value using the
return
statement:
JavaScript
function multiplyNumbers(a, b) {
return a * b;
}
const product = multiplyNumbers(6, 7); // Output: 42
6. Examples of Common Uses:
- Performing calculations: JavaScript
function addNumbers(a, b) { return a + b; }
- Manipulating strings: JavaScript
function reverseString(str) { return str.split("").reverse().join(""); }
- Interacting with the browser: JavaScript
function displayAlert(message) { alert(message); }
- Creating reusable components: JavaScript
function createButton(text, color) { // Code to create a button element }
7. Benefits of Using Functions:
- Code organization and readability: Break down complex tasks into smaller, manageable units.
- Reusability: Write code once and use it multiple times with different inputs.
- Modularity: Test and debug functions independently.
- Abstraction: Hide implementation details, making code easier to understand and maintain.
Have you ever wondered how when you turn
on the dial or press a different button on your washing machine for a specific wash,
it just knows what to do. You select sports wash and
the machine runs a wash cycle at the same temperature every time
or you turn the dial to synthetics and the machine runs a wash for
the exact same length of time. Each time functions work just like this,
running the same set of stored instructions repeatedly without requiring
you to adjust the settings every time. Over the next few minutes you learn about
the advantages of using functions in JavaScript, you will learn how
functions are structured and how to declare a function in your
code with the use of parameters. Finally, you will discover how to call or invoke a function with your
code with the use of arguments. But first, what is a function and
what does it do? One of the basic principles of
programming can be summed with the acronym DRY in other
words don’t repeat yourself. And it’s thanks to functions
that you can avoid repetition. With functions you can take several
lines of code that performs a set of related actions and then group them
together under a single label. Then when you need to run the code
that you’ve saved, you just invoke or call the function. You can run the code as
many times as you want. For example,
suppose you want to add two numbers. The process could be as follows. First creates two variables a and b. And assign each a number value,
then create another variable c, which holds the value of a and
b added together. Finally output the value
of c to the console. This piece of code works and
adds two numbers together. But what if you want to execute
this code more than once? Well you can do this by placing this
block of code inside a function. You declare a function by typing
the keyword function, then space and then the name of the function. You can name the function
nearly anything you want. In this example it’s named
addTwoNums after the function name. Place a left and right parenthesis. Finally place a left and a right
curly brace to complete the function. The code to be executed will then
be placed in between the left and right curly braces. And this is known as
the body of the function. It’s important to remember that a function
declaration on its own doesn’t execute the code. It’s just specifying what
operations should be performed. Once the function is executed to run
the functions code you need to call or invoke the function and this is
achieved by typing the function named followed by the opening and
closing parenthesis. Instead of saying run a function
developers may say that they call a function or
invoke a function but don’t worry. All these terms mean the same
thing to execute the code inside the functions body. Next let’s explore another
major advantage of functions. The use of values. Did you notice how the add to numbs
example was just adding the numbers 10 and 20. These numbers are are chosen values for
this function but this is just one example of the use
of values with functions you can use any values you want take for example
the add to numbs function created earlier. The function accepted,
no arguments in other words, no parameters were defined while
variables can be used to produce results. There are limitations as variables a and
b have specific values and the function would always
give the same result. So let’s change this function to
make it more flexible to do this. You need to pass values to the function. These values are known as
function parameters and are placed inside the function definition. The values passed to the function
are called arguments. Let’s explore this a little
further now by setting a and b as parameters instead
of using variables. I can easily plug in any two numbers
that I want to add parameters are sort of like variable names. They allow us to set changeable
values on each function call. Functions with parameters can accept
any kind of value and result in clean. More efficient code building functions
this way allows you to write flexible functions that can be reused with various
values as many times as you need. For example by passing values as
arguments to our function, addTwoNums. We can call it as many times as we want
and as long as we send it to values, it will add them together and
output the result. In this lesson you learned about
functions in JavaScript first you created a function without parameters and assigned fixed values inside
the body of the function itself. Then you learned about function
parameters to pass values to functions. It’s important to remember that function
parameters act sort of like variable names. The actual values that these variables
will be assigned will come in the form of function arguments. At the time the function is invoked. You’re now familiar with the advantages of
using functions declaring a function with parameters and
calling a function with arguments. Working with functions is common
in day to day development and is one of the core skills a developer
needs to master as they help you write more efficient reusable code.
You are creating a function and write the following code:
function hello() {
console.log(“Hello world”);
}
hello();
Correct. In JavaScript, you can call a function by typing the function name followed by the open and close parentheses.
Video: Storing data in arrays
- Arrays in JavaScript allow for the storage and rearrangement of sequenced collections of items.
- Arrays are created using the array literal syntax, which is an opening and closing square bracket.
- Each item in an array is assigned a number starting from 0, which corresponds to its place in the sequence.
- These numbers can be used to access each item in the array.
- Arrays are useful for grouping related values and accessing them through their index numbers.
Storing Data in Arrays: Your Organized Data Containers
In JavaScript, arrays are essential for storing collections of data in an organized manner. Think of them like storage boxes with numbered compartments for your items.
Let’s explore how they work:
1. Creating Arrays:
- Use square brackets
[]
to create an empty array:
JavaScript
let myArray = [];
- Add elements directly within the brackets, separated by commas:
JavaScript
let fruits = ["apple", "banana", "orange"];
2. Accessing Elements:
- Each element has a unique index starting from 0:
JavaScript
console.log(fruits[0]); // Output: "apple" (first element)
console.log(fruits[2]); // Output: "orange" (third element)
3. Adding Elements:
push()
method adds elements to the end:
JavaScript
fruits.push("grape"); // fruits now contains ["apple", "banana", "orange", "grape"]
unshift()
method adds elements to the beginning:
JavaScript
fruits.unshift("mango"); // fruits now contains ["mango", "apple", "banana", "orange", "grape"]
4. Removing Elements:
pop()
method removes the last element:
JavaScript
fruits.pop(); // removes "grape"
shift()
method removes the first element:
JavaScript
fruits.shift(); // removes "mango"
5. Finding Element Length:
- Use the
length
property to get the number of elements:
JavaScript
console.log(fruits.length); // Output: 3
6. Looping Through Arrays:
- Use
for
loops to iterate over elements:
JavaScript
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
7. Other Useful Methods:
indexOf()
: Finds the index of a specific elementslice()
: Extracts a portion of an arraysplice()
: Adds or removes elements at a specific indexsort()
: Sorts elements alphabetically or numericallyreverse()
: Reverses the order of elements
Key Points to Remember:
- Arrays are ordered collections, meaning the elements have a specific sequence.
- Indexing starts from 0, not 1.
- Arrays can hold different data types (numbers, strings, even other arrays).
- They are mutable, meaning you can change their contents after creation.
Mastering arrays is a fundamental step in JavaScript programming. Use them to store, organize, and manipulate data effectively in your projects!
You probably know that freight trains are an important
means for moving cargo. But have you ever thought about the system that
keeps things running smoothly as changes are
made at every stop? Carriages are typically set
in a specific sequence, and each carriage may carry
different items or materials. Other carriages can
also be added or removed without disrupting
the rest of the order. Much like a freight train, JavaScript has a piece of
functionality that allows you to store and rearrange
sequenced collections of items. This is called an array. In this video, I’ll
guide you through how to build an array and
access its contents. I’ll also demonstrate
how JavaScript stores the contents of the array
and indexes its values. Let’s say that you
want to emulate a toy freight train
using JavaScript. On this train, each carriage
has a number painted on its site and is presented in
sequence, starting from 0. Using JavaScript, you’ll assign some
cargo to each carriage. For the first one, let’s input var carriage0 equals wheat. Great. Now when you inspect
the contents of carriage 0, you’ll get back the word wheat. You can use the same approach
to model your entire train. Let’s say you do
just that and end up with five variables
of different values. You’ve just built a train
with five carriages, each holding different cargo. Now let’s make things
interesting and introduce a second train. This one only has
two carriages with the number 0 and 1
painted on the sides. Seems pretty simple, right? Well, you can’t use
the variable names carriage0 and carriage1
because they’re already taken. You could use more
descriptive names, such as train2carriage0 and a train2carriage1 but
that feels a bit wordy. Another problem is that
you need to signal that these variables are a
collection belonging Train 2. But when written this way, JavaScript doesn’t
understand that. Luckily, we can fix this. To make JavaScript understand
that we will group a sequence of variables in a
collection, we use arrays. You can build an array using
the array literal syntax, which is an opening
square bracket followed by a closing one. The array is currently empty, but JavaScript now
understands that we would provide a
collection of items. Let’s assign that collection
to the Train 1 variable. Finally, let’s add
carriages to the train 1 array by typing in the item names with each
separated by a comma. Now we have a train. But what happened to the
carriage numbers? Not to worry. Behind the scenes, JavaScript
gives each item a number starting from 0 that corresponds to its
place in the sequence. You can then use these numbers
to access each carriage. For example, typing
train1 followed by 0, encased in brackets will access the value
inside carriage 0, which is wheat in this case. To summarize, arrays help us achieve several
things in JavaScript. Arrays signal that
the assigned values all belong to a group. These values are ordered
in a sequence and each one can be accessed through its index number
in that sequence. In this video, you
learned how to build an array in JavaScript. You also learned how JavaScript sequences array
items using an index value.
Reading: Building and calling functions
Reading
In this reading, you will learn how to build and call a function. The purpose of this reading is to provide you with an example of function declaration (build) and function invocation (call). In the next lesson you will be writing the code.
By the end of this reading you should be able to:
- Code simple functions that can accept an array and iterate through it
Let’s start with giving our function declaration a name:
function listArrayItems(arr) {
// ... code to be added ...
}
So, I’ve declared a listArrayItems function, and I’ve set it up to accept a single parameter, arr – which stands for an array.
Now, I’ll need to code a for loop to loop over an array.
As covered in previous lessons in this course, a for loop needs the following information:
1. the starting loop counter value as a temporary variable i
2. the exit condition (the maximum value of the loop counter variable i, above which the loop no longer runs)
3. how to update the value of i after each loop
Here’s the information I’ll use in this function declaration: 1. The loop’s starting counter will be 0. The reason for setting it to zero is due to the fact that arrays are also counted from zero.
This means that I’ll have a one-to-one mapping of the current value of the i variable at any given time, corresponding to the same index position of any item in the arr array 2.
The for loop’s exit condition is when the value of i is equal or greater than arr.length.
Since the arr.length counts the number of items in the array from one, and the array items are indexed from zero, this effectively means that as soon as i is equal to arr.length, the loop will finish and any other code after it will be run.
This practically means that the exit condition for this for loop will be i < arr.length returning false.
In other words, as long as i < arr.length is true, this for loop will continue to run. 3. To make sure that none of the items in the arr array are skipped, I have to increase the value of i by 1 after each loop.
Now that I know exactly how my for loop should behave, I can add it to my listArrayItems() function:
function listArrayItems(arr) {
for (var i = 0; i < arr.length; i++) {
// ... code pending here ...
}
}
Now all that I have left to decide is how I want to output each item from the received arr array.
It can be as simple as console logging the array item index of the current value of i:
function listArrayItems(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]) //display the array item where the index is euqal to i
}
}
If I now invoke the listArrayItems function, I can, for example, give it the following array of colors:
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink'];
listArrayItems(colors); //display all items in the array at once
The output will be:
red
orange
yellow
green
blue
purple
pink
I can update the output any way I like. For example, here are my arr items with a number in front of each item:
//function that takes an array as input and display all items of this array
function listArrayItems(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(i, arr[i])
}
}
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink'];
listArrayItems(colors);
Now the output of the above code will be as follows:
0 'red'
1 'orange'
2 'yellow'
3 'green'
4 'blue'
5 'purple'
6 'pink'
To start the count from one instead of zero, I can update my function declaration as follows:
function listArrayItems(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(i+1, arr[i])
}
}
Invoking the above, updated, function declaration on my colors array, will now result in the following output:
1 'red'
2 'orange'
3 'yellow'
4 'green'
5 'blue'
6 'purple'
7 'pink'
I can even add one or more conditions, such as:
function listArrayItems(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == 'red') {
console.log(i*100, "tomato!")
} else {
console.log(i*100, arr[i])
}
}
}
Now I’m adding control flow right inside my function, based on whether a specific array member matches a specific value – in this case the string “red”.
Invoking my newest updated version of the listArrayItems function on the colors array will now result in the following output:
0 'tomato!'
100 'orange'
200 'yellow'
300 'green'
400 'blue'
500 'purple'
600 'pink'
Reading: Exercise: Practicing with functions
Reading
Your task in this exercise is to code a function which will be able to take a word and locate the position of a chosen letter in that given word.
Task 1:
Write a function named letterFinder that accepts two parameters: word and match.
Task 2:
Code a ‘for’ loop inside the function’s body. The for loop’s counter should start at zero, increment by 1 on each iteration and exit when the counter variable’s value is equal to the length of the word parameter.
Task 3:
Add an if statement inside the for loop whose condition works as follows:
- Access each of the letters inside the passed in word using the counter variable, with word[i].
- Check if the current word[i] is equal to the value of match.
Task 4:
console.log the following inside the body of the if statement: console.log(‘Found the’, match, ‘at’, i).
Task 5:
Write the else condition. Here you’ll just console log the following: console.log(‘—No match found at’, i).
Task 6:
Call the letterFinder and pass it as its first argument as the string “test” and as its second argument, the string “t”.
Your output should be the following:
Found the t at 0
—No match found at 1
—No match found at 2
Found the t at 3
function letterFinder(word,match) {
for(var i = 0; i < word.length; i++) {
if(word[i] == match) {
console.log('Found the', match, 'at', i)
} else {
console.log('---No match found at', i)
}
}
}
letterFinder("test","t")
Found the t at 0
---No match found at 1
---No match found at 2
Found the t at 3
Reading: Solution: Practicing with functions
Reading
Task 1 solution:
// A function that accepts two parameters
function letterFinder(word, match) {
}
Task 2 solution:
function letterFinder(word, match) {
for(i = 0; i < word.length; i++) {
//this loop exists when i is equal to the length of the word
}
}
Task 3 solution:
function letterFinder(word, match) {
for(i = 0; i < word.length; i++) {
if(word[i] == match) {
//check if the current characater, word[i], is equal to the match
}
}
}
Task 4 solution:
function letterFinder(word, match) {
for(i = 0; i < word.length; i++) {
if(word[i] == match) {
//check if the current characater, word[i], is equal to the match
console.log('Found the', match, 'at', i)
}
}
}
Task 5 solution:
function letterFinder(word, match) {
for(i = 0; i < word.length; i++) {
if(word[i] == match) {
//check if the current characater, word[i], is equal to the match
console.log('Found the', match, 'at', i)
} else {
console.log('---No match found at', i)
}
}
}
Task 6 solution:
function letterFinder(word, match) {
for(var i = 0; i < word.length; i++) {
if(word[i] == match) {
//check if the current characater, word[i], is equal to the match
console.log('Found the', match, 'at', i)
} else {
console.log('---No match found at', i)
}
}
}
letterFinder("test", "t")
Video: Introduction to objects
Key Points:
- Objects group related data, improving code organization and understanding.
- Benefits: Shorter variable names, clear connection between properties, and code flexibility.
- Building Objects:
- Dot notation:
storeManager.{property}
assigns properties likemovementRange
. - Comma-delimited key-value pairs:
{key1: value1, key2: value2, ...}
within object literal.
- Dot notation:
- Object Updates: New properties can be added with dot notation or key-value pairs.
Example: Building a Store Manager and Assistant Manager object for your JavaScript cookie game.
Remember: Objects offer a powerful way to structure and manage your data in JavaScript, leading to cleaner and more maintainable code. Go forth and build your coding empire!
♀️ Welcome to JavaScript Objects: Your Essential Guide to Data Organization!
Ready to unlock the power of objects in JavaScript? Let’s dive in!
️ What are Objects?
- Think of objects as containers for related data. They’re like little filing cabinets, keeping information organized and easy to access.
- Each piece of data within an object is called a property, and it has a name (the key) and a value.
- Objects help you create more complex and meaningful structures, making your code more readable and maintainable.
** Why Use Objects?**
- Code clarity: Objects group related properties together, making your code easier to understand and reason about.
- Real-world modeling: They’re perfect for representing real-world entities like people, animals, cars, or even delicious cookies!
- Flexibility: You can easily add, remove, or modify properties as your code evolves.
️ Building Objects:
1. Object Literals:
JavaScript
let myObject = {}; // Empty object literal
let person = {
name: "Alice",
age: 30,
hobbies: ["coding", "reading", "baking"]
};
2. Constructor Function:
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
let myPerson = new Person("Bob", 25);
** Accessing Properties:**
- Use dot notation:
person.name
- Use square bracket notation:
person["age"]
(useful for dynamic property names)
** Modifying Objects:**
- Add new properties:
person.city = "New York";
- Change existing properties:
person.age = 31;
✨ Common Object Methods:
toString()
: Returns a string representation of the object.valueOf()
: Returns the primitive value of the object.
** Practice Examples:**
- Create objects to represent different cookies in a bakery, with properties like flavor, size, and price.
- Build a character object for a game, with properties like health, strength, and inventory.
** Remember:**
- Objects are fundamental building blocks in JavaScript.
- Mastering them is essential for writing clean, organized, and efficient code.
- Experiment, practice, and have fun exploring the world of objects!
Stay tuned for more object adventures! ️
You have created a “worker” character for your game and would like to assign it several traits. Which of the following best describes the benefits of creating an object for this purpose? Choose all that apply.
It enables you to use shorter property names.
That’s right! Objects tend to allow for shorter names.
All properties can be connected to the same object.
That’s right! Objects can be assigned multiple properties.
In programming, if you have groups of data that you
would like to relate, you can assign them to
something known as an object. In this video, I’ll help you to understand why we use
objects in JavaScript. I’ll also demonstrate
how to build objects using dot notation, as well as by specifying comma
delimited key-value pairs. Let’s say that you are
using JavaScript to build a game where the objective is to build your own cookie
selling business. Your game is turn-based and uses tiles for
characters to move, trade, and build their company. Your first task is to build
a store manager character. You need to set certain traits, so let’s call them with
JavaScript variables. We’ll set some numbers
for the movement range, social skills, street
smarts, and help. There. You’ve created
a store manager, but there are a few improvements that you could
make in your code. One issue is the long length
of the variable names. Another is that your code does
not explain to JavaScript that these variables are related and all describe
the same character. This is where objects come in. Using objects, we can resolve these pain
points by shortening our variable names and
getting JavaScript to understand that all those
variables are related. Let’s start by declaring the variable store manager
to which you assign an opening and a
closing curly brace This creates an empty
object literal. Next, instead of declaring individual variables
for the traits, you can add a dot
operator to each one, right after the
words store manager. Now, when you inspect the
store manager object, it recognizes these as
traits of the store manager. Here you have built a
store manager object using dot notation. Each trait is a
property of the object. Objects can be described
as collections of related properties
where each property is represented as
a key value pair. This means that what is normally a variable name
becomes a property key and what is normally a variable’s value becomes the property value
of the object. Objects can also be
built by listing the key value pairs inside
of the object literal, which specifies them as
comma delimited properties. To demonstrate, let’s build
a new character object. First, I declare the object name using var and then the object, for example, assistant manager. Then I simply input the
properties and values in-between curly braces with each property followed by a colon
and its value. Next, I separate each key
value pair by a comma. Lastly, I finish the declaration using a closed curly bracket. That’s it. I created
an object and assigned some values
to its properties. After an object is built, you can still update the object by adding
new properties to it. This can also be done
with dot notation. For the store manager object, you can add another
property called next achievement by
using dot notation. As before, you do
this by placing a dot operator between the
object name and the property. Then for the assistant
manager object, you can add a property
with the same name using dot notation,
and that’s it. Now your objects have new properties added
to the previous ones. In this video, you’ve
learned why objects are valuable tools in
JavaScript coding and how to build them using
dot notation and by specifying comma delimited
key value pairs. Perhaps you can
apply this knowledge towards creating the
next great gain.
Reading: Object Literals and the Dot Notation
Reading
By the end of this reading, you’ll be able to:
- Explain one of the three common ways to build objects ( using the object literal notation)
- Outline the common way to add new properties to objects (or update existing properties) using the dot notation
Object literals and the dot notation
One of the most common ways of building an object in JavaScript is using the object literal syntax: {}.
To be able to access this object literal, it is very common to assign it to a variable, such as:
var user = {}; //create an object
Now an object literal is assigned to the variable user, which means that the object it is bound to can be extended and manipulated in a myriad of ways.
Sometimes, an entire object can be immediately built, using the object literal syntax, by specifying the object’s properties, delimited as key-value pairs, using syntax that was already covered in an earlier lesson item in this lesson.
Here’s one such previously built object:
//creating an object with properties and their values
var assistantManager = {
rangeTilesPerTurn: 3,
socialSkills: 30,
streetSmarts: 30,
health: 40,
specialAbility: "young and ambitious",
greeting: "Let's make some money"
}
The beauty of this syntax is that it’s so easily readable.
It essentially consists of two steps:
1. Declaring a new variable and assigning an object literal to it – in other words, this: var assistantManager = {}
2. Assigning the values to each of the object’s keys, using the assignment operator, =
Notice that it’s very easy to build any kind of an object in JavaScript using this example syntax.
For example, here’s a table object:
var table = {
legs: 3,
color: "brown",
priceUSD: 100,
}
To access the table object, I can simply console log the entire object:
console.log(table);//display the object in the developer console
The returned value is the entire table object:
{legs: 3, color: 'brown', priceUSD: 100}
Additionally, I can console log any individual property, like this:
console.log(table.color); // 'brown'
Now that I have this “syntax recipe”, I can build any other object in a similar way:
var house = {
rooms: 3,
color: "brown",
priceUSD: 10000,
}
An alternative approach of building objects is to first save an empty object literal to a variable, then use the dot notation to declare new properties on the fly, and use the assignment operator to add values to those properties; for example:
var house2 = {};
house2.rooms = 4;
house2.color = "pink";
house2.priceUSD = 12345;
Additionally, nothing is preventing me from combining the two approaches. For example:
console.log(house); // {rooms: 3, color: "brown", priceUSD: 10000}
house.windows = 10;
console.log(house); // {rooms: 3, color: "brown", priceUSD: 10000, windows: 10}
This flexbility additionally means that I can update already existing properties, not just add new ones:
house.windows = 11;
console.log(house); // {rooms: 3, color: "brown", priceUSD: 10000, windows: 11}
Reading: Object Literals and the Brackets Notation
Reading
By the end of this reading, you’ll be able to:
- Explain how to build objects using the brackets notation
- Explain that with the brackets notation you can use the space character inside keys, since property keys are strings
- Explain that the keys inside the brackets notation are evaluated
Object literals and the brackets notation
There is an alternative syntax to the dot notation I used up until this point.
This alternative syntax is known as the brackets notation.
To understand how it works, it’s best to use an example, so I’ll go through the process of coding the house2 object again, in the same way that I did with the dot notation, only this time, I’ll use the brackets notation.
var house2 = {};
house2["rooms"] = 4;
house2['color']= "pink";
house2["priceUSD"] = 12345;
console.log(house2); // {rooms: 4, color: 'pink', priceUSD: 12345}
Note that using the brackets notation, I essentially just wrap each property’s key as a string, inside either the single or double quotes – just like with regular strings.
Then I wrap the entire property key into an opening and a closing square bracket.
That’s essentially all there is to it.
I can both access and update properties on objects using either the dot notation, or the brackets notation, or a combination of both, like in the following example:
var car = {};
car.color = "red";
car["color"] = "green";
car["speed"] = 200;
car.speed = 100;
console.log(car); // {color: "green", speed: 100}
For the time being, this is probably enough information on object creation.
Before I discuss the topic of arrays and objects, let me just give you another important piece of information about the brackets notation.
With the brackets notation, I can add space characters inside property names, like this:
car["number of doors"] = 4;
console.log(car); // {color: 'green', speed: 100, number of doors: 4}
Additionally, I can add numbers (as the string data type) as property keys:
car["2022"] = 1901;
console.log(car); // {2022: 1901, color: 'green', speed: 100, number of doors: 4}
However, doing this is discouraged, due to obvious reasons of having a property key as a number string not really conveying a lot of useful information.
Finally, there’s one really useful thing that bracket notation has but is not available in the dot notation: It can evaluate expressions.
To understand what that means, consider the following example:
var arrOfKeys = ['speed', 'altitude', 'color'];
var drone = {
speed: 100,
altitude: 200,
color: "red"
}
for (var i = 0; i < arrOfKeys.length; i++) {
console.log(drone[arrOfKeys[i]])
}
The above code will result in the following output:
100
200
red
Using the fact that brackets notation can evaluate expressions, I accessed the arrOfKeys[i] property on the drone object.
This value changed on each loop while the for loop was running.
Specifically, the first time it ran, it was evaluated like this:
- The value of i was 0
- The value of arrOfKeys[i] was arrOfKeys[0], which was “speed”
- Thus, drone[arrOfKeys[i]] was evaluated to drone[“speed”] which is equal to 100
This allowed me to loop over each of the values stored inside the drone object, based on each of its properties’ keys.
Reading: Arrays are Objects
Reading
By the end of this reading, you’ll be able to:
- Explain that arrays are objects, with their own built-in properties and methods
- Outline the common way to extend arrays using the push() method
- and explain how to trim the last member of an array using the pop() method
Arrays are objects
In JavaScript, arrays are objects. That means that arrays also have some built-in properties and methods.
One of the most commonly used built-in methods on arrays are the push() and the pop() methods.
To add new items to an array, I can use the push() method:
var fruits = [];
fruits.push("apple"); // ['apple']
fruits.push('pear'); // ['apple', 'pear']
To remove the last item from an array, I can use the pop() method:
fruits.pop();
console.log(fruits); // ['apple']
Tying into some earlier lessons in this course, I can now build a function that takes all its arguments and pushes them into an array, like this:
function arrayBuilder(one, two, three) {
var arr = [];
arr.push(one);
arr.push(two);
arr.push(three);
console.log(arr);
}
I can now call the arrayBuilder() function, for example, like this:
arrayBuilder('apple', 'pear', 'plum'); // ['apple', 'pear', 'plum']
Even better, I don’t have to console log the newly built array.
Instead, I can return it:
function arrayBuilder(one, two, three) {
var arr = [];
arr.push(one);
arr.push(two);
arr.push(three);
return arr;
}
Additionally, I can save this function call to a variable.
I can name it anything, but this time I’ll use the name: simpleArr.
var simpleArr = arrayBuilder('apple', 'pear', 'plum');
And now I can console log the values stored in simpleArr:
console.log(simpleArr); // ['apple','pear','plum']
Reading: Math object cheat sheet
Reading
JavaScript has handy built-in objects. One of these popular built-in objects is the Math object.
By the end of this reading, you’ll be able to:
- Outline the built-in properties and methods of the Math object
Number constants
Here are some of the built-in number constants that exist on the Math object:
- The PI number: Math.PI which is approximately 3.14159
- The Euler’s constant: Math.E which is approximately 2.718
- The natural logarithm of 2: Math.LN2 which is approximately 0.693
Rounding methods
These include:
- Math.ceil() – rounds up to the closest integer
- Math.floor() – rounds down to the closest integer
- Math.round() – rounds up to the closest integer if the decimal is .5 or above; otherwise, rounds down to the closest integer
- Math.trunc() – trims the decimal, leaving only the integer
Arithmetic and calculus methods
Here is a non-conclusive list of some common arithmetic and calculus methods that exist on the Math object:
- Math.pow(2,3) – calculates the number 2 to the power of 3, the result is 8
- Math.sqrt(16) – calculates the square root of 16, the result is 4
- Math.cbrt(8) – finds the cube root of 8, the result is 2
- Math.abs(-10) – returns the absolute value, the result is 10
- Logarithmic methods: Math.log(), Math.log2(), Math.log10()
- Return the minimum and maximum values of all the inputs: Math.min(9,8,7) returns 7, Math.max(9,8,7) returns 9.
- Trigonometric methods: Math.sin(), Math.cos(), Math.tan(), etc.
Video: Math object
Key points:
- Math object: Provides useful built-in mathematical methods in JavaScript.
- random() method:
- Generates a decimal number between 0 (inclusive) and 1 (exclusive).
- Can be multiplied to extend its range (e.g.,
Math.random() * 10
for 0-9.99).
- ceil() method:
- Rounds up a decimal number to the nearest integer.
Combining the methods:
- Generate a decimal between 0 and 9.99 using
Math.random() * 10
. - Round it up to an integer between 0 and 10 using
Math.ceil()
.
Example:
JavaScript
let decimal = Math.random() * 10;
let rounded = Math.ceil(decimal);
console.log(rounded); // Outputs a random integer between 0 and 10
Encouragement: The video encourages viewers to experiment with these methods in their own code for creative applications.
Introduction:
- Math object: A built-in object in JavaScript that provides various mathematical constants and functions.
- Accessing methods: Use the dot notation, e.g.,
Math.methodName()
. - No direct instantiation: You don’t create instances of Math like other objects.
Common Methods:
- Math.random(): Generates a random decimal number between 0 (inclusive) and 1 (exclusive).
- Example:
let randomNumber = Math.random();
- Example:
- Math.ceil(x): Rounds a number x up to the nearest integer.
- Example:
let roundedUp = Math.ceil(4.2); // Output: 5
- Example:
- Math.floor(x): Rounds a number x down to the nearest integer.
- Example:
let roundedDown = Math.floor(4.8); // Output: 4
- Example:
- Math.round(x): Rounds a number x to the nearest integer, with ties rounding to the nearest even integer.
- Example:
let rounded = Math.round(4.5); // Output: 4
- Example:
- Math.abs(x): Returns the absolute (positive) value of a number x.
- Example:
let absoluteValue = Math.abs(-5); // Output: 5
- Example:
- Math.max(x1, x2, …): Returns the largest of the given numbers.
- Example:
let largest = Math.max(3, 7, 2); // Output: 7
- Example:
- Math.min(x1, x2, …): Returns the smallest of the given numbers.
- Example:
let smallest = Math.min(5, 1, 9); // Output: 1
- Example:
- Math.pow(x, y): Returns x raised to the power of y.
- Example:
let squared = Math.pow(4, 2); // Output: 16
- Example:
- Math.sqrt(x): Returns the square root of a number x.
- Example:
let squareRoot = Math.sqrt(16); // Output: 4
- Example:
Constants:
- Math.PI: The mathematical constant pi (approximately 3.14159).
- Math.E: The mathematical constant e (approximately 2.71828).
Applying Math Methods:
- Generating random integers:
let randomInt = Math.floor(Math.random() * 10) + 1;
- Calculating distances:
let distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
- Finding angles:
let angle = Math.atan2(y2 - y1, x2 - x1);
Experimenting and Practicing:
- Try out different Math methods in your code to explore their capabilities.
- Use console.log() to print results and visualize outcomes.
- Refer to the MDN Web Docs for comprehensive documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
You have written the following code:
var myNum = Math.ceil(2.49); console.log(myNum);
When you run this code, what value will be returned? Select the correct answer below:
3
That’s right! The ceil() method only rounds upwards to the nearest whole number, which is 3 in this case.
In this video,
you’ll learn how to use the random and seal methods of the math
object in JavaScript. The math object is really useful when
using some of its built in methods, one of which is the random method. For example, this method allows you to generate
a decimal number between 0 and 0.99. So, let’s explore how the random
method works in practice. One way you can work with
the math dot random method, is to save its result in a variable. Notice I have created
a variable named decimal and assign its value to
the math dot random method. I can now log the value to the console,
but please note the limited range of
numbers that will be returned. If you want to output a number larger than
one, you must multiply the variable by 10. And I can do this with the multiplication
operator using the asterisk symbol. When I click on the run button,
the output shows two numbers. The first one is a random decimal, and the second one is the decimal
multiplied by 10. So, this is an example of how you can
extend the range of the math random method to meet your needs. Okay, let me switch tabs now and learn about another built in
method of the math object. The Ceil method. This is used to round up any decimal
number to the nearest integer. Let’s pass several different
decimals through this method and inspect the output. Notice that I have some
code pasted into this file. And online 4,
I’ve created a variable named rounded and assigned it to the math dot ceil method. Inside the parentheses,
I have placed the value 0.0001. I’ve logged this variable to the console. When I run my code notice that
a value of one is output. This is because the seal
method can only round upwards. Just to confirm that behavior,
we can change the decimal. When I set it to 0.5,
I get the same outcome. I change it to 0.99 and
as expected, 1 again. Okay, let’s move on to working
with some larger numbers. Let me in comment line seven and
notice that 1.01 returns a value of 2. When the value is 1.5,
2 is also of the output. Finally, if I run the seal method
on the value 2.99 I end up with 3. So, now you understand how both
the random and seal methods work. Let me switch tabs again and next build
some code that will combine the two to return a random integer between 0 and 10. The first step is to create a variable and assign it the value of the math dot
random method multiplied by 10. I need to pass this variable through
the ceil method to ensure that an integer instead of a decimal value is created. So, I declare the variable rounded and
assign it the value of the math dot ceil method containing the decimal
variable inside the parentheses. Finally, I use the console dot log
method to output the variable rounded. If I run the code, notice that a value
between 0 and 10 is output to the console. Just to confirm this works,
I’ll rerun the code and once again I get the expected results. In this video,
you have learned how to use the random and seal methods of the math
object in JavaScript. Can you think of editing creative uses for
these? Why not give them a try in your own code?
Video: A closer look at strings
Main points:
- Iterables: Data types that can be looped over using “for of” loops. Examples: arrays and strings.
- Strings as array-like: They can be iterated over like arrays due to their sequential nature, but they’re not true arrays.
- String iteration example: Looping over a string “ABC” to print each letter individually.
- Arrays vs. strings: While sharing iterability, strings lack array methods like “pop”.
- String concatenation:
- Using the “+” operator: Joins strings like “Hello” + “Lisa” results in “Hello Lisa”.
- Using the “concat” method: Similar to “+” but allows adding various values.
Key takeaways:
- Understand the concept of iterables and how strings behave like them.
- Practice iterating over both arrays and strings using “for of” loops.
- Remember that strings are not true arrays and have limitations with certain methods.
- Utilize “+” and “concat” methods for string concatenation efficiently.
This summary captures the video’s core concepts on iterables and string manipulation in JavaScript, providing a concise overview for further learning and application.
When two JavaScript developers discuss a subject
related to work, sometimes you might hear the word iterable
being mentioned. But what exactly
does iterable mean? Well, in JavaScript
an iterable is any datatype that
can be iterated over using a for of loop. Some of the data
types you can iterate over are arrays and strings. In this video, you
will learn about the array characteristics
of strings, and you will also explore further string manipulation using the concatenation
operator. In the world of JavaScript, it can often be said
that strings behave like arrays as strings
are array-like. For example, you can run a
for loop over an array of letters and output the result using the console.log method. Additionally, you can also
run a for loop over a string. For example, loop
over the string A, B, C to output the
letters individually. Let me demonstrate this now
with some code examples. In the file I have
opened in my console, I have a variable veggies, which has an array
with three strings. Each string holds the
name of a vegetable, specifically onion,
parsley, and carrot. I’ve typed a console
log for veggies.length, which will return the
number of array items. I also have console logs for
the first and second item of the array using the indexes
zero and one respectively. Finally, I have an
example of a for loop that sets the
counter of i to zero. The exit condition
for this loop is that the comparison
of i is less than veggies length
returns false and i plus plus is the value to
increment on each loop. Inside the for loop, I’m console logging the
veggies at the index of i. When I run this code, I get a three to represent
the array length. Onion from index 0, parsley from index 1, and then finally onion, parsley and carrot
as a result of the for loop outputting all
the items in the array. Now, let’s clear the console and move
on to the next file. Here I’ll explore how strings
can be iterated over. In this file, I have a variable named greeting
with a string value of howdy, along with console logs
for the string length, and the characters at
indexes zero and one. Again, I have a for loop that is structurally the same as
the previous example. Running this code
gives us five for the string length H and O for the zero and one indexes
and then each of the characters of
the full string in sequence as an
output of the loop. Despite the similar behavior, strings are not arrays. To examine this more closely, let’s move on to
the next example. Let me clear the output first. In this code, I have the greet variable that stores a string hello and a user variable
that stores a string Lisa. Then I run a console log with the string greet
and the pop method, which as you know, removes items from an array. There are two other
lines of code, but don’t worry about them now, I’ll cover them shortly. When I try to run this code, I get an error that says type error greet.pop is
not a function. This tells me that I can’t run all the array
methods on strings. Now, let’s run the two
other lines of code. On the first one, I console
log the variable greet, the plus operator, and
the variable user. On the next line, I console log the variable greet and concat method with
the variable user. The concat method
accepts whatever value I want to concat or join
with the greet variable. In this case, both lines
of code will work. They both console
log Hello Lisa. I can confirm that the
plus operator here, when used on strings, acts as a concatenation
operator, meaning it join
strings together. I also have a method named
concat that I can use on a string to add
values to whatever string the concat
method was running.
Reading: String cheat sheet
Reading
By the end of this reading, you’ll be able to:
- Identify examples of String functions and explain how to call them
In this cheat sheet, I’ll list some of the most common and most useful properties and methods available on strings.
For all the examples, I’ll be using either one or both of the following variables:
var greet = "Hello, ";
var place = "World"
Note that whatever string properties and methods I demo in the following examples, I could have ran it on those strings directly, without saving them to a variable such as the ones I named greet and place.
In some of the examples that follow, for the sake of clarity, instead of using a variable name, I’ll use the string itself.
All strings have at their disposal several built-in properties, but there’s a single property that is really useful: the length property, which is used like this:
greet.length; // 7
To read each individual character at a specific index in a string, starting from zero, I can use the charAt() method:
greet.charAt(0); // 'H'
The concat() method joins two strings:
"Wo".concat("rl").concat("d"); // 'World'
The indexOf returns the location of the first position that matches a character:
"ho-ho-ho".indexOf('h'); // 0
"ho-ho-ho".indexOf('o'); // 1
"ho-ho-ho".indexOf('-'); // 2
The lastIndexOf finds the last match, otherwise it works the same as indexOf.
The split method chops up the string into an array of sub-strings:
"ho-ho-ho".split("-"); // ['ho', 'ho', 'ho']
There are also some methods to change the casing of strings. For example:
greet.toUpperCase(); // "HELLO, "
greet.toLowerCase(); // "hello, "
Here’s a list of all the methods covered in this cheat sheet:
- charAt()
- concat()
- indexOf()
- lastIndexOf()
- split()
- toUpperCase()
- toLowerCase()
Reading: Creating arrays and objects (solutions)
Reading
Answers
Step 1
Create a new empty array literal and assign it to the variable clothes.
var clothes = [];
Step 2
Add 5 of your favorite items of clothing as strings using the push() method.
var clothes = [];
clothes.push('gray t-shirt'); // 1st item of clothing
clothes.push('blue t-shirt'); // 2nd item of clothing
clothes.push('yellow t-shirt'); // 3rd item of clothing
clothes.push('slippers'); // 4th item of clothing
clothes.push('old jeans'); // 5th item of clothing
Step 3
Remove the fifth piece of clothing from the array using the pop() method.
var clothes = [];
clothes.push('gray t-shirt'); // 1st item of clothing
clothes.push('blue t-shirt'); // 2nd item of clothing
clothes.push('yellow t-shirt'); // 3rd item of clothing
clothes.push('slippers'); // 4th item of clothing
clothes.push('old jeans'); // 5th item of clothing
clothes.pop();
Step 4
Add a new piece of clothing using the push() method.
var clothes = [];
clothes.push('gray t-shirt'); // 1st item of clothing
clothes.push('blue t-shirt'); // 2nd item of clothing
clothes.push('yellow t-shirt'); // 3rd item of clothing
clothes.push('slippers'); // 4th item of clothing
clothes.push('old jeans'); // 5th item of clothing
clothes.pop();
clothes.push('green scarf');
Step 5
Use console.log to show the third item from the clothes array in the console.
var clothes = [];
clothes.push('gray t-shirt'); // 1st item of clothing
clothes.push('blue t-shirt'); // 2nd item of clothing
clothes.push('yellow t-shirt'); // 3rd item of clothing
clothes.push('slippers'); // 4th item of clothing
clothes.push('old jeans'); // 5th item of clothing
clothes.pop();
clothes.push('green scarf');
console.log(clothes[2]);
Step 6
Create a new empty object literal and assign it to the variable favCar.
var favCar = {};
Step 7
Using the dot notation, assign a color property to the favCar object and give it a string value with the color of your choice.
var favCar = {};
favCar.color = "red";
Step 8
Using the dot notation, assign a covertible property to the favCar object and give it a boolean value of your choice.
var favCar = {};
favCar.color = "red";
favCar.convertible = true;
Step 9
Use the console to log the entire favCar object.
var favCar = {};
favCar.color = "red";
favCar.convertible = true;
console.log(favCar);
Error Handling
Video: Bugs and errors
- Bugs are when our code behaves unexpectedly but continues to work, while errors cause our program to stop running.
- Common error types in JavaScript include syntax errors, reference errors, and type errors.
- Syntax errors occur when you write code that JavaScript cannot read, such as missing closing quotation marks or using an array method on a number.
- Reference errors happen when you try to use a value that is not defined in your code.
- Type errors occur when you perform an operation on a value of the wrong type, such as trying to use an array method on a number.
- JavaScript helps catch these errors by outputting error messages to the console, which can help identify and fix issues in your code.
- Programming errors are common and will likely occur whenever you write code.
- There are different JavaScript tools available to help catch and debug these errors.
Understanding Bugs and Errors:
- Bugs: Unintended flaws in code that cause unexpected behavior or results.
- Errors: Issues that halt code execution, often due to syntax violations or runtime problems.
Common Types of Errors:
- Syntax Errors:
- Caused by incorrect code structure or grammar.
- Examples: Missing semicolons, misspelled keywords, unclosed parentheses.
- Identified by the browser’s console.
- Runtime Errors:
- Occur during code execution, typically due to unexpected inputs or calculations.
- Examples: Dividing by zero, accessing undefined variables, infinite loops.
- Caught using try/catch blocks.
- Logical Errors:
- Produce incorrect results despite code running without syntax or runtime errors.
- Often due to flawed logic or reasoning within the code.
- Require careful debugging to identify.
Debugging Techniques:
- Console Logging:
- Use
console.log()
to print variable values and trace code execution.
- Use
- Debugger:
- Step through code line by line, inspect variables, and set breakpoints.
- Rubber Duck Debugging:
- Explain code to an inanimate object (like a rubber duck) to clarify thought processes.
Prevention Strategies:
- Planning and Writing Clear Code:
- Think through logic before coding.
- Use meaningful variable names and comments.
- Write code in a modular and organized way.
- Testing Thoroughly:
- Write test cases to cover various scenarios.
- Utilize automated testing tools for continuous testing.
- Staying Updated:
- Keep JavaScript knowledge current to avoid common pitfalls.
Additional Tips:
- Use a linter to catch potential errors early.
- Collaborate with other developers for code reviews.
- Learn from debugging experiences to improve coding skills.
Remember: Debugging is an essential skill for any JavaScript developer. Practice patience and persistence to effectively identify and resolve errors in your code.
Isn’t it frustrating when you’re working at your computer and an error message appears on the screen and forces you
to stop what you’re doing. When a bug happens, our program keeps running, but it behaves in a
way we didn’t intend. When an error happens, our program stops running
as the result of an error. In this video, you will
learn about bugs and errors in JavaScript and some
of the common error types, such as syntax, reference
and type errors. Suppose you have created a function that you
pass two numbers. The function adds the two
numbers and outputs the result. Next, you call the function and add another console
log to the next line, where you will output the
string still running. When you run the code, the number 3 will output. Then JavaScript will
happily continue onto the next line of code and console log the
string still running. This is because our example
code contains no errors. When the function is called, the code is executed and
then moved to the next line. While this code
works as expected, what if you pass to the function
some varying data types, such as a string and a number? For example, a string of
one and number of two. For this, recall how
concatenation works. Due to JavaScript coercion, when you add a
string and numbers using concatenation
with the plus operator, the values will
concatenate as strings. Thus, the result
is a string of 12. Our function is now no
longer adding numbers. Instead, it is
concatenating strings. However, JavaScript
happily continues executing the code, outputs the string of 12 and console logs the
words still running. Notice that our program is
working without interruption. However, it is not working
how we intended it to work. This is what’s
referred to as a bug, as it makes our code
behave unexpectedly, but it continues to work. How does an error
differ from a bug? Well, let’s explore
another scenario. Suppose you had
simpler programming that has two statements. The first uses console
log to output c plus d, and the second one uses console log to output
the statement, this line never runs. What at these two lines of code were the only lines of
code in our program. Where would JavaScript find the values of the
variables c and d? Well, it wouldn’t because
in the sample code, these variables don’t exist. They have neither being
declared or assigned. It would look for
the variables of c and d. Since they don’t exist, JavaScript outputs
a reference error. This type of error occurs
when a value is not defined, but you attempt to
use it in your code. When an error happens, our program stops execution the code as a
direct consequence. No further lines of
code are executed. In JavaScript and some other
programming languages, we say that an error is thrown. An error can be defined
as a faulty piece of code that prevents the program
from further execution, an error gets thrown
and the program stops. JavaScript does its best
with reporting error by outputting an error
message to the console. This error reporting is useful because it narrows down
the issue with our code. In JavaScript, there
are many error types and some of the most
common are syntax error, type error, and reference error. You have just learned
about reference error. Let’s explore syntax error
and type error briefly now. A syntax error occurs
when you write a piece of code that
JavaScript cannot read. For example, if you declare a variable and assign
it a value of a string, but forget one of the
closing quotation symbols. Alternatively, suppose you try to run an array
method on a number. For example, the pop method. In this example, a type error would be reported on
called type error, 5.pop is not a function. You’ve now learned
about bugs and errors and the
differences between them. You’ve also learned
about some of the common errors and how JavaScript helps you catch these by outputting error messages. It’s a fact that
programming errors will almost certainly occur
every time you write code. Next, you’ll learn about some of the different JavaScript tools used to catch these errors.
Video: Try catch blocks
- JavaScript errors: Can stop code execution, making debugging difficult.
- Error handling: Using
try
,catch
, andthrow
keywords to handle errors gracefully and prevent code stop. - try-catch block:
try
block contains code that might throw an error,catch
block handles the thrown error. - throw keyword: Manually throws an error within the
try
block. - Benefits:
- Program continues even with errors.
- Catches and handles errors for further processing or logging.
- Comparison to catch in a game: Similar to players catching a thrown ball,
catch
block catches errors thrown by the program.
This video teaches the try-catch
mechanism and throw
keyword for error handling in JavaScript, enabling code to handle errors and continue execution.
Here’s a tutorial on “Try/Catch Blocks” in JavaScript:
Understanding Try/Catch Blocks:
- Purpose: To handle potential errors gracefully and prevent code from crashing.
- Structure:
try
block: Encloses code that might throw errors.catch
block: Executes if an error occurs within thetry
block, catching and handling it.
Syntax:
JavaScript
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
}
Example:
JavaScript
try {
const result = 10 / 0; // This will throw a "Division by zero" error
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
}
Key Points:
- Error Object: The
catch
block receives anerror
object containing information about the error, including its name and message. - Multiple Catch Blocks: You can have multiple
catch
blocks to handle different error types specifically. - Finally Block: Optionally, use a
finally
block to execute code regardless of whether an error occurs or not, often for cleanup tasks.
Common Use Cases:
- Handling user input errors
- Preventing unexpected API response issues
- Managing file system operations
- Debugging code
Best Practices:
- Use try/catch blocks judiciously to avoid excessive error handling.
- Provide meaningful error messages for debugging and user feedback.
- Consider alternative error handling techniques like conditional checks when appropriate.
Remember: Try/catch blocks are essential for writing robust and resilient JavaScript code. By effectively handling errors, you can ensure a better user experience and prevent unexpected application crashes.
Have you ever watched two
people playing a game of catch? It’s a pretty simple game. One player throws a ball and
the other tries to catch it. You may recall that when your code
contains an error, it stops running. Well, in JavaScript, there are some
built in statements to help your code continue to run
even if an error occurs. They also use keywords like throw and
catch. However they tried to catch
the error instead of the ball. In this video, you will learn about
the statements throw, try and catch and how they can be used to
work with errors in JavaScript and prevent your code from stopping. This process is more commonly
known as error handling. First, let’s explore the try, catch statement that uses the key words,
try and catch. If a piece of code throws an error,
it can get wrapped inside a try block. Then you can catch the error with the
catch block, and use it to do something. For example,
output the error message to the console. Another key word that you need to
be aware of is that throw keyword. Using the throw keyword, you can force an error to be thrown
from the try block to the catch block. It’s important to remember
that you can use the throw keyword outside the try block, but
it will not be possible to catch it. The catch block accepts something
called an error which is an object. This is the actual error that
is thrown from the try block. While you can name it anything you like,
it’s best to keep it short and meaningful. in this case I named it Err. Let me demonstrate how this works
further with some code examples. Let’s define a block of code to be tested
for errors using the try catch statement. Okay, so
I have visual studio code open and a JavaScript file with some sample code. If I was to run this code now it would
return an error and stop working. This is because the first line
uses a console log to output a+b. But these variables
are not declared anywhere. The second line has a console
log to output the string. This line is never reached and
this statement looks to be or free. When I click the run button,
a reference error is output, telling me that a is not defined. The JavaScript engine then
stops immediately and does not process the 2nd line. It’s not only JavaScript that
throws errors in our programs, you can actually throw them on purpose. This is done by typing the keyword
throw followed by the keyword new and then a specific errors constructor. In this case I use the reference error
constructor with a pair of parenthesis at the end. When I run the code this time I get
a reference error output again. So how can we prevent errors
from stopping our programs? This is where the try catch
syntax makes itself useful. Let’s go to a separate file with
code that shows how that works. But first let’s break down
the structure of the code. The try block starts with the try keyword. And inside of curly braces, you place the
code that you think will throw an error. Next is the catch block which catches
the error that the try block produces. It begins with the catch keyword and
in parenthesis you have a built in or object that you can
name whatever you like. But here I’ve used err. Inside the curly braces, you place
the code you would like to execute. In this example, the try block contains the same console
log statement as before to output a+b. The catch block contains console
logs to output two strings. There was an error and
the error was saved in the error log. Finally, after the catch block,
another console log outputs the string, my program does not stop. The benefit of using try catch is that
even if JavaScript throws an error while going through our code,
it will not stop program execution. To demonstrate that let’s
run our code example. Notice again a reference error is output
stating that a is not defined, and then the two strings from our catch block. It’s important to understand here that
the error is output because I logged it to the console. The strings output after the error message
proving our program continued running. Finally let me switch
tabs to another file, and demonstrate how JavaScript responds
when I manually throw an error. In this example, the try block contains the throw
statement to throw a new reference error. In the catch block there
are two console logs. The first one outputs the error object and the second outputs the string,
there was a reference error. Outside the try catch blocks,
the program ends with a console logs to output the string,
My program does not stop. When I run this code,
notice that the reference error is output. This is the error that was
thrown in the try block and then output using the error
object in the catch block. Once again,
this is just the error being output. The code has not stopped running. And I can confirm this as the final
console log message is output to the console. In this video, you’ve learned how
to work with errors in JavaScript. You learned how you can use try and
catch blocks and the throw keyword to deal with them. The next time you see a game of catch,
think about how you can use a similar mechanism to help catch
errors in your code.
Reading: Syntax, logical and runtime errors
Reading
By the end of this reading, you’ll be able to:
- Recognize common types of errors in JavaScript
Here are some of the most common errors in JavaScript:
- ReferenceError
- SyntaxError
- TypeError
- RangeError
There are some other errors in JavaScript. These other errors include:
- AggregateError
- Error
- InternalError
- URIError
However, in this reading I’ll focus on the Reference, Syntax, Type, and Range errors.
ReferenceError
A ReferenceError gets thrown when, for example, one tries to use variables that haven’t been declared anywhere.
An example can be, say, attempting to console log a variable that doesn’t exist:
console.log(username);
If the variable named username hasn’t been declared, the above line of code will result in the following output:
Uncaught ReferenceError: username is not defined
SyntaxError
Any kind of invalid JavaScript code will cause a SyntaxError.
For example:
var a "there's no assignment operator here";
The above line of code will throw the following error:
Uncaught SyntaxError: Unexpected string
There’s an interesting caveat regarding the SyntaxError in JavaScript: it cannot be caught using the try-catch block.
TypeError
A TypeError is thrown when, for example, trying to run a method on a non-supported data type.
A simple example is attempting to run the pop() method on a string:
"hello".pop() // Uncaught TypeError: "hello".pop is not a function
The array-like behavior of strings was already covered in an earlier lesson in this course.
However, as can be confirmed by running the above line of code, strings do not have all the array methods readily available to them, and trying to use some of those methods will result in a TypeError being thrown.
RangeError
A RangeError is thrown when we’re giving a value to a function, but that value is out of the allowed range of acceptable input values.
Here’s a simple example of converting an everyday Base 10 number (a number of the common decimal system) to a Base 2 number (i.e binary number).
For example:
(10).toString(2); // '1010'
The value of 2 when passed to the toString() method, is like saying to JavaScript: “convert the value of 10 of the Base 10 number system, to its counter-part in the Base 2 number system”.
JavaScript obliges and “translates” the “regular” number 10 to its binary counter-part.
Besides using Base 2 number system, I can also use the Base 8, like this:
(10).toString(8); // 12
I get back the value 12, which is the plain number 10, writen in Base 8 number system.
However, if I try to use a non-existing number system, such as an imaginary Base 100, since this number system effectively doesn’t exist in JavaScript, I will get the RangeError, because a non-existing Base 100 system is out of range of the number systems that are available to the toString() method:
(10).toString(100); // Uncaught RangeError: toString() radix argument must be between 2 and 36
Video: Undefined, null and empty values
The video explains three types of empty values in JavaScript: null, undefined, and empty strings. Each has its own meaning and context:
- Null: Represents the intentional absence of a value. Can be returned by functions or used to indicate no object exists.
- Undefined: Placeholder for a value that hasn’t been assigned yet or doesn’t exist. Used by undeclared variables, functions without return values, or accessing non-existent object properties.
- Empty String: A string with no characters inside. Can be created with quotes containing nothing.
Understanding these empty values is crucial for writing effective JavaScript code, as they can affect how your program runs and data is handled. Remember:
- Always assign values to variables when declaring them.
- Undefined can occur while working with uninitialized variables or accessing non-existent object properties.
- Empty strings are just that, no characters inside.
By utilizing these concepts, you can write more precise and error-free JavaScript code.
Understanding Empty Values:
- In JavaScript, it’s crucial to grasp the distinct concepts of undefined, null, and empty values. Each has a specific meaning and purpose in representing the absence of data.
1. Undefined:
- Placeholder for a value that hasn’t been assigned yet or doesn’t exist.
- Common scenarios:
- Undeclared variables: JavaScript
let myVariable; // Undefined console.log(myVariable); // Outputs "undefined"
- Functions without explicit return values: JavaScript
function sayHi() { console.log("Hi!"); } let greeting = sayHi(); // Undefined
- Accessing non-existent object properties: JavaScript
const person = {}; console.log(person.name); // Undefined
- Undeclared variables: JavaScript
2. Null:
- Represents the intentional absence of any object value.
- Common scenarios:
- Returned by functions to indicate no meaningful value: JavaScript
function findElement(array, value) { for (let i = 0; i < array.length; i++) { if (array[i] === value) { return i; // Found the index } } return null; // Not found }
- Used to explicitly set a variable to “no value”: JavaScript
let middleName = null;
- Returned by functions to indicate no meaningful value: JavaScript
3. Empty String:
- A string with no characters inside.
- Created using quotes with nothing between them:
javascript let emptyString = "";
Distinguishing Between Them:
- Undefined: A placeholder for a missing value.
- Null: A deliberate representation of no value.
- Empty String: A string with a length of 0, but it’s still a string data type.
Key Points:
- Always assign values to variables when declaring them to avoid undefined.
- Use null intentionally when you want to signify the absence of an object value.
- Remember that empty strings are strings, even though they have no characters.
- Check for these values using comparison operators (===) and typeof.
Example:
JavaScript
function checkValue(value) {
if (value === null) {
console.log("The value is null.");
} else if (value === undefined) {
console.log("The value is undefined.");
} else if (value === "") {
console.log("The value is an empty string.");
} else {
console.log("The value has a defined value:", value);
}
}
By understanding these concepts, you’ll create more robust and predictable JavaScript code.
Imagine that a restaurant has been booked for a
wedding reception, and the big day has
finally arrived. Unfortunately, not everything
is going smoothly and it seems that many expected
guests have not yet arrived. How do we know that empty seats should be filled with guests? It’s as simple as placing a
small sign on each table. Each one tells us a person
is not currently here, but a person should be here. In JavaScript, there are
similar situations in which you need to mark the places where a value or object should exist. In this video, you’ll
learn about three types of empty values:
the null datatype, the undefined datatype,
and empty strings. I’ll also demonstrate
some of the scenarios in which you can expect to
encounter these values. We’ll start with
the null datatype. Null represents the
intentional absence of any object value. It is also a return value of some built-in
JavaScript methods. For example, let’s
say you create the variable named letters and assign it a string value of abc. You’d like to search for
the letter a in the string. You could do this by using the match method to search
inside the variable. This returns an array with several pieces of information, but the most important
part is that it confirms the a was found in the string. This time, let’s use the same method on
a different letter, the letter d. The return value of the match method
should be an array, which is a object in JavaScript, but since the d letter
cannot be found, the array with the
result can’t be built, so null appears instead to indicate the
absence of an object. In JavaScript, there may also be times when you are
building something that hasn’t been clearly defined yet and so you can’t
assign a value to it. Fortunately, there is a way
to store it so that you can assign it later using
the undefined datatype. While some data types in JavaScript can hold
many possible values, others are constrained
to just a few. For example, the
string data type can hold a virtually
infinite combination of characters while the
Boolean data type is limited to the
values true or false. The undefined data type can only hold one value, undefined. You may recall seeing this
in your practice code. For example, all functions
return undefined by default unless it’s been decided to return a specific
value instead. When you use console.log to
output something like a name, you will see undefined
displayed after the output. This is because console.log is a function and you are
not returning a value. Another common situation
where the undefined value appears is when a variable is declared without
an assignment. For example, suppose I create
a variable named noise, but do not assign it a value. You might recall
that this is valid JavaScript and the
code will run. However, as the variable has
not been assigned a value, JavaScript automatically
assigns the value of undefined. We can even explore
this further. For example, let’s
say you use console. to output the unassigned
variable noise. Then on the line below, you assign the noise variable the string value of thunder. What will happen
if you then output this variable again
to the console? The console will output
the string thunder. This means only the
instances after the declaration was take
the assigned value. Even if the declaration
assigns a value, any uses of the variable before the declaration will
still return undefined. While it’s important to
understand this behavior, it’s usually best
practice to always assign your variables with values
when you declare them. As you may have noticed, JavaScript gives you
some flexibility, but you still have limitations. For example, if you
tried to console.log a variable that hasn’t been
declared in your entire code, your program
execution will stop, and rather than undefined, a reference error
will be output. One way to think
about it is that the undefined datatype acts like a placeholder for a value that the JavaScript engine
knows to exist. It just has not been specified. Another scenario of
undefined is when you try to access an object
property that doesn’t exist. For example, let’s say you have a game object with a property score that
has a value of 1,000. The property contains
all lowercase words. Let’s say you try to
access this property, but you make a spelling
mistake and spell score with a capital S. JavaScript can’t find anything
with this information, so it gives you the
value undefined instead. Finally, let’s explore
the last empty value, which you might be already familiar with, the empty string. This is a string without
any characters inside of it and it can be
built in a few ways, such as with single quotes or double quotes with no
characters in between them. In this video, you learned about the differences between
null, undefined, and empty strings,
as well as some of the common situations
in which they appear.
Reading: Exercise: Error prevention
Reading
Instructions
Task 1: Code a function declaration
You need to code a function declaration named addTwoNums, which accepts numbers a and b and console logs a + b.
Task 2: Invoke the addTwoNums function with a number and a string
You need to invoke the addTwoNums using the following arguments: 5 and “5”.
Task 3: Update the addTwoNums function with a try…catch block
Add the try and catch blocks inside the function definition’s body. For now, just make sure that the console log of a + b is inside the try block. Additionally, the catch block should catch an error named err and, inside the body of the catch block, you need to console log the err value.
Task 4: If the passed-in arguments are not numbers, throw an error
If either of the arguments passed to the addTwoNums are not numbers, you’ll throw an error.
Specifically, code a conditional with the following logic:
- if the typeof the a parameter is not equal to ‘number’, throw a new ReferenceError. Inside the ReferenceError, pass a custom error message of ‘the first argument is not a number’.
- else if the typeof the b parameter is not equal to ‘number’, throw a new ReferenceError. Inside the ReferenceError, pass a custom error message of ‘the second argument is not a number’.
- else, console log a + b
Once you’ve completed this task, all the code inside the try block will be inside these conditional statements.
Task 5: Update the catch block
Inside the catch block, update the code from console.log(err) to console.log(“Error!”, err).
Task 6: Invoke the addTwoNums function
Invoke the addTwoNums function using 5 and “5” as arguments.
Task 7: Add another console log under the addTwoNums function invocation
Add another line of code that console logs the string “It still works”.
function addTwoNums(a,b){
try {
console.log(a+b);
} catch(err) {
console.log(err);
}
}
Reading: Solution: Error prevention
Reading
Solution to task 1: Code a function declaration
function addTwoNums(a,b) {
console.log(a + b) //display the result
}
Solution to task 2: Invoke the addTwoNums function with a number and a string
function addTwoNums(a,b) {
console.log(a + b)
}
addTwoNums(5, "5") // "55"
55
Solution to task 3: Update the addTwoNums function with a try…catch block
function addTwoNums(a,b) {
try {
console.log(a + b)
} catch(err) {
console.log(err)
}
}
addTwoNums(null,false)
Solution to task 4: If the passed-in arguments are not numbers, throw an error
function addTwoNums(a,b) {
try {
if(typeof(a) != 'number') {
throw new ReferenceError('the first argument is not a number')
} else if (typeof(b) != 'number') {
throw new ReferenceError('the second argument is not a number')
} else {
console.log(a + b)
}
} catch(err) {
console.log(err)
}
}
addTwoNums("a","b")
ReferenceError: the first argument is not a number
at addTwoNums (file:///tmp/sjuee/submission.mjs:12:19)
at file:///tmp/sjuee/submission.mjs:22:1
at ModuleJob.run (internal/modules/esm/module_job.js:183:25)
at async Loader.import (internal/modules/esm/loader.js:178:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
at async handleMainPromise (internal/modules/run_main.js:59:12)
Solution to task 5: Update the catch block
function addTwoNums(a,b) {
try {
if(typeof(a) != 'number') {
throw new ReferenceError('the first argument is not a number')
} else if (typeof(b) != 'number') {
throw new ReferenceError('the second argument is not a number')
} else {
console.log(a + b)
}
} catch(err) {
console.log("Error!", err)
}
}
Solution to tasks 6 and 7: Invoke the addTwoNums function and Add another console log under the addTwoNums function invocation
function addTwoNums(a,b) {
try {
if(typeof(a) != 'number') {
throw new ReferenceError('the first argument is not a number')
} else if (typeof(b) != 'number') {
throw new ReferenceError('the second argument is not a number')
} else {
console.log(a + b)
}
} catch(err) {
console.log("Error!", err)
}
}
addTwoNums(5, "5")
console.log("It still works")
Error! ReferenceError: the second argument is not a number
at addTwoNums (file:///tmp/invfk/submission.mjs:14:19)
at file:///tmp/invfk/submission.mjs:22:1
at ModuleJob.run (internal/modules/esm/module_job.js:183:25)
at async Loader.import (internal/modules/esm/loader.js:178:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
at async handleMainPromise (internal/modules/run_main.js:59:12)
It still works
Reading: Exercise: Defensive programming
Reading
Defensive programming is all about assuming that all the arguments a function will receive are of the wrong type, the wrong value or both.
In other words, you are assuming that things will go wrong and you are proactive in thinking about such scenarios before they happen, so as to make your function less likely to cause errors because of faulty inputs.
How would you then refactor the function given below with defensive programming in mind?
For this exercise, let’s make sure that both of the arguments that are passed in satisfy the following criteria:
- The length of the word parameter cannot be less than 2.
- The length of the match parameter must be 1.
- The type of both the word and the match parameters must be string.
You will use the code below to complete your task:
function letterFinder(word, match) {
for(var i = 0; i < word.length; i++) {
if(word[i] == match) {
//if the current character at position i in the word is equal to the match
console.log('Found the', match, 'at', i)
} else {
console.log('---No match found at', i)
}
}
}
Here are the tasks to complete:
- Just above the for loop in the letterFinder function definition, declare a variable named condition1 and assign to it the following code: typeof(word) == ‘string’ && word.length >= 2.
- Declare a variable named condition2 on the next line and assign to it and assign to it a check that makes sure that the type of match is a string AND that the length of the match variable is equal to 1.
- Write an if statement on the next line that checks that condition1 is true, and condition2 is true
- Move the rest of the function’s body into the if statement you wrote in the previous step.
- Code an “else” block after the “if” condition and console.log the following: “Please pass correct arguments to the function.”.
- As a failing test, run the letterFinder function and pass it with any two numbers as arguments.
- As a passing test, run the letterFinder function and pass it with correct arguments, such as: letterFinder(“cat”, “c”).
Reading: Solution: Defensive programming
Reading
Answer (full completed code)
function letterFinder(word, match) {
var condition1 = typeof(word) == 'string' && word.length >= 2; //if the word is a string and the length is greater than or equal to 2
var condition2 = typeof(match) == 'string' && match.length == 1; //if the match is a string and the length is equal to 1
if(condition1 && condition2) { //if both condition matches
for(var i = 0; i < word.length; i++) {
if(word[i] == match) {
//check if the character at this i position in the word is equal to the match
console.log('Found the', match, 'at', i)
} else {
console.log('---No match found at', i)
}
}
} else {
//if the requirements don't match
console.log("Please pass correct arguments to the function")
}
}
letterFinder([],[])
letterFinder("cat","c")
Practice Quiz: Knowledge check: Error handling
What will be printed when the following code runs?
var result = null;
console.log(result);
null
That’s correct! Since the value is initialised with null, null will be output.
When the following code runs, what will print out?
try {
console.log('Hello');
} catch(err) {
console.log('Goodbye');
}
Hello
That’s correct! Since there is no error thrown inside the try block, the catch block will not run. Therefore, “Hello” will print out.
If you pass an unsupported data type to a function, what error will be thrown?
TypeError
That’s correct! TypeError will be thrown when an incorrect data type is passed to a function.
What will print out when the following code runs?
var x;
if(x === null) {
console.log("null");
} else if(x === undefined) {
console.log("undefined");
} else {
console.log("ok");
}
undefined
That’s correct! Since the value is not initialised, it will have the undefined data type.
What will print out when the following code runs?
throw new Error();
console.log("Hello");
Nothing will print out.
That’s correct! Throwing an error will stop the execution of the code.
Video: Module summary: The Building Blocks of a Program
- Introduction to arrays, objects, and functions
- Purpose and benefits of functions
- Process for building an array and accessing its contents
- Array characteristics and concatenation operators for strings
- Building and calling functions
- Creating custom objects
- How math objects work and interact with arrays and objects
- Recognizing the differences between bugs and errors
- Using try-catch blocks
- Understanding undefined, null, and empty string values
- Recognizing common types of errors in JavaScript
- Engaging in defensive programming
You’ve reached the end of this module on the building
blocks of a program. In this module, you’ve
discovered how to work with arrays,
objects, and functions. You’ve also discovered how to prevent errors in your code. It’s now time to recap the key topics you learned
and skills that you gained. You began the module with an introduction to arrays,
objects, and functions. Now that you’ve
completed this lesson, you can explain the purpose of functions and describe
their benefits. Outline the process for building an array and accessing
its contents. You now understand the
array characteristics and concatenation
operators of strings. You can also build and call functions, create
custom objects, explain how math objects work and interact with
arrays and objects. During this module, you also undertook a series
of exercises in which you demonstrated
your ability to utilize functions to
solve simple problems, add strings to arrays and
add properties to objects. You then moved on
to the next lesson, in which you explored the
concept of error prevention. During this lesson,
you discovered how to recognize the differences
between bugs and errors. Demonstrate try-catch blocks, and explain the
concepts of undefined, null, and empty string values. You also completed several
readings in which you learned how to recognize common types
of errors in JavaScript, including syntax,
logical, and run-time, and engage in
defensive programming. You should now be familiar
with arrays, objects, and functions and
you should also have developed your skills
in error prevention. Great work. You’re
making good progress on your journey to becoming
a JavaScript developer.
Quiz: Module quiz: The Building Blocks of a Program
What data type is the variable x ?
var x = {};
Object
That’s correct! {} is the array literal.
What will be the output of running the following code?
try {
console.log('hello)
} catch(e) {
console.log('caught')
}
Uncaught SyntaxError: Invalid or unexpected token.
Correct, you cannot handle SyntaxErrors in JavaScript using a try catch block.
What value is printed when the following code runs?
var burger = ["bun", "beef", "lettuce", "tomato sauce", "onion", "bun"];
console.log(burger[2]);
lettuce
That’s correct! Indices start at 0. Therefore lettuce will print out as it is at index 2.
In the following code, how many methods does the bicycle object have?
var bicycle = {
wheels: 2,
start: function() {
},
stop: function() {
}
};
2
AI
The bicycle object has 2 methods.
Explanation:
- Methods are functions that are defined within an object and can be called upon that object.
- In the given code, the bicycle object has two methods:
- start: This method is likely used to initiate some action related to the bicycle’s movement.
- stop: This method is likely used to halt the bicycle’s movement.
- The wheels property is not a method; it’s a simple property that stores the number of wheels the bicycle has.
Key points:
- Methods are always functions, but not all properties are methods.
- Methods are used to perform actions or tasks related to an object.
- Properties store data or information about an object.
When the following code runs, what will print out?
try {
throw new Error();
console.log('Hello');
} catch(err) {
console.log('Goodbye');
}
Goodbye
That’s correct! When the error is thrown, the code will execute the code inside the catch statement.
AI
The code will print out “Goodbye”.
Explanation:
- Error Thrown: The
throw new Error();
statement intentionally creates an error within thetry
block. - Catching the Error: The
try...catch
structure is designed to handle errors. When the error is thrown, control immediately jumps to thecatch
block. - Console Output: The
console.log('Hello');
statement never executes because the error halts the normal flow of code within thetry
block. Instead, theconsole.log('Goodbye');
statement within thecatch
block is executed, printing “Goodbye” to the console.
Key Points:
throw
is used to create and throw errors.try...catch
blocks are used for error handling.- When an error is thrown within a
try
block, the code jumps to the correspondingcatch
block, skipping any remaining code in thetry
block.
If you mis-type some code in your JavaScript, what kind of error will that result in?
SyntaxErrror
Will the following code execute without an error?
function add(a, b) {
console.log(a + b)
}
add(3, "4");
Yes
That’s correct! Although the code has a bug, it will execute without error. Instead of adding the numbers and printing 7 , it will print 34 .
What will be printed when the following code runs?
var result;
console.log(result);
undefined
That’s correct! Since no value was assigned to result , undefined will print out.
What will be the output of the following code?
var str = "Hello";
str.match("jello");
null
AI
The output of the code will be null.
Explanation:
- String Creation: The
var str = "Hello";
line creates a string variable namedstr
with the value “Hello”. - Match Attempt: The
str.match("jello");
line calls thematch
method on the string “Hello”, trying to find a match with the pattern “jello”. - No Match Found: The pattern “jello” does not match any part of the string “Hello”, so the
match
method returns null.
Key Points:
- The
match
method returns an array of matches if a match is found, or null if no match is found. - The
match
method is case-sensitive, so “jello” does not match “Hello”. - The empty string (“”) matches any string, so
str.match("")
would return an array containing the entire string “Hello”.
What will be the output of the following code?
try {
Number(5).toPrecision(300)
} catch(e) {
console.log("There was an error")
}
“There was an error”
Correct! The catch block will execute and print because of the Range error.