Skip to content
Home » META » Meta Front-End Developer Professional Certificate » Programming with JavaScript » Week 2: The Building Blocks of a Program

Week 2: The Building Blocks of a Program

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

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: JavaScriptfunction addNumbers(a, b) { return a + b; }
  • Manipulating strings: JavaScriptfunction reverseString(str) { return str.split("").reverse().join(""); }
  • Interacting with the browser: JavaScriptfunction displayAlert(message) { alert(message); }
  • Creating reusable components: JavaScriptfunction 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 element
  • slice(): Extracts a portion of an array
  • splice(): Adds or removes elements at a specific index
  • sort(): Sorts elements alphabetically or numerically
  • reverse(): 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

Reading: Exercise: Practicing with functions

Reading

Reading: Solution: Practicing with functions

Reading

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 like movementRange.
    • Comma-delimited key-value pairs: {key1: value1, key2: value2, ...} within object literal.
  • 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

Reading: Object Literals and the Brackets Notation

Reading

Reading: Arrays are Objects

Reading

Reading: Math object cheat sheet

Reading

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:

  1. Generate a decimal between 0 and 9.99 using Math.random() * 10.
  2. 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();
  • Math.ceil(x): Rounds a number x up to the nearest integer.
    • Example: let roundedUp = Math.ceil(4.2); // Output: 5
  • Math.floor(x): Rounds a number x down to the nearest integer.
    • Example: let roundedDown = Math.floor(4.8); // Output: 4
  • 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
  • Math.abs(x): Returns the absolute (positive) value of a number x.
    • Example: let absoluteValue = Math.abs(-5); // Output: 5
  • Math.max(x1, x2, …): Returns the largest of the given numbers.
    • Example: let largest = Math.max(3, 7, 2); // Output: 7
  • Math.min(x1, x2, …): Returns the smallest of the given numbers.
    • Example: let smallest = Math.min(5, 1, 9); // Output: 1
  • Math.pow(x, y): Returns x raised to the power of y.
    • Example: let squared = Math.pow(4, 2); // Output: 16
  • Math.sqrt(x): Returns the square root of a number x.
    • Example: let squareRoot = Math.sqrt(16); // Output: 4

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:

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

Reading: Creating arrays and objects (solutions)

Reading

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:

  1. Syntax Errors:
    • Caused by incorrect code structure or grammar.
    • Examples: Missing semicolons, misspelled keywords, unclosed parentheses.
    • Identified by the browser’s console.
  2. 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.
  3. 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:

  1. Console Logging:
    • Use console.log() to print variable values and trace code execution.
  2. Debugger:
    • Step through code line by line, inspect variables, and set breakpoints.
  3. Rubber Duck Debugging:
    • Explain code to an inanimate object (like a rubber duck) to clarify thought processes.

Prevention Strategies:

  1. Planning and Writing Clear Code:
    • Think through logic before coding.
    • Use meaningful variable names and comments.
    • Write code in a modular and organized way.
  2. Testing Thoroughly:
    • Write test cases to cover various scenarios.
    • Utilize automated testing tools for continuous testing.
  3. 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, and throw 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 the try 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 an error 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

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: JavaScriptlet myVariable; // Undefined console.log(myVariable); // Outputs "undefined"
    • Functions without explicit return values: JavaScriptfunction sayHi() { console.log("Hi!"); } let greeting = sayHi(); // Undefined
    • Accessing non-existent object properties: JavaScriptconst person = {}; console.log(person.name); // Undefined

2. Null:

  • Represents the intentional absence of any object value.
  • Common scenarios:
    • Returned by functions to indicate no meaningful value: JavaScriptfunction 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”: JavaScriptlet middleName = null;

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

Reading: Solution: Error prevention

Reading

Reading: Exercise: Defensive programming

Reading

Reading: Solution: Defensive programming

Reading

Practice Quiz: Knowledge check: Error handling

What will be printed when the following code runs?

When the following code runs, what will print out?

If you pass an unsupported data type to a function, what error will be thrown?

What will print out when the following code runs?

What will print out when the following code runs?

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 ?

What will be the output of running the following code?

What value is printed when the following code runs?

In the following code, how many methods does the bicycle object have?

When the following code runs, what will print out?

If you mis-type some code in your JavaScript, what kind of error will that result in?

Will the following code execute without an error?

What will be printed when the following code runs?

What will be the output of the following code?

What will be the output of the following code?


Home » META » Meta Front-End Developer Professional Certificate » Programming with JavaScript » Week 2: The Building Blocks of a Program