Skip to content
Home » META » Meta Front-End Developer Professional Certificate » Programming with JavaScript » Week 3: Programming Paradigms

Week 3: Programming Paradigms

This module is about functional programming and the oriented programming paradigm. You will learn what scope is in JavaScript. You’ll explore the differences between var, let and const. And you’ll learn how to use classes and inheritance in object oriented programming. Additionally, you’ll explore how to use write JavaScript using modern features like spread and rest. You will build code that can manipulate the DOM and handle events. And you will use JSON in JavaScript. After completing this module, you will be able to:

Learning Objectives

  • Outline the tenets of the functional programming and object-oriented programming paradigm
  • Describe how scope works in JavaScript
  • List the differences between var, let, and const
  • Use classes and inheritance in OOP in JavaScript
  • Use JSON in JavaScript
  • Build code that manipulates the DOM and handles events
  • Write JavaScript code using more modern features like spread, rest, template strings, and modules
Table Of Contents
  1. Introduction to Functional Programming
  2. Introduction to Object-Oriented Programming
  3. Advanced Javascript Features
  4. Javascript in the Browser
  5. Task 5: Add an event listener

Introduction to Functional Programming


Video: Introduction to functional programming

Key Points:

  • Programming paradigms are different approaches to writing code, similar to various styles in human languages.
  • Functional programming (FP) focuses on clear separation between data and functions.
  • Data exists outside functions and can be passed as arguments.
  • Functions receive data, perform operations, and return results.
  • Unlike object-oriented programming (OOP), data and functions aren’t bundled in objects.
  • The example calculates currency conversion using a function named convertCurrency that multiplies amount by rate.
  • The function’s output is used to update a variable holding the converted currency value.
  • This demonstrates how FP separates data and logic cleanly for solving problems.

Overall:

Functional programming offers a distinct approach to code structure and data manipulation, with its emphasis on data immutability and pure functions. By understanding its principles, developers can choose the programming paradigm best suited for their specific needs and goals.

** Welcome to the Wonderful World of Functional Programming in JavaScript!**

In this tutorial, we’ll dive into the core concepts of functional programming (FP) and explore how to apply them in JavaScript to create more elegant, maintainable, and bug-resistant code.

Here’s a roadmap of our journey:

  1. Paradigm Shift: Understanding the FP mindset and its key principles.
  2. Functions as First-Class Citizens: Treating functions like any other data type, passing them around, and returning them from other functions.
  3. Immutability: Embracing the concept of non-mutating data to ensure predictability and reduce side effects.
  4. Pure Functions: Functions that always produce the same output for the same input, making testing and reasoning easier.
  5. Higher-Order Functions: Functions that operate on other functions, like map, filter, and reduce, unlocking powerful data manipulation techniques.
  6. Recursion: Solving problems by breaking them down into smaller, self-similar subproblems, often leading to elegant and concise solutions.
  7. JavaScript’s FP Arsenal: Exploring built-in FP features like arrow functions, const, let, and template literals.
  8. Common FP Patterns: Mastering techniques like function composition and currying to create modular and reusable code.
  9. Real-World Examples: Applying FP to solve practical problems in JavaScript, such as data processing, asynchronous programming, and user interface design.

Get ready to:

  • Think declaratively, focusing on what you want to achieve rather than how to achieve it step by step.
  • Embrace immutability and pure functions for cleaner code and easier reasoning.
  • Master higher-order functions for elegant data transformations.
  • Unleash the power of recursion for concise problem-solving.
  • Write more concise, expressive, and bug-free JavaScript code.

**Let’s embark on this exciting adventure together! **

In functional programming, the data and functions that work on that data are combined inside objects.

False

Correct! In functional programming, data and functions that operate on it are clearly separated, not combined inside objects.

When you listen to
a lecture in class, the language used is
probably very formal. Grammar rules are observed, and syntax and vocabulary can get quite complex
based on the topic. Some other examples
of the use of formal language can be found in courts and other
legal institutions. Now let’s consider
the way people talk in their everyday life. There’s lots of slang, grammar rules are
bent and broken, and the entire delivery
is colloquial. There are many styles in
every human language, and they all perform the exact same function,
communication. The same can also be said
about computer languages. They too have various styles, also known as
programming paradigms. Just like in human languages, no one style is better
suited than the other. In programming, there are
two commonly used paradigms. Functional programming,
sometimes abbreviated as FP, and object-oriented programming, sometimes abbreviated as OOP. You can think of
these paradigms as different approaches
to writing code. But the result is
still the same, instructing a computer to
perform a set of operations. In this lesson, you will learn about functional
programming. Let’s now focus on the
functional programming style. There is a clear distinction between data and functions in functional programming as data can exist outside of functions. For example, you may recall
that when functions need some data you pass them the values in the
form of arguments. Then the function
perform some work on the given data and returns some values that you can then use somewhere else
in your program. An alternative paradigm is the object-oriented
programming paradigm, where you combine both data
and functions into objects. You’ll learn more about object oriented
programming later. Now let’s examine a
practical implementation of the functional
programming style using a coding example to calculate
currency conversion. In this example of
functional programming, let me start by giving
my program some data. The purpose of the program is to perform currency conversions. Notice that I already have
a variable declared with the name currencyOne and
assigned it the value of 100. Next, I’ll add two more
variables, currencyTwo, which is assigned a value of 0, and exchangeRate,
which is set to 1.2. Notice that I have declared all these variable
names using CamelCase. This is where the
first letter of the first word is lowercase and the first letter of the
subsequent words are without spaces and in uppercase. Next, I can create the
function that will work with these variables
and operate on this data. First, I create a function named convertCurrency that
accepts two parameters, amount and rate. Then in the function’s body, I returned the result of the amount multiplied
by the rate. Basically, I’m coding
it to multiply the two values it receives
and return the result. Next, I need to update
the value of currencyTwo, which was previously
defined on line four, assigned to the value of 0. To do this, I
assign the value of currencyTwo to the result of
the function I just created. Recall that when the
function is invoked, it will return a
value which will be assigned to the
variable currencyTwo. It’s important to remember
that I need to also pass the two arguments required
for my function to work. In this example, I’m sending the variables currencyOne
and exchangeRate. Basically, I’m passing
the values 100 and 1.2 to the function so it can perform its calculation
and return the result. Finally, I console log the value of currencyTwo to test my code. Success, 120 is output
to the console, the result of 100
multiplied by 1.2. In this lesson,
you learned about functional programming
and how it can be used to solve a problem by separating data from functions. Great job.

Reading: Return values from functions

Reading

Video: Function calling and recursion

– Definition: A recursive function is a function that calls itself within its own body, creating a loop-like behavior. – Potential Issue: If not designed carefully, it can lead to infinite loops, continuously calling itself without stopping. – Treadmill Analogy: Like a treadmill that needs a stopping mechanism, recursive functions require a condition to break the recursion and prevent endless running. – Example:

  • A function named example was created.
  • It initially logged three lines of text.
  • To demonstrate recursion, the function was modified to call itself, resulting in an infinite loop.
  • To prevent this, a counter variable and a conditional statement were added:
    • The counter starts at 3 and decrements with each function call.
    • When the counter reaches 0, the function returns, ending the recursion. – Key Takeaways:
  • Recursive functions offer an alternative way to repeat tasks without traditional loops.
  • They’re powerful but require careful design to avoid infinite loops.
  • A base case (like the counter reaching 0) is essential to ensure termination.

Welcome to the JavaScript Function Calling and Recursion Playground!

Here’s a guided tour through these fundamental concepts:

1. Function Calling: The Art of Delegation

  • Function as a Recipe: Imagine a function as a recipe for performing a specific task. It has a name and a set of instructions (the code within its body).
  • Calling a Function: When you call a function, you’re asking the JavaScript interpreter to execute those instructions.
  • Syntax: JavaScriptfunctionName(arguments); // Example: greet("Alice");
  • Example: JavaScriptfunction greet(name) { console.log("Hello, " + name + "!"); } greet("Bob"); // Output: Hello, Bob!

2. Recursion: Functions Calling Themselves

  • Definition: A recursive function is a function that calls itself within its own body. It’s like a spiral staircase, where each step leads back to itself.
  • Base Case: To avoid infinite loops, every recursive function must have a base case—a condition that stops the recursion.
  • Example: Counting Down JavaScriptfunction countDown(number) { if (number === 0) { // Base case console.log("Blast off!"); } else { console.log(number); countDown(number - 1); // Recursive call } } countDown(3); // Output: 3, 2, 1, Blast off!

3. Visualizing Recursion: The Call Stack

  • Think of the Call Stack as a Pile of Plates: Each function call adds a new plate to the stack, and each function return removes a plate.
  • Understanding the Stack: When a function calls itself recursively, multiple instances of that function are added to the stack, each with its own local variables and execution context.

4. Common Use Cases for Recursion

  • Traversing trees and graphs (e.g., file systems, family trees)
  • Solving problems that can be broken down into smaller, self-similar subproblems (e.g., factorial calculation, Fibonacci sequence)
  • Implementing algorithms like sorting and searching

5. Cautions and Considerations

  • Infinite loops: Ensure a base case to prevent them.
  • Performance overhead: Recursion can be slower than loops for large problems.
  • Stack overflow: Too many nested calls can exhaust memory.

Get Ready to Experiment!

  • Practice writing and calling functions.
  • Explore recursive examples and visualize the call stack.
  • Understand the benefits and trade-offs of recursion.
  • Apply recursion to solve real-world problems.

Unlock the Power of Function Calling and Recursion in JavaScript!

Treadmills are a useful piece of
equipment for doing cardio at the gym, or when running outdoor isn’t an option. They are also easily started
with the push of a button. Imagine however, if there was no way
to control when a treadmill stopped, that wouldn’t be ideal, would it? Fortunately, most treadmills have a
function that tells the treadmill to stop after a specified amount of time. Thank goodness. In JavaScript, functions that
repeat tasks are similarly helpful, unless they run endlessly. In this video, I’ll demonstrate what
recursive functions are, and help you understand how to write them properly to
avoid getting stuck in an infinite loop. To call, invoke, or execute a function
means instructing it to follow the code inside of it one line at a time. To demonstrate,
let’s first build an example. Type function example, parentheses,
then left curly brace. Press enter to advance to the next
line and type console dot log. Inside of the parentheses,
type quote line one, unquote, and then close off with a semi colon. I now have one line of code,
but let’s add a few more. On separate lines, I am put two more
console dot log lines as I did before, but this time containing the strings
line two and line three respectively. I close the function by
inputting a right curly brace. I’ve built a function called
example with three lines. When I run it, each of the lines will
be executed one at a time in sequence producing three strings. To make things interesting, let’s add
one more line to the example function. This time,
type the name of the function itself. So that’s example, parentheses, semicolon. Now, if I run the function again,
it will repeat in an infinite loop. Obviously this wouldn’t be useful. So let’s improve it, and
ensure that it won’t run endlessly. I add a new line before the function and
let counter equal sign three semi colon. Next, I delete my three
console dot log lines, which I’ll replace with
some different code. For the first line,
I type console dot log, and then counter inside of the parentheses. On the second line, I type counter
equal sign, counter minus 1 semi colon. And finally, for the third line,
I start by typing if, and then inside of the parentheses,
I type counter triple equal sign, zero. And then I type return in a semi colon. If I call the function this time, it will
log the numbers 3, 2, 1, and then stop. When a function calls itself,
this is what’s known as recursion. Recursion is an alternative way to run
repetitive code without the use of loops. Next time you see someone
running on a treadmill, imagine a function running
in the background. It might be calling itself to continue
running until its condition is meant to stop. In this video, you learned about the uses
and potential problems of recursive functions, and how to write them so
that they don’t run endlessly.

Do you recall these comparison operators == and === ?

Yes

Great! But just in case, check out the reading, Operators in depth in Module 1 Lesson 2.

Consider the following code:
function myDay() {
    console.log('Morning');
    console.log('Afternoon');
    console.log('Evening');
    myDay();
}
Which one of the following best describes what will happen if you run this code?

The function will run in an infinite loop.

Correct! The function will run over and over, as there is no condition to stop it.

Video: Introduction to scope

Here’s a summary of the key points about scope in JavaScript:

Scope Defined:

  • It determines which parts of the code (like variables and functions) are accessible from different parts of your program.
  • It’s like a two-way mirror in a restaurant: code inside a function can see “out” to the global scope, but code outside can’t see “in” to the local scope.

Types of Scope:

  • Global Scope:
    • Code outside of any function.
    • Variables and functions here are accessible from anywhere in the program.
  • Local Scope (Function Scope):
    • Code within a function.
    • Variables and functions defined here are only accessible within that function.

Scope Chain:

  • Each function has a reference to its parent scope, forming a chain.
  • When a variable is not found in the local scope, JavaScript searches up the scope chain to find it.

Key Takeaways:

  • Understanding scope is essential for writing well-organized and predictable JavaScript code.
  • It helps prevent naming conflicts and unintended variable access.
  • Knowing the different scope types and how the scope chain works is crucial for effective JavaScript development.

Welcome to the JavaScript Scope Playground!

In this tutorial, we’ll explore the concept of scope, a crucial part of writing well-structured and predictable JavaScript code.

Here’s what we’ll cover:

1. What is Scope?

  • Imagine your code as a well-organized house with different rooms. Scope determines which variables and functions live in which rooms and who can access them.
  • It prevents naming conflicts and unintended access, keeping your code clean and efficient.

2. Global Scope:

  • The outermost room of your code house.
  • Variables and functions declared here are like global house rules: everyone can see and use them from anywhere.
  • Be mindful of what you put here to avoid clutter and potential conflicts.

3. Local Scope (Function Scope):

  • Each function creates its own private room within the house.
  • Variables and functions declared inside a function are like personal belongings: only accessible within that room.
  • This keeps things organized and prevents unintended interactions.

4. Scope Chain: The Family Tree:

  • Functions can also access variables from their parent scopes (the functions that contain them), creating a hierarchy like a family tree.
  • JavaScript searches for variables up this chain if it can’t find them in the local scope, ensuring everyone has access to what they need.

5. Let’s Play with Scope!

  • We’ll experiment with code examples to see scope in action.
  • Observe how variables behave in different scopes and how the scope chain works.
  • Write code that demonstrates local and global scope, and try to visualize the scope chain.

6. Best Practices:

  • Embrace local scope whenever possible to keep code modular and avoid naming clashes.
  • Use global scope sparingly, reserving it for truly shared values.
  • Be mindful of scope when designing functions and interacting with variables.

7. Quiz Time!

  • Test your understanding with fun and interactive quizzes.

By the end of this tutorial, you’ll be a scope master, ready to write clear, organized, and predictable JavaScript code!

You decide to create a variable within the local scope while scripting a new JavaScript file. Is this variable accessible to code at the global scope level?

No

Correct. Variables created within the local scope cannot be read by code at the global scope level. They are accessible only to functions located within the local scope.

Scope is all about
code accessibility. It determines which
parts of the code are accessible and which
parts are inaccessible. For example, what variables can a function
access within code? Over the next few minutes, you will explore the
concept of scope and learn about how the scope chain
works within JavaScript. You will also explore some of
the different scope types, such as global and local. A nice way to think
about how scope works in JavaScript is a
two-way mirror glass. This is a piece of glass where only one side is transparent. For example, if a restaurant
uses two-way glass, people outside the restaurant
can’t see what’s happening inside but the people inside can see what
is happening outside. The process is similar to how
scope works in JavaScript. For example, the
code that exists outside of a function is
referred to as global scope, and all the code inside
of a function is known as local scope
or function scope. If a variable is defined
within a function, then you can say it’s
scoped to that function. This is also known
as local scope. For example, I could
define a variable named localvar and place
it within a function. I could then say that
this variable is scoped to the function
in which it was created. Each function keeps a
reference to its parent scope. This chain of scope
references is referred to as the scope chain. You’re now familiar
with scope and how the scope chain
works in JavaScript. You can also identify how some of the different
types of scope work, including global and local, also known as function scope.

Reading: The functional programming paradigm

Reading

Programming Assignment: Building a functional program

README.md

functionalprogramming.js

Video: Scoping with var, let and const

Here’s a summary of the video on variable scoping in JavaScript:

Key Concepts:

  • Scope: Determines which parts of code can access variables.
  • Global Scope: Variables declared outside functions, accessible throughout the program.
  • Local Scope: Variables declared within functions, accessible only within those functions (ES5).
  • Block Scope: Variables declared within blocks of code (using let or const), accessible only within those blocks (ES6).

Variable Declaration Keywords:

  • var (ES5):
    • Lenient scoping rules.
    • Can be used before declaration.
    • Can be redeclared.
    • Function-scoped or global-scoped.
  • let (ES6):
    • Stricter scoping rules.
    • Must be declared before use.
    • Cannot be redeclared.
    • Block-scoped.
  • const (ES6):
    • Similar to let but creates constants.
    • Value cannot be changed after assignment.

Best Practices:

  • Prefer let and const over var for modern JavaScript development.
  • Use let for values that might change.
  • Use const for values that will never change.

Key Differences:

Featurevarletconst
HoistingYesNoNo
RedeclarationYesNoNo
ScopeFunctionBlockBlock
MutabilityMutableMutableImmutable

Here’s a tutorial on variable scoping in JavaScript, designed to help you master this crucial concept:

Understanding the Playground of Variables:

Imagine a JavaScript program as a sprawling playground, where variables are the kids running around. Scope is like the rules that govern which kids can play in which areas. It determines where variables are accessible and how they interact with each other.

Types of Scopes:

  1. Global Scope: The entire playground! Variables declared outside of any function can be accessed from anywhere in the program. Think of them as the playground supervisors, always available.
  2. Local Scope (Function Scope): Individual play zones within the playground. Variables declared inside a function can only be accessed within that function. They’re like kids playing a specific game, only interacting with others in the same game.
  3. Block Scope: Temporary play areas marked by curly braces {}. Variables declared with let or const within blocks are only accessible within those blocks. They’re like kids joining a quick game of tag, only interacting within that short-lived activity.

Keywords for Declaring Variables:

  • var (ES5): The old-school way, with some quirks. Think of it as the relaxed playground where kids can roam freely, sometimes causing confusion.
    • Can be used before declaration (hoisted).
    • Can be redeclared.
    • Function-scoped or global-scoped.
  • let (ES6): The modern choice for most variables. It creates well-defined boundaries, keeping things organized.
    • Must be declared before use.
    • Cannot be redeclared.
    • Block-scoped.
  • const (ES6): For variables that need to stay constant, like the playground rules that never change.
    • Similar to let but creates constants.
    • Value cannot be changed after assignment.

Best Practices:

  • Prefer let and const over var in modern JavaScript. They offer better control and prevent unexpected behavior.
  • Use let for values that might change. It’s flexible when you need to update a variable’s value.
  • Use const for values that will never change. It protects variables from accidental modifications and makes your code more predictable.

Remember:

  • Scope determines where variables can play and who they can interact with.
  • Choose the right keyword (var, let, or const) to establish clear boundaries and avoid playground chaos!
  • By understanding scope, you’ll write more reliable, maintainable, and bug-free JavaScript code.
You are performing an update to some code and you need to create a variable named quantity, which calculates the total number of items. You need this variable to be accessible only inside a for loop. You declare the variable using the let keyword and it is within a for loop that performs the calculation of the total number of items. Does this variable declaration address your needs?

Yes

Correct. When you use let and const to declare a variable, it is scoped to the block – even within if statements and loops, like the for or while loops. Therefore, the quantity variable you create will only exist within the for loop.

You might recall that scope relates to code accessibility. It determines which
part of the code are accessible by different
parts of the program. In this video you will explore
scoping in more detail, and learn about two more
scope types and how they work with the keywords
var, let, and const. You may recall that all
the code outside of functions is referred
to as global scope, and all the code inside of a function is known
as local scope. Local scope states that
a variable is only accessible in the function
where it is declared. In the ES5 version
of JavaScript, only functions can
build local scope. The ES6 version of
JavaScript introduced a new variety of scope
known as the block scope. Block scope states that a
variable declared in a block of code is only accessible
inside that block. All the other code outside of the code block cannot access it. Block scope is built
when you declare variables using let or const. In other words when you build variables with let or const, they become
immediately scoped to the code block they
were created in. The scope of these variables is contained within
curly braces. For example, you can declare two separate variables
with the same name. If one is declared inside curly braces and
the other is not, you can then only access these variables
inside their scope. Before ES6, the
only way to declare a variable in JavaScript
was to use the var keyword. The var keyword is very lenient. Let’s outline some
characteristics of variables that are
declared with var. First, you can use it in your code even before
it is declared. Also, you can redeclare the same variable
when you use VAR. The variables are scoped
to a function R if they are declared outside the function their
scope is global. With ES6, the suggested
way to declare variables is to use the
let or const keywords. Its syntax is very similar
to the var syntax. Only the keyword is replaced. For example, let’s say
you want to declare a variable named user and assign it to a string set to
the value of Miranda. In ES5, you use the keyword var, the variable user,
the equal operator, and then the string value
Miranda inside double quotes. In ES6 with let and const, you use the same syntax, only changing the var keyword
to either let or const. Notice that the syntax
is very similar. You might be wondering what’s
the difference between var, let, and const. The simplest explanation is that the behavior of let and
const is more strict. With a let or a const variable, you cannot use it in your
code before you declare it. You can redeclare it using the variable keyword
like you can with var. Finally, it’s scoped
to the block, even within if
statements and loops, like the far or while loops. If you are new to JavaScript, it may be confusing as to
when to use either var, let, or const. A pro tip is to remember
it’s like this. Use let if the value might
change in the future, and use const if the
value will never change. In this video, you learned
how the scope of variables changes when you use the
keyword var in ES5 JavaScript, and when you use the
keywords let and const in ES6 JavaScript. Great job.

Video: Comparing var, let and const

Here’s a summary of the video on variable declaration keywords in JavaScript:

Key Points:

  • var (most lenient):
    • Can be accessed before initialization.
    • Can be redeclared.
    • Function-scoped or global-scoped.
  • let (more strict):
    • Cannot be accessed before declaration.
    • Cannot be redeclared.
    • Block-scoped.
    • Can be reassigned.
  • const (strictest):
    • Must be initialized on declaration.
    • Cannot be redeclared.
    • Cannot be reassigned.
    • Block-scoped.

Best Practices:

  • Prefer let and const over var in modern JavaScript.
  • Use const by default for variables that won’t change.
  • Use let for variables that need to be reassigned.

Additional Notes:

  • var variables can be accessed before their declaration due to a process called “hoisting.”
  • let and const variables are not hoisted.
  • const variables must be initialized with a value during declaration.

Choosing the Right Keyword:

  • Use const for values that should remain constant throughout the code.
  • Use let for values that may need to be updated later.
  • Avoid using var in modern JavaScript due to its potential for unexpected behavior.

Here’s a tutorial on variable declaration keywords in JavaScript, designed to help you master how to create and manage variables effectively:

Mastering the Art of Variable Creation:

In JavaScript, variables are like containers for storing data. But before you start filling them, you need to know how to create them properly. That’s where variable declaration keywords come in!

Keywords: Your Tools for Variable Crafting:

JavaScript offers three keywords for declaring variables: var, let, and const. Each has its own rules and best practices:

1. var (The Old-School, Lenient One):

  • Accessibility: Can be accessed before declaration (hoisted).
  • Scope: Function-scoped or global-scoped.
  • Redeclaration: Can be redeclared within the same scope.
  • Reassignment: Can be reassigned new values.
  • Modern Use: Generally avoided in modern JavaScript due to potential for unexpected behavior.

2. let (The Modern, Controlled One):

  • Accessibility: Cannot be accessed before declaration.
  • Scope: Block-scoped (accessible only within their enclosing curly braces).
  • Redeclaration: Cannot be redeclared within the same scope.
  • Reassignment: Can be reassigned new values.
  • Best Use: Used for variables that may need to be reassigned later.

3. const (The Constant Guardian):

  • Accessibility: Cannot be accessed before declaration.
  • Scope: Block-scoped.
  • Redeclaration: Cannot be redeclared within the same scope.
  • Reassignment: Cannot be reassigned after declaration.
  • Best Use: Used for values that should remain constant throughout the code.

Choosing Wisely:

  • Prefer const by default: It prevents accidental changes and makes code more predictable.
  • Use let for variables that need to be reassigned: This ensures proper scoping and avoids potential issues.
  • Avoid var in modern JavaScript: Its lenient behavior can lead to confusion and bugs.

Remember:

  • Choose the right keyword based on whether the variable’s value will change or not.
  • Understanding these keywords is crucial for writing clean, maintainable, and error-free JavaScript code!
Which one of the following statements is true when declaring variables using either var, let or const?

Variables declared with const must be assigned during declaration.

In this video, you’ll learn about the var,
let, and const variables and the different rules
that they are bound to. Let’s start with the var keyword. I’ve typed some example code that
is currently commented out but we’ll go through it one point at a time. A variable declared with the var keyword
can be accessed before initialization as long as the variable is eventually
initialized somewhere in our code. To confirm that, let’s try to console log
a variable that hasn’t been declared or initialized. I type console.log(user) and
click the Run button. This returns reference error. User is not defined which
is probably expected. However, suppose I use the var
keyword to declare the variable user as my last line of code and
rerun the code. Notice that undefined is output but
no error. This means that the JavaScript
engine continues to run. Let me clear my window here. And another thing to know about the var
keyword is that we can declare and redeclare the same var
variable without errors. Let me in comment lines 9-13
in my code to demonstrate. Notice that each line uses the var keyword
to repeatedly declare the user variable and assigns it to a different string
value Mary, Joanna, and finally, Mark. I’ll comment out line 15. When I run my code,
it outputs the first value undefined and then the value of the latest reassignment,
in this case the string Mark. Let’s move on to the let keyword. A key difference is that you cannot access
a let variable before declaring it. For example, in lines 4 and 5 suppose I run a console log on
the user variable as our first line. In that case, I get the reference error
cannot access user before initialization. What we can do however, is declare
an unassigned variable with let. Running a console log by uncommenting
lines 8 and 9 works without problems and returns undefined. However, once you declare a variable
threat, you cannot redeclare it. Trying to do so by uncommenting line
12 will produce the syntax error, identifier user has already been declared. While you cannot redeclare a let variable,
you can reassign it. For example, notice lines 8 and 15, initially it is set to undefined and
then to the string value of Anna. Now if I run my code, notice that undefined is output
first followed by the string Anna. Finally, let me switch
tabs again to demonstrate the const keyword which is the strictest. A const variable must be initialized. For example, on lines 4 and 5, you get the syntax error missing
initializer in const declaration. Next, let’s comment out lines 4 and
5 and uncomment lines 8 and 9. As you can see, you can access a const
variable before initialization or else you’ll get a reference here. Next uncommon line 9 as well as line 12. A const variable can’t be re declared as
it throws the type error assignment to constant variable. Okay, and that’s it for this video comparing variable
declaration using var, let and const. It might seem confusing at the beginning
to know which type to choose. Try to remember it like this. The Var keyword is the most lenient,
while the Const keyword is the strictest. The best choice and use,
usually depends on whether or not you will be reassigning values. In modern JavaScript,
I’d advise you to pick either let or const based on whether they
will be reassigned or not. Why not give it a try in
your own practice code?

Practice Quiz: Knowledge check: Introduction to Functional Programming

What will print out when the following code runs?

Variables declared using const can be reassigned.

When a function calls itself, this is known as _____________.

What will print out when the following code runs?

What value will print out when the following code runs?

Reading: Additional resources

Reading

Introduction to Object-Oriented Programming


Video: Introduction to object-oriented programming

Summary of Object-Oriented Programming (OOP) vs. Functional Programming:

Key Points:

  • Paradigms: OOP organizes programs using objects; Functional separates data and functions.
  • Example: Calculating shoe cost
    • Functional: Define variables, write function, call function with variables.
    • OOP: Create objects holding data and functions, access functions with dot notation.
  • Benefits of OOP:
    • Create multiple objects with similar functionality.
    • Reuse code with this keyword to avoid duplicate methods.
    • Use classes for efficient template-based object creation.

Overall Message:

OOP offers an efficient way to structure programs by grouping related data and functions in objects, allowing code reuse and efficient object creation through classes.

Additional Notes:

  • The video compares OOP and functional programming using the example of calculating shoe cost.
  • It highlights using the this keyword to avoid code duplication and introduces the concept of classes for efficient object creation.

I hope this summary is helpful! Let me know if you have any other questions.

Here’s a tutorial on Object-Oriented Programming (OOP) vs. Functional Programming, incorporating visuals:

Introduction:

  • Programming Paradigms: Different ways of organizing code to solve problems.
  • OOP and Functional Programming: Two popular paradigms with distinct approaches.

OOP (Object-Oriented Programming):

  • Key Concepts:
    • Objects: Encapsulate data (properties) and behavior (methods) into reusable units.
    • Classes: Blueprints for creating objects with similar characteristics.
    • Inheritance: Objects can inherit properties and methods from parent classes.
    • Polymorphism: Objects of different classes can respond to the same method call in different ways.
  • Example:

Functional Programming:

  • Key Concepts:
    • Functions: First-class citizens, treated like any other data value.
    • Pure Functions: Given the same input, always produce the same output (no side effects).
    • Immutability: Data cannot be changed after creation, new values are produced instead.
    • Recursion: Functions calling themselves to solve problems.
  • Example:

Comparison Table:

FeatureOOPFunctional Programming
FocusObjects and their interactionsFunctions and their composition
StateObjects can hold and modify stateData is immutable, new values are created
Code StructureOrganized around objects and classesOrganized around functions and data flow
ReuseThrough inheritance and polymorphismThrough higher-order functions and closures
Best Suited ForModeling real-world entities and complex systemsData processing, parallel programming, algorithms

When to Choose Which:

  • OOP: Well-suited for modeling real-world entities, GUI applications, and systems with complex interactions.
  • Functional Programming: Excels in data processing, parallel programming, and algorithms where correctness and predictability are crucial.

Conclusion:

  • Both OOP and Functional Programming offer powerful approaches to problem-solving.
  • Understanding their strengths and weaknesses is essential for choosing the right paradigm for your project.
  • Modern languages often support both paradigms, allowing developers to combine their best features.
You are coding in OOP style. Why would you want to use the "this" keyword?

To refer to the object itself without specifying the object’s name.

Correct. The “this” keyword is an alias for the name of the object.

In programming, there is something
known as the programming paradigms. You can think of this as a classification,
a style or just a general way to write code. You may already be familiar
with one of these paradigms. Functional programming, in this video,
you will learn about another popular one. The object oriented programming paradigm,
often referred to as OOP. OOP revolves around the idea of
organizing our programs using objects to group related data and functionality. This is in contrast to the functional
programming approach, where the data used in the app needs to be kept separate from
functions that operate on that data. Let’s explore this concept further using
some code examples from the two paradigms, suppose we are asked to write some
code that calculates the total cost of buying a pair of shoes. The code needs to calculate the total
price which is the shoes multiplied by the tax amount. To code this solution, you decide that you
need variables to store the values for shoes and tax and total price. You need a function which you
will call total price to perform the calculation of multiplying
the shoes by the tax. Finally, you need to be
able to output the result. Using the functional programming approach, you clearly separate a program’s data
from functions that work on that data. With the OOP approach, you create
an object and store all data related to that object including variables,
functions and output statements. For example,
you create an object named purchase one. You may recall that functions inside
objects are known as methods. Now that the purchase 1 object is created. You access the total price method on the
purchase1 object using the dot notation. Then, you invoke the total price
method which works with data inside the purchase 1 object and
returns the result of 120. In fact, you can access any data
that the purchase 1 object has. For example, using the dot notation, you can access the shoes price data and
the state tax data. An advantage to using the OoP approach
is that you can build as many objects as you need. For example, you can build another
purchase object and name it purchase2. Once created, you can also access
the total price method on the purchase2 object just like you did on
the purchase 1 object previously. You may notice, that the total price
method was almost the same in both the purchase 1 and the purchase 2 objects. This means that you can
improve the objects so that both methods are identical. And you can do that by using this
keyword which you may recall. It essentially means this object. It’s important to note that the code
still works exactly the same as before. Okay, so you may be wondering why did
I go through the trouble of updating the code of purchase 1 dot choose
price to this dot choose price. Well, the advantage here is that
rather than having to think about the name of the object whose shoes
priced property I’m trying to access, I just used the alias of the current
objects name, namely, this keyword. And now I can just copy the total price
method from the purchase 1 object and reuse it in the purchase 2 object. So, using that this keyword allows me
to not really care about the current objects name, which is an improvement
to the previous code I had. However, programmers are always eager to
avoid wasting resources when writing code. And coding a custom method on each
of the objects I built is wasteful. The solution to this is to code my
objects using some sort of a template. You will learn how to create this later
in this lesson using something called a class. For now, let’s explore object
oriented programming principles with the example of calculating the total
cost of buying a pair of shoes. Before starting, let’s first quickly
revisit another programming style. Functional programming, this should help you understand
the differences between the two paradigms. I start with var shoes equals 100 and I also add var state tax equals 1.2. Next, I declare a function, which returns the value of the shoes
multiplied by the value of the tax. This is written as function total price,
with shoes and tax in parenthesis. Inside of curly braces,
I add return shoes, asterix tax. Now, I’m declaring the variable to pay
which invokes the total price function and passes the shoes variable value as
well as the state tax variable value. Finally, I cancel log the to pay variable. When I run the code, the output is 120. So that’s an example of
the functional paradigm. But this time let’s build something
similar with the OOP paradigm. I go to a separate file where I
declare the variable, purchase 1 and store an object literal inside
of it with curly braces. I didn’t add the property shoes and
set it to 100, followed by state tax,
which is set to 1.2. The last property is total price, which is set to a function to
declare a calculation variable. This variable is equal to
the purchase1 dot shoes property multiplied by the purchase
1 dot state tax property. The 2nd part of the function
console logs the string total price along with the value
of the calculation variable. Online 10, I call the function with
purchase 1 dot total price parenthesis. Which I expect to return a value of 120. I run the code and
that’s indeed what I get. On another file, I’ll build another
OOP example, this one starts with the variable purchase 2, which has
the same structure as purchase 1. However, that shoes
value is changed to 50. In the total price function,
the calculation variable is updated to access the shoes and
state tax properties from purchase 2. When I invoked the total price
method on the purchase 2 object and run the code, It returns a value of 60. Between these two OOP examples,
you may have noticed that aside from accessing the shoes and state tax
properties in different objects,. The two methods are completely the same. This means that I can improve my objects
to make both methods identical while getting the same results. I can do this using the this keyword
which essentially means this object. Let’s move to another file,
to examine how that works. In this file,
I had the same purchase 1 and purchased 2 objects from before
with all of the same values. in the total price function of purchase 1, I replaced the references to
purchase 1 with the this keyword. I can then copy the total price
method from purchase1 and paste it into the purchase 2 object,
since they are now identical. I run this code and
it gives me a total price of 120 for purchase 1 and 60 for purchase 2. This is an improvement, over my original code from
the perspective of reducing waste. Instead of writing custom methods for
every object, this approach allows for
the reuse of existing code. However, although I’m
reusing the existing code, I’m now repeating the same method
on each new object that is built. That is wasteful and
programs need to be efficient. This is where making templates for
objects comes in. In JavaScript,
one of the most elegant ways to efficiently build new
objects is by using classes. Congratulations. In this video, you learned about
object orientated programming and how it differs from
functional programming. With the object orientated approach, you can code more efficiently
by reusing existing code.

Video: Classes

Here’s a summary of the video about classes in JavaScript:

Key Points:

  • Classes as Blueprints: Classes serve as reusable blueprints for creating objects with defined properties and methods.
  • Creating Classes:
    • Use the class keyword followed by the class name (capitalized).
    • Enclose the class definition in curly braces.
  • Constructor Function:
    • Used to initialize objects when they’re created.
    • Accepts parameters to set object properties.
  • Methods:
    • Functions defined within the class to perform actions on objects.
    • Called using dot notation on objects (e.g., objectName.methodName()).
    • Can accept parameters like regular functions.
  • Creating Objects (Instances):
    • Use the new keyword followed by the class name and parentheses to create objects.
  • Accessing Properties and Methods:
    • Use dot notation to access properties and methods of objects.

Example:

  • Car Class: Blueprint for creating car objects with properties like make, model, and color, and methods like turboOn().
  • Creating a Car Object: let car1 = new Car("Toyota", "Camry", "red");
  • Calling a Method: car1.turboOn();

Benefits of Classes:

  • Efficient Object Creation: Reusable blueprints for multiple objects with similar characteristics.
  • Code Organization: Enhances code structure and maintainability.

Here’s a tutorial on classes in JavaScript, incorporating visual aids:

Understanding Classes:

  • Blueprints for Objects: Think of classes as templates or blueprints that define the properties (data) and methods (behavior) of objects.
  • Creating Multiple Objects: You can use a single class to create multiple objects, each with its own unique values for the properties.

Creating a Class:

Syntax:

class ClassName {
    // Constructor function
    constructor(parameters) {
        // Initialize properties here
    }

    // Methods
    methodName() {
        // Perform actions here
    }
}

Example: Car Class:

class Car {
    constructor(make, model, color) {
        this.make = make;
        this.model = model;
        this.color = color;
        this.currentSpeed = 0;
    }

    accelerate(speed) {
        this.currentSpeed += speed;
        console.log(`Accelerating to ${this.currentSpeed} mph!`);
    }

    brake() {
        this.currentSpeed = 0;
        console.log("Stopped!");
    }
}

Creating Objects (Instances):

Use the new keyword:

let car1 = new Car("Toyota", "Camry", "red");

Each object is an instance of the class:

Accessing Properties and Methods:

Dot notation:

console.log(car1.make); // Output: Toyota
car1.accelerate(30);

Benefits of Classes:

  • Code Organization: Structures code logically and improves readability.
  • Reusability: Creates multiple objects with similar characteristics efficiently.
  • Maintainability: Easier to modify and update code within classes.

Additional Concepts:

  • Inheritance: Classes can inherit properties and methods from other classes.
  • Static Methods: Methods that belong to the class itself, not individual objects.
  • Getters and Setters: Control access to properties.

Practice:

  • Experiment with creating your own classes and objects to solidify your understanding.
  • Explore advanced concepts like inheritance and static methods to expand your knowledge.
You are working with classes in JavaScript. Which of the following instructions should you adhere to? Check all that apply.

Add a constructor function to accept your parameters.

That’s right. The constructor function assigns passed-in parameters to the future object’s properties.

Build your classes using the “class” keyword.

That’s right. Any class is built using the “class” keyword.

Create an instance of the class using the keyword new and that class’ name, followed by opening and closing parentheses, and optional arguments, based on how the class itself is defined.

That’s right. For example, if a class named Car doesn’t take any arguments, you’d instantiate it like this: new Car()

In programming there are situations where
you need to build many objects that have a certain specific set
of properties and methods. For example, you might need to
build hundreds of car objects for a car racing game. To code this efficiently,
you can use something called classes. They are essentially a blueprint that you
can repeatedly use to build new objects of a certain kind, as many times as you like. In this video,
you will learn about classes. In java script any class is built using
the class keyword, followed by the name of the class starting with a capital
letter and a pair of curly braces. Inside of the curly braces you have
the constructor function which accepts as many parameters as needed. The role of the constructor function
is to assign the passed in parameters to the future objects properties. It is the constructor function that is
used when instantiating new objects, instances of a given class. After the constructor is defined,
you add as many methods as you want. It’s important to remember that you
don’t use the function keyword here. Just the name of the method is needed. Once the class definition is ready,
you can start building the car object, now that you have instantiation
the car class and saved the instant of the class as car one. You have access to its methods and
properties. For example,
to access the turbo on method, you type the name of the object
which is car one, then the dot and then the name of the method
that exists on that object. In this example, the turbo on method,
with a pair of parenthesis to invoke it. When invoked, the turbo on method
will work with the available data in the car one object to produce its output. Like with regular functions, you can also
pass parameters to the class methods and then use them the same as
with regular functions. In this video,
you learned about classes and how they can be used to build multiple
object instances with specific properties.

Reading: Object Oriented Programming principles

Reading

Reading: Constructors

Reading

Video: Inheritance

JavaScript Inheritance: Prototypes and Class Syntax

This video delves into inheritance in JavaScript, focusing on the prototype-based model.

Key Takeaways:

  • Prototype: An object holding properties shared by other objects. These “children” inherit the prototype’s properties.
  • Inheritance Model: JavaScript uses prototypes for inheritance, not classical “class” inheritance.
  • Object.create(): Creates a new object with a specified prototype.
  • Property Lookup: JavaScript searches for properties first on the object itself, then on its prototype, and so on.
  • Overriding Properties: Children can define their own properties to override those inherited from the prototype. This affects only the child object, not the prototype or other children.
  • Class Syntax: A newer addition to JavaScript, offering a more familiar class-based syntax for inheritance, but still working with prototypes behind the scenes.

Examples:

  • bird object as prototype with properties hasWings, canFly, hasFeathers.
  • eagle1 and eagle2 objects created with Object.create(bird), inherit bird’s properties.
  • penguin1 created with Object.create(bird), but canFly set to false on penguin1 itself, overriding the prototype.

Conclusion:

Understanding prototype-based inheritance is crucial for JavaScript developers. While older methods involve Object.create(), newer class syntax provides a more familiar and streamlined approach, but still relies on the underlying prototype mechanism.

Welcome to the JavaScript Inheritance Workshop!

Here’s your guide to unlocking the secrets of JavaScript’s unique approach to object-oriented programming.

Unveiling Prototypes:

  • The Prototype Playground: Imagine a shared blueprint for objects, where common properties and behaviors reside. That’s a prototype! ️
  • The Inheritance Chain: Objects inherit from prototypes, forming a family tree of sorts.
  • Object.create(): The Prototype-Making Factory: Use this method to create new objects with a specific prototype, ensuring they inherit its traits.

Property Lookup: Following the Family Tree:

  • From Self to Ancestors: When JavaScript needs a property, it searches the object itself. If it’s not found, it looks up the prototype chain, like exploring a family history book.

Overriding Inherited Properties:

  • Redefining Traits: Child objects can have their own unique properties, even if they share a prototype. This is like a child inheriting blue eyes from parents but having a different hair color.
  • Local Overrides: These properties take precedence over inherited ones, just as a child’s unique personality might shine through family resemblance. ✨

Classes: The Familiar Face of Inheritance:

  • Class Syntax: A Modern Approach: JavaScript offers a class-based syntax that makes inheritance feel more like traditional OOP languages, but prototypes still work behind the scenes.
  • Under the Hood: Classes are essentially a syntactic sugar for prototype-based inheritance, making it easier to structure and organize code.

Key Points to Remember:

  • Prototypes are the heart of JavaScript’s inheritance model.
  • Understanding property lookup is essential for working with prototypes.
  • Classes provide a cleaner syntax but still rely on prototypes.

Now it’s time to practice and explore!

True or false? In JavaScript, you can use a prototype object to hold properties that can be shared with various other objects.

True

Correct! The prototype is an object that can have properties to be shared by multiple other objects.

In the real world, inheriting
something means acquiring possession, condition our trade from past generations. In this video you will learn that
inheritance also exists in JavaScript and the inheritance model revolves around
something called the prototype. You may also be familiar with the concept
of a prototype which is often referred to as an original model from
which other forms are developed. In JavaScript, the prototype is
an object that can hold properties to be shared by multiple other objects. And this is the basis of how
inheritance works in JavaScript. This is why it’s sometimes said that
JavaScript implements a prototype of inheritance model. Let’s explore this further now, with some code examples to demonstrate
inheritance and how to build a prototype. Consider the following object. I’m setting the var bird to
an object that has three properties. Each set to the boolean value of true. The properties are has wings can fly and
has feathers. Using the readily available object create,
I can construct new objects. For example, I’ve set the eagle1 variable
to a call that takes the bird object and passes it to the object .create method. I can console log the contents
of the eagle1 object now. Let’s run the code and notice an empty
object logged to the console. However, since I used object to create
to instantiate the eagle1 object. I also have access to all
the properties of the bird object. So I canceled log eagle1 has wings and
pass eagle1.has wings. And I also console log eagle1 can fly and
pass eagle1.can fly. And finally eagle1 has feathers
passing it eagle1.has feathers. Let’s read from the code once again
notice eagle1 has wings true, eagle1 can fly true and
eagle1 has feathers true. Our output to the console with
the object creates syntax. I can build as many objects as I want and they will all have the bird
objects as their prototype. Here, notice that I built
an eagle2 object and I’ve used the bird object as a prototype. Because I ran the object
.create method on it and I save everything to the eagle2 variable. It’s important to understand
that the eagle2 object also has access to the property stored
on the bird object as its prototype. Let’s run this code to confirm and indeed notice that eagle2 has wings
true is output to the console. I can even add different objects
with different behaviors. For example, I can add a penguin1 object. I do this by declaring
a penguin1 variable and assigning the result of
the object .create method to it. Penguins are flightless birds so I want
to set the can fly property to false. Thankfully, this is a relatively
straightforward process because JavaScript starts from the object itself when
looking for properties to work with. Then if it can’t find it on the object,
it looks up to its prototype. It’s important to remember that it doesn’t
look further if it finds the property on the immediate object. This makes for a simple mechanism for
overriding inherited properties. So let’s implement this now. First I set that can fly property
on the penguin1 object to false. And now I can cancel log
that penguin1 object. Notice the output to the console
after running the code is that penguin1 is an object with a can
fly property set to false. Additionally, I can still access all
the properties of the prototype. So accessing that has feathers and
can fly properties of penguin1 will return the values that are stored on
the prototype when I run the code. However, the can fly property is now
set on the penguin1 object itself, so it overrides the can fly
property on the prototype. This override only affects
the penguin1 object, it doesn’t change my prototype or
other eagle objects. In this video, you learned about
inheritance in JavaScript, although it is possible to build inheritance
using the object create method. It’s probably better to use class syntax
for more complex objects and inheritance. Although under the hood,
this syntax still works with prototypes. It makes sense to use classes as
they improve developer experience in more complex scenarios.

Reading: Creating classes

Reading

Reading: Default Parameters

Reading

Reading: Designing an OO Program

Reading

Programming Assignment: Building an object-oriented program

README.md

ooprogramming.js

Practice Quiz: Knowledge check: Introduction to Object-Oriented Programming

What will print out when the following code runs?

When a class extends another class, this is called ____________.

What will print out when the following code runs?

What will print out when the following code runs?

What will print out when the following code runs?

Reading: Additional resources

Reading

Advanced Javascript Features


Video: De-structuring arrays and objects

Here’s a summary of the key points about destructuring in JavaScript:

Understanding Destructuring:

  • It’s a way to extract specific values from objects or arrays and create new variables from them.
  • Imagine a project folder: Destructuring is like copying a file from that folder to a separate location.
  • The original item remains in the folder, but the copy is independent.

How It Works:

  • Use the let keyword and curly braces to target desired properties.
  • Example: let { PI } = Math; extracts the PI property from the Math object into a new variable named PI.
  • Case-sensitivity matters: let { pi } = Math; would return undefined because pi doesn’t exist on Math.

Key Characteristics:

  • Independence: Destructuring creates a separate copy, not a reference.
  • No Connection: Modifying the dstructured variable doesn’t affect the original property.
  • Array Destructuring: Works similarly to extract elements into individual variables.

Example:

  1. let { PI } = Math; creates a copy of Math.PI in PI.
  2. PI === Math.PI initially returns true.
  3. Changing PI to 1 doesn’t affect Math.PI.
  4. PI === Math.PI now returns false, proving their independence.

Remember:

  • Destructuring is a powerful tool for working concisely with objects and arrays in JavaScript.
  • It can simplify code and make it more readable.

✨ Welcome to the De-structuring Arrays and Objects in JavaScript Tutorial! ✨

Here, you’ll unlock a powerful technique to extract specific values from arrays and objects, creating new variables in a clean and concise way.

Let’s dive in!

What is Destructuring?

  • It’s like carefully unpacking items from a box and placing them on individual shelves.
  • You select specific values from a collection (array or object) and assign them to new variables.
  • It’s often used to simplify code, make it more readable, and avoid repetitive property/element access.

De-structuring Objects:

Syntax:

let { property1, property2, ... } = objectToDestructure;

Example:

let person = { name: "Alice", age: 30, city: "New York" };
let { name, age } = person;  // Extract name and age into separate variables
console.log(name);  // Output: "Alice"
console.log(age);   // Output: 30

De-structuring Arrays:

Syntax:

let [element1, element2, ... ] = arrayToDestructure;

Example:

let numbers = [10, 20, 30];
let [first, second] = numbers;  // Extract first two elements
console.log(first);  // Output: 10
console.log(second); // Output: 20

✨ Advanced Features:

Default Values:

let { city = "Unknown" } = person;  // If "city" is missing, assign "Unknown"

Ignoring Values:

let { name, _ } = person;  // Extract name, ignore other properties

Destructuring in Functions:

function greet({ name, age }) {
    console.log("Hello, " + name + ", age " + age + "!");
}
greet(person);  // Pass the object directly

Benefits of Destructuring:

  • Cleaner, more concise code
  • Enhanced readability
  • Improved variable naming
  • Efficient value extraction
  • Flexible data manipulation

Practice and Explore:

  • Experiment with different examples.
  • Combine destructuring with other JavaScript features.
  • Discover creative ways to leverage its power in your projects!

Have you ever needed to apply
the formatting of text in a word processor from one portion of text to another. In essence you are copying the properties
from some text that is already formatted and applying them to another
piece of text that you want to format. In a similar way as with text, JavaScript objects can have properties
that define their characteristics. In this video, you will learn
how to D structure, objects and arrays and
also how to use the D structuring syntax, to extract new variables from objects and
arrays. To illustrate D structuring,
imagine that an object or an array is like a project folder that you have on
your computer with several files in it. D structuring something out of an object
or array, in this case your project folder is like copying that item from your
folder on to another location. The original item still exists
in your project folder. I just made a copy of
the original item but this copy is completely
independent of the original item. Now let’s explore an example with
an existing built in math object to D Structure the value of phi from it. Let’s start by using the LET keyword and surround the uppercase Pie in curly
brackets equals math because I already know that the pie property
exists on the math object. I make a copy of it and I save
the new object in a separate variable. I name Pie. Note that I can only destruction
something that already exists on an object using faulty spelling,
including lower case won’t work and will return an undefined value If I
type let open curly bracket small case pi close curly bracket equals
math pi returns as undefined. This is because there isn’t a lowercase
pi property on the math object. So when I try to destroy culture it,
I get the value of undefined for the lower case pi variable. The next step is to confirm that all caps
pi variable has the identical value and data type as math dot pi by using the
triple equal strict comparison operator. This will return a value of true to
prove that the D structured property and the original property
are in no way connected. I update the value of
the pie variable to be one. By Typing Pi equals one. I can now compare all caps pie and
math dot pi again by typing pie, triple equal sign, math dot pi, thus
getting back the boolean value of false. It’s clear that these two
are no longer the same. The only reason why this worked is because
the original property on the object and the D structured value
are not connected in any way. In other words, there’s no connection
between the d structured variable and the source property on the given object. In this video, you covered how to de
structure objects and erase and also how to use the D structuring syntax to extract
new variables from objects and arrays

True or False. In JavaScript, it's possible to extract the properties from objects into distinct variables using destructuring.

True

Correct. In JavaScript, it’s possible to extract the properties from objects into distinct variables using destructuring.

Reading: For of loops and objects

Reading

Video: For- of loops and objects

Here’s a summary of the video:

Key points:

  • for…in loops: Iterate over an object’s own properties and its prototype’s properties, making them potentially unreliable for targeting only object-specific properties.
  • for…of loops: Iterate exclusively over an object’s own properties, disregarding its prototype.

Demonstration:

  • An object named car with properties engine, steering, and speed is created.
  • A sportsCar object inherits from car using Object.create.
  • A for...in loop on sportsCar logs both its own speed property and the inherited engine and steering properties, highlighting its inclusion of prototype properties.
  • A for...of loop on sportsCar logs only its own speed property, demonstrating its focus on object-specific properties.

Simplified example:

  • A simplified version reinforces the key concepts using a car object with only an engine property and a sportsCar object inheriting from it.
  • The for...in loop again logs both speed (from sportsCar) and engine (from the prototype), while the for...of loop logs only speed.

Conclusion:

  • When iterating over objects in JavaScript, use for...of loops to reliably target only the object’s own properties.
  • Use for...in loops cautiously, being mindful of their inclusion of prototype properties.

Navigating Objects with Precision: A Guide to For…of Loops in JavaScript

In the realm of JavaScript, where objects reign supreme, understanding how to effectively loop through their properties is essential. While for…in loops have their place, for…of loops offer a more focused and reliable approach when working with objects directly.

In this tutorial, we’ll explore the distinctions between these loops and how to confidently use them to navigate object properties.

1. Understanding the Key Differences

  • for…in: Iterates over all enumerable properties of an object, including those inherited from its prototype chain. This can be useful for exploring an object’s full structure, but it’s important to be aware of the potential inclusion of prototype properties.
  • for…of: Iterates exclusively over the object’s own enumerable properties, disregarding any inherited ones. This provides a more precise and predictable way to focus on the object’s specific attributes.

2. Syntax and Usage

for…in:

for (const property in object) {
    console.log(property, object[property]);
}

for…of:

for (const value of object) {
    console.log(value);
}

3. Examples in Action

JavaScript

const car = { engine: true, steering: true, speed: "slow" };
const sportsCar = Object.create(car);
sportsCar.speed = "fast";

// for...in loop (includes prototype properties)
for (const prop in sportsCar) {
  console.log(prop); // Output: "speed", "engine", "steering"
}

// for...of loop (only object's own properties)
for (const prop of sportsCar) {
  console.log(prop); // Output: "speed"
}

4. When to Use Each Loop

  • Use for…of:
    • When you want to iterate over an object’s own properties directly.
    • When you need to avoid prototype pollution and ensure predictable results.
    • When working with arrays or iterables in general.
  • Use for…in:
    • When you need to explore the full hierarchy of an object, including inherited properties.
    • When working with objects for key-value mapping or property enumeration.

5. Key Points to Remember

  • for…of loops are generally preferred for iterating over object properties due to their accuracy and predictability.
  • for…in loops can be useful for specific scenarios, but be mindful of their inclusion of prototype properties.
  • Choose the appropriate loop based on your intended use case and desired level of property inclusion.

By mastering for…of loops and understanding their distinction from for…in loops, you’ll gain greater control and precision when navigating objects in JavaScript, ensuring you work with the exact properties you need.

When working with objects, the for-of loop and for-in loop can be used to iterate over the object's properties. Which of the following statements are correct? Choose all that apply.
  • The for-of loop will iterate over the object’s own properties only when using the Object.keys() method to return an array to loop over.
  • The for-of loop will not iterate over the object and its prototype properties.

In this video, I’ll help you
understand the difference between for and loops
and for of loops, when applied to
objects in JavaScript. At first, this code
may appear complex, but you’ll find that
it only involves concepts that you’ve
dealt with before. Let’s begin by breaking
down what I have. I have a concept to an object and assign to a
variable named car. This object has three
properties, engine, steering and speed, which
are given the values true, true, and slow respectively. I also have a cost assigned
to the variable sports car, and I’ve used Object.create, so that inherits the properties
of the car variable. Then I set the speed
property of the sports car to fast and save it to
the sports car variable. I’ve also added a console
log to display the string, the sports car object, followed by the properties
of the sports car object. Next, I have two for loops. The first one is a
for-in loop written to log the properties of
the sports car object. This is typed as for, followed by properties and
sports car in parentheses. Inside of curly braces is
a console log for prop, so it displays the properties
of the sports car. Before and after the
foreign loop code, I’ve written console
logs to print some comments which will be addressed after I run my code. My second for loop uses the object keys method
on my sports car object, which should iterate
over that object. This is typed as for, followed by prop of objects, dot keys, sports car
inside of parentheses. Inside of the curly braces is a console log for
prop plus a colon in double-quotes and sports car with prop enclosed
in square brackets. I’ve also console logged
another comma after this code. When I run this code, I get the output. The sports car object
is speed fast. It also displays a
comment I had in the code for in is unreliable. Let’s explore why. From the for-in loop, the console log values
might surprise us. It loops over the property
in the sports car object, but the output includes
the properties on the sports car’s prototype too. Instead of just a
speed property, I also looped over the
engine and steering properties which exist on the prototype of the
sports car object, not on the sports
car object itself. In fact, as the common state, for in loops are unreliable
in this scenario because they iterate over not only
the specified object, but also its prototype. That’s why I used a thinking
emoji in my comment with a string iterating over
objects and its prototype. Now, let’s examine what came
from the second for loop, which is a for of loop. Note that our output,
the comment I had in the code for of is reliable. I’ve gotten back speed
fast, or in other words, the property and value that I’ve assigned to the
sports car object. Just as I have stated in
the comment in my code. This is because a for of
loop only iterates over the object’s own properties and does not count the
prototype at all. Hopefully, you are able
to differentiate between the for in and the for
of types of loops. Let’s run a
simplified version of the same code without
the comments. Also show my other file. This time around my
car object only has an undrawn property
then I’m declaring the sports car variable
and I’m setting the car object as the
sports car prototype. I’m also setting the speed
of the sports car as fast. Finally, I’m console logging the sports car
object and looping over prop and sports car and props of object keys
and sports car. In summary, the two
loops are simplified. I’m only console logging a
thinking emoji and the props value for the first
loop, the foreign loop. I’m only console logging
a bull’s eye emoji and the provenance value
in the for of loop. That is the second
loop in my code. When I run the code again, the result is much simpler. First, I confirm that the
sports car object only has one single property
speed, which is fast. Then the for in loop
displays speed and engine, because engine belongs
to the prototype of the sports car object and not the sports car object itself. Finally, the for of loop outputs looping over only the sports
car object properties, which in this case is
only the property fast. The emojis from my
code up here alongside these properties and help us to understand what they mean. Just to sum it up, the speed and engine properties are
from the foreign loop because it draws from
the prototype of the sports car object as
well as the object itself. The speed fast
property, however, comes from the for of loop, since that iterates over the sports car objects
property only. In this video, you learn
that when you run on objects in JavaScript
for in loops, iterate over the properties of the object and its prototype. While for of loops do this only for the
objects’ properties.

Reading: Template literals examples

Reading

Video: Working with template literals

Here’s a summary of the video on template literals in JavaScript ES6:

Key Points:

  • Template Literals: A new way to create strings in ES6, using backticks (`) instead of single or double quotes.
  • Multiline Strings: Template literals allow strings to span multiple lines without errors, unlike ES5 methods.
  • Variable Interpolation: Embed variables directly into strings using ${variableName} syntax, eliminating concatenation with ‘+’.
  • Quote Flexibility: Quotes within template literals are treated as regular characters, not string delimiters.

Benefits:

  • Enhanced Readability: Multiline strings improve code readability and maintainability, especially for longer text blocks.
  • Easier Concatenation: Variable interpolation streamlines string building, making code more concise and expressive.
  • No Escaping Quotes: Eliminates the need to escape quotes within strings, simplifying syntax and reducing errors.

Example:

JavaScript

let first = `I'm a string with "quotes"`;
let second = `And I'm another one`;
let combined = `Here's a message with ${first} and ${second}.`;
console.log(combined);

Output:

Here's a message with I'm a string with "quotes" and And I'm another one.

Conclusion:

Template literals offer a powerful and flexible approach to string creation in JavaScript, enhancing code readability, maintainability, and expressiveness. Embrace them for a better coding experience!

Tutorial: Mastering Template Literals in JavaScript ES6

Unleash the Power of Strings with Backticks!

Introduction

Greetings, fellow coders! Ready to explore a more elegant and flexible way to create strings in JavaScript? ES6 introduces template literals, a game-changer that’ll make your code more readable, maintainable, and expressive. Let’s dive in!

What Are Template Literals?

  • Backticks Enclose Them: Instead of single or double quotes, template literals are enclosed within backticks (`), usually located above the Tab key.
  • Multiline Magic: Write strings across multiple lines without errors or concatenation hassles!
  • Embed Variables Seamlessly: Use ${variableName} within the template literal to inject variables directly into the string.
  • Quote Freedom: Quotes within template literals are treated as regular characters, not string delimiters. No more escaping needed!

Key Advantages:

  • Enhanced Readability: Multiline strings make code more readable and easier to maintain, especially for longer text blocks.
  • Concise Concatenation: Variable interpolation streamlines string building, eliminating the need for ‘+’ operators.
  • Simpler Syntax: No escaping quotes means cleaner and less error-prone code.

Example Time:

JavaScript

let greeting = "Hello";
let name = "Bard";
let message = `${greeting}, ${name}! Welcome to the world of template literals.`;
console.log(message);

Output:

Hello, Bard! Welcome to the world of template literals.

Common Use Cases:

  • Multiline Strings: Formatting texts for better readability.
  • Building Dynamic HTML: Creating flexible HTML elements with variables.
  • Constructing URLs: Assembling dynamic URLs with ease.
  • Generating Code: Crafting code blocks or templates dynamically.

Tips and Tricks:

  • Whitespace Preservation: Template literals maintain original whitespace, including indentation and spacing.
  • Tagged Templates: Advanced feature for custom string processing (explore this later).

Conclusion

Template literals offer a powerful and versatile approach to string creation in JavaScript. Embrace them to write cleaner, more expressive, and maintainable code!

Image: [Illustration of code blocks with template literals, highlighting backticks, multiline strings, and variable interpolation]

In what ways can template literals be used to write JavaScript code more efficiently? Check all that apply:

You can create multi-line strings. You can interpolate variables. You can combine strings with less code.

Correct! Template literals can be used to create multi-line strings, interpolate variables, and to combine strings with simpler code.

In this video, I’ll guide you
through creating and using template literals
in JavaScript ES6 to understand their benefits. First, let’s revisit
strings in JavaScript ES5, which are built using single
quotes or double quotes. I have an example in my code, I’ve declared a variable, no multi-line with
the let keyword, which holds the string value, no multi-line strings in ES5. On the following line, I’m using the
console.log method to output the string did you know, followed by the
plus operator and then finally the no
multi-line variable. Recall that you can use the plus operator
for concatenation. When I run the code, I get the expected output
of did you know, no multi-line strings in ES5. This time, let’s change the value of the no
multi-line variable. To do this, I place my
cursor after the word no and press the Enter key to move part of the string
to a second line. This now spans the string
over multiple lines. If we were to run this code now, we would get the error. Also, notice that VS Code is trying to warn
us about this error by highlighting the end
of lines 3 and 4 with red text and displaying the message unterminated
string literal. This is basically JavaScript telling us that our
single line string is not coded correctly with the expected closing
double quotation symbol. Using ES5 methods, you can only create
strings using single or double
quotations and using this method does not support the use of multi-line strings. Next, let me clear the output and switch tabs in my code. Here we have some syntax that
may be unfamiliar to you. We have a variable multi-line declared with the let keyword
and it contains a string. Like the previous example, this string is distributed
across several lines. However, instead of quotes, it’s encased within
a pair of backticks. This turns it into
an ES6 expression known as a template literal. The backtick symbol is
usually located above the tab key to the left of
the one key on your keyboard. Still, it’s a good idea
to check your devices documentation as you may be using a different
keyboard layout. Using template
literals, you can add as many lines as you want
without causing errors. I can confirm this
by running my code. Notice that the output
is a multi-line string. But wait, it gets better. We can combine
template literals with variable interpolation for
even more flexibility. Once again, let me clear the output and continue
to the next tab. Here, notice I have two variables called
first and second, each containing a
single line string encased in backticks. But there’s a twist here. Each string also has a segment that sits
inside of quotes. Wouldn’t this cause
conflict you might wonder? Fortunately, that’s
not the case. By using template literals, JavaScript does not
consider quotes, a string delimiters, meaning they are just
regular characters here. Now I can use template
literals again to interpolate the variables first and
second on a different line. Instead of using the plus
operator for concatenation, I can simply enclose the full desired string
within backticks. I can then place the variable
name by enclosing it within a set of curly braces
preceded by a dollar symbol. If I run this code, JavaScript combines
everything and outputs the full string. With template literals you
don’t need to worry about the limitations of using
single and double quotes. This can make for a much
better coding experience as you just need to use backticks and variable
interpolation. That’s all for this video. Well done, you learned how to build then apply
template literals to create multiline strings and interpolate variables
in JavaScript.

Programming Assignment: Array and object iteration

README.md

solution.js

Video: Data Structures

Summary of JavaScript Data Structures for Beginners:

Problem: How to write a program to calculate average grade from test results?

Key Points:

  • Data structure choice: Before coding, consider how to represent data efficiently.
  • JavaScript data structures: Arrays, objects, maps, and sets.
  • Objects: Unordered key-value pairs, useful for storing and accessing data under specific keys (e.g., object-oriented programming).
  • Arrays: Ordered collections of values, accessed by index, ideal for iterating and modifying data.
  • Maps: Ordered key-value pairs, similar to arrays but any value can be a key (unlike objects limited to strings or symbols).
  • Sets: Collections of unique items, adding duplicates has no effect, useful for checking for unique values.

Takeaway:

  • The data structure you choose should fit the task and improve code efficiency.
  • Consider different structures like arrays, objects, maps, and sets when solving any coding problem.

Next Up:

Applying these data structures to solve specific coding tasks.

JavaScript Data Structures 101: Organize Your Code Like a Pro

Welcome to the world of JavaScript data structures! In this tutorial, we’ll explore how to organize your code efficiently and strategically using JavaScript’s fundamental building blocks: objects, arrays, maps, and sets.

Why Data Structures Matter

Imagine your JavaScript code as a bustling city – data structures are like the buildings that house and manage its residents (data). Choosing the right structure is essential for:

  • Efficiency: Finding the data you need quickly and easily, just like navigating to the right building in a well-planned city.
  • Maintainability: Keeping your code organized and understandable, making it easier to update and expand in the future, like a city with clear road maps.

Meet the JavaScript Data Structure Squad

Here are the key players you’ll encounter:

  1. Objects:
    • Unordered collections of key-value pairs, like a phonebook where names are keys and numbers are values.
    • Ideal for storing related information and accessing it by specific keys.
    • Example: Creating a student object with properties like name, age, and grades.
  2. Arrays:
    • Ordered lists of values, like a numbered row of houses on a street.
    • Perfect for storing sequences of items and accessing them by their position in the list (index).
    • Example: Keeping a list of studentNames in an array to iterate through them.
  3. Maps:
    • Similar to objects, but with more flexible keys – any value can be a key, not just strings or symbols.
    • Useful for quick lookups when you need to associate unique keys with values.
    • Example: Storing a map of student names and their favorite colors.
  4. Sets:
    • Collections of unique values, like a unique set of keys to unlock different houses.
    • Ensure each item is present only once, helpful for checking for duplicates or removing duplicates.
    • Example: Keeping a set of unique student email addresses.

Choosing the Right Structure for the Job

Here’s a quick decision guide:

  • Need to store key-value pairs with string or symbol keys? Use an object.
  • Need to store a sequence of items in order? Use an array.
  • Need more flexible key-value pairs with any value as a key? Use a map.
  • Need to ensure unique values in a collection? Use a set.

Practice Makes Perfect

Ready to put these structures to work? Here are some exercises to get you started:

  • Create an object to represent a pet with properties like name, species, and age.
  • Create an array to store a shopping list and practice adding, removing, and sorting items.
  • Use a map to store a collection of words and their definitions, allowing for non-string keys.
  • Use a set to keep track of unique visitors to a website.

Remember, data structures are the foundation of efficient and organized code. By mastering these essential JavaScript structures, you’ll unlock a whole new level of coding prowess!

Which one of these data structures consists of iterable key-value pairs?

Maps

That’s right! Maps are made up of iterable key value pairs.

Suppose you receive some data on students
test results and your task is to write a program that outputs an average grade
from all the tests based on the raw data. Before you can code this task,
you need to consider two separate issues. First, how do you represent
the given data in your app and second, how do you called the solution? Before you even start coding a solution, you need to think about how
you will represent the data. In this video, you will learn about
some of the JavaScript’s most common data structures such as objects,
arrays, maps and sets. A data structure is
a way to organize data. For example,
you could represent it as a string. However, it would be somewhat
of a strange representation. You’d need to somehow extract the numbers
from the string before performing calculations on them. Alternatively, you could
represent it as several numbers, each number saved in a variable. Doing it this way you don’t have to
extract and convert strings to numbers. But is this the most efficient
way of storing your apps data? Perhaps another approach would be to
store all the grades in an array. This way of organizing your
data is even more efficient. It involves less typing and we’re grouping related data
together under a single label. You may recall the many
benefits of using a arrays. But what is important here is
that you understand how you code a solution to a given task depends
on how you structure your data. In other words, a solution to a coding task depends
on the data structure you use. JavaScript is somewhat limited in
the types of data structures available compared to other programming languages,
such as, Java or Python. However, some of the most common that
you will encounter are objects arrays, maps and sets. You may be familiar with
some of these already. Let’s explore each briefly. Now you may recall that
an object is unaltered, noniterable collection
of key value pairs and you use objects when you need to store and
later access a value under a key. An example of using this data
structure is when you need to write object orientated, R00P code. Similarly, you may also recall
an array which is an ordered iterable collection of values. Likewise, you use arrays
when you need to store and later access a value under an index. And remember, we do not specify the index,
JavaScript does this automatically. You only use the index to access
the specific value stored in the array. When working with arrays,
it’s common to use a loop, such as a for loop to access and edit the data. For example, to find the average grade for
the task earlier, you could loop over the array and
calculate the total sum. Then after the for loop, calculate the average by dividing
the sum by the length of the array. The next data structure is map which
is like an array because it’s iterable. However, it consists of key value pairs. It’s important not to
confuse a map with an object. With maps any value can be used as a key. With objects,
keys can only be strings or symbols. Finally, the last data structure I
want you to know about is a set. This is another collection where each
item in the collection must be unique. For example, if you try to add
a non unique item to a set, this operation will simply not be run. In other words, no errors will be thrown
and no updates will be made to a set. In this video, you learned about some of
JavaScript’s most common data structures, such as, objects, arrays, maps and sets, which one you need to use
depends on the task at hand. Next time you have a coding task, try to think of the data
structures you might use.

Reading: Data Structures examples

Reading

Video: Spread operator

Summary of the Spread Operator in JavaScript:

What it is:

  • Introduced in ES6.
  • A “magical tool” for spreading array items and joining objects.
  • Represented by three dots (…).

Benefits:

  • Simply copies object properties to create new objects.
  • Concisely passes all array elements to functions.
  • Avoids manual listing of individual array elements.

Example:

  • Function takes three arguments for places to visit (place1, place2, place3).
  • Calling the function with individual array elements is tedious.
  • Using the spread operator before an array name (…arrayName) simplifies the call.

Conclusion:

  • Spread operator makes code cleaner and more efficient.
  • Applicable to both arrays and objects.
  • A valuable tool for modern JavaScript development.

Mastering the Spread Operator in JavaScript: A Practical Guide

Welcome to the Spread Operator Playground! ✨ Get ready to unlock the power of this versatile tool, which can transform your JavaScript code into a masterpiece of efficiency and elegance.

Here’s the itinerary for our journey:

1. Unveiling the Spread Operator:

  • Introduction: Meet the spread operator (…), a versatile tool introduced in ES6 that streamlines array and object manipulation.
  • Syntax: Master its simple yet powerful syntax: three dots placed before an array or object.

2. Spreading Out Arrays:

  • Expanding Arrays: Effortlessly combine multiple arrays into a single array, as if by magic!
  • Passing Elements to Functions: Conquer the challenge of passing all array elements as individual arguments to functions—the spread operator handles it gracefully.
  • Creating New Arrays: Craft new arrays with ease, featuring elements from existing arrays and additional items.

3. Merging Objects:

  • Combining Properties: Seamlessly merge properties from multiple objects into a new object, preserving data integrity.
  • Copying Objects: Safely create copies of objects without altering the originals, ensuring data consistency.

4. Advanced Adventures:

  • Rest Parameter: Harness the power of the spread operator to gather remaining function arguments into an array, embracing flexibility.
  • Destructuring Assignment: Extract specific elements from arrays or objects with precision, using the spread operator in destructuring patterns.

5. Hands-On Practice:

  • Interactive Exercises: Reinforce your understanding through engaging coding challenges, designed to solidify your skills.
  • Real-World Examples: Discover how the spread operator enhances code readability and maintainability in practical scenarios.

6. Mastering the Spread:

  • Key Takeaways: Revisit the essential concepts and benefits of using the spread operator.
  • Creative Applications: Explore diverse use cases and unleash your imagination to apply this powerful tool in innovative ways.

Ready to embark on this exciting adventure? Let’s spread the knowledge and transform your JavaScript skills!

The spread operator allows you to pass all array elements into a function without having to type them all individually. Is this true or false?

True

Correct! The spread operator will include all of the array elements with much less code.

The spread operator
is another of the many great new
editions that came to the JavaScript language
in its ES6 update. It is the shortest and
simplest method to copy the properties of an object
onto a newly created object. Think of the spread operator as a magical multi-purpose
tool that can spread out array items and
join objects together. In this video, you
will explore what the spread operator
is and how to use it. Note that the spread operator is characterized by three dots. To illustrate where the spread
operator becomes useful, let’s first build an array and then call the items
with a basic function. Using the variable keyword let, I create an array of the top
three places to visit on a holiday to Rome
and I call it top3. Then I include the
Colosseum, Trevi Fountain, and the Vatican City as the elements of
my top three array. Now I write a function that lists these three attractions. To keep it simple, I just
log it into the console, I create a function
and I name it, showItinerary with
three arguments, place1, place2, place3. Now I console log the
three places to visit by typing console.log and
then the string Visit, and the first argument, place1. Next, I console log the other two arguments by
first using the strings, then visit, and the
argument place2. Then the string finish
with a visit to, and the third argument place3. Then when I run the function showItinerary it should run
through all three places. Now, let’s try to run the showItinerary function with the elements in the top3 array. I write the function
name, showItinerary, and each array element
starting with top3, open square bracket zero, which is the first
element in the array, and close square bracket. Then I do the same for the other array
elements one and two. But what if I
extended my function to have seven places
that I want to visit? Let’s disregard what the showItinerary function
definition may show and imagine that I have made the necessary updates so that the function will
handle seven arguments. I have now built an
entirely new array of the top seven destinations, and I’ve saved it in a
variable named top7. Now I call the
showItinerary function and passing this function, the seven arguments
again start with zero as in top7 and zero within
square brackets. Then the array again, top7 and number one within
square brackets, and so on until we get to the last top seven
array element, which is top7 and number
6 within square brackets. While this code will work, it seems a bit impractical the spread operator simplifies
things. Let’s try it now. I type the showItinerary
function, then open parenthesis, three dots, top7, close parenthesis,
semicolon, that’s it. I use the spread operator
by placing it in front of an array which is passed to the showItinerary function. The advantage of
this approach is that you don’t have to list each individual member of the array that you want
to pass to your function. The syntax is clear, concise, and easy to type. Now, if I go back
to the top3 array, I can use it with the spread operator just like I used it for the top7 array. I type the showItinerary
function and the three dots and
the array name, top3 within parenthesis and
I end with a semicolon. The function returns
the combination of the strings and the
variables I used earlier, visit the Colosseum, then visit Trevi Fountain and finish with a visit to
the Vatican City. In this video, you explored what the spread operator is
and how you can use it.

Video: Rest operator

Summary of the Rest Operator in JavaScript:

What it is:

  • Used to collect remaining function arguments into a single array.
  • Opposed to the spread operator, which expands existing arrays or objects.
  • Represented by three dots (…).

Benefits:

  • Simplifies handling a variable number of arguments in functions.
  • Enables concise construction of sub-arrays from existing ones.
  • Useful for destructuring assignment to extract specific elements.

Example:

  • Extracting top 3 attractions from a “top 7” vacation list:

JavaScript

const top7 = [
  "Colosseum", "Roman Forum", "Vatican", "Trevi Fountain", "Pantheon",
  "Piazza Venezia", "Palatine Hill"
];

const [first, second, third, ...secondVisit] = top7;

console.log(`Top 3: ${first}, ${second}, ${third}`);
console.log(`Next visit: ${secondVisit.join(", ")}`);

Other Applications:

  • Multiplying values with variable tax rates.
  • Building dynamic lists for various purposes.

Key Takeaways:

  • Rest parameter should be the last parameter in a function.
  • Use destructuring with rest operator for selective element extraction.
  • The rest operator enhances code flexibility and reduces boilerplate.

Ready to Unpack the Rest Operator in JavaScript?

Here’s a visual guide to mastering this versatile tool:

1. What It Is:

  • Definition: Think of it as a box that collects the remaining items in an array or function arguments.
  • Syntax: Represented by three dots (…) before a variable name.

2. Gathering Leftovers in Arrays:

  • Extracting Sub-Arrays: Imagine a suitcase full of clothes. Use the rest operator to neatly pack specific items into a smaller bag, leaving the rest behind.
  • Example:

JavaScript

const colors = ["red", "green", "blue", "yellow", "purple"];
const [firstColor, ...otherColors] = colors;
console.log(firstColor); // Output: "red"
console.log(otherColors); // Output: ["green", "blue", "yellow", "purple"]

3. Capturing Variable Arguments in Functions:

  • Handling Uncertain Numbers: Picture a party where you don’t know exactly how many guests will attend. The rest operator ensures no one is left out!
  • Example:

JavaScript

function greetGuests(greeting, ...names) {
  names.forEach(name => console.log(`${greeting}, ${name}!`));
}
greetGuests("Welcome", "Alice", "Bob", "Charlie");
// Output: "Welcome, Alice!", "Welcome, Bob!", "Welcome, Charlie!"

4. Key Points to Remember:

  • Last in Line: The rest parameter must always be the final parameter in a function’s definition.
  • Destructuring Duo: Often combined with destructuring assignment for selective element extraction.

That’s it! Now you’re equipped to handle arrays and functions with ease using the rest operator. Enjoy its flexibility and code more efficiently!

The rest operator allows you to take items from an array and use them to create a separate sub-array. True or false?

True

Correct! The rest operator can be used to destructure existing array items, rather than typing them out again.

You might already know,
that a spread operator in JavaScript, is used to unpack a box, for
example, to unpack an array. The rest operator, on the other hand,
is used to build a smaller box, and pack items into it. In this video, you will explore what
a rest operator is, and how to use it. To illustrate how a rest operator can
be useful, consider a travel itinerary, I’ve realized, that there are many
things I’d love to see, while in Rome, during my vacation. Unfortunately, I’m pressed for time, and there’s no way to really
enjoy all of the attractions, even if I rush to see them all, let’s
explore how to solve this itinerary issue. In this case I can create an array of
seven places that I would like to visit, on my holiday to Rome. So I type const top7 to create the array,
and I list the seven places I would
like to go, within square brackets, with each item in double quotes,
and separated by a comma. The Colosseum, the Roman Forum,
the Vatican, Trevi Fountain, the Pantheon, Piazza Venezia,
and the Palatine Hill. To solve the problem, I decided to
organize my list in such a way, that I have my top three attractions, and
prepare another list, for a second visit. To do this, I use the rest operator, and
a technique known as de structuring, in this de structure in syntax,
I simply specify, what I want to get out of the top seven
array, in this case the first three items. So, I start by typing const, open and
closed square bracket, equal sign, top7. Then, I create three variables first,
second and third, plus another variable, to hold the rest
of the list, named secondVisit. To do this, I type const first,
second, third, and then three dots, and
a new variable, secondVisit, within Square brackets,
then equals top7, semi colon. With this syntax, I extracted
the contents of the top7 array, into four variables, the variable first,
with the value of the Colosseum. The variable second, with the value of
the Roman Forum, the variable third, with the value of the Vatican. And then I include the variable
secondVisit, that is a sub array, of the rest of the items,
in the original top7 array. If I inspect secondVisit, an array
of the four remaining attractions, Trevi Fountain, the Pantheon,
Piazza Venezia, and the Palatine Hill, are all saved as string primitives. The rest operator, therefore, gives us what is left over of the source
array, as a separate sub array. The rest operator is also useful
in functions too, in fact, I can use a rest parameter,
to quickly multiply values. I create a function,
to add the tax rate to prices, I name it, addTaxToPrices, and
give it two parameters, the tax rate and the rest operator,
with the items bought. The function returns each item with
the tax rate, in the addToTaxPrices, parameters, the rest parameter
gives me an array, so I can use array methods,
on items bought, using the map method. It’s important to know,
that the rest parameter, must be the last parameter
in the function definition. This means, that adding any other
parameter, to my addTaxToPrices function, after the rest operator, and
the items bought would result in an error. In this video,
you learned how to use the rest operator, which groups the remaining parameters in a
list, within a standard JavaScript array, well done with completing this video,
on the rest operator.

Reading: Using Spread and Rest

Reading

Practice Quiz: Knowledge check: Advanced JavaScript Features

What will print out when the following code runs?

The for-of loop works for Object data types.

What will print out when the following code runs?

What values will be stored in the set collection after the following code runs?

What value will be printed out when the following code runs?

What value will be printed out when the following code runs?

Reading: Additional resources

Reading

Javascript in the Browser


Video: JavaScript modules

Summary of “JavaScript Modules: ES6 and Beyond”

Key points:

  • Modules in JavaScript:
    • Standalone units of code that can be reused.
    • Added in ES6 to avoid issues with global functions in complex programs.
    • Work by importing and exporting code between files.
  • Before modules:
    • All functions were global, leading to conflicts and namespace issues.
    • Third-party libraries and multiple developers created challenges.
    • CommonJS was an early module system, but not supported natively in browsers.
  • ES6 modules in action:
    • Requires a type="module" attribute on the <script> tag.
    • Uses import and export keywords to manage code between files.
    • Can be run locally with a server to avoid CORS security issues.
  • Outcomes:
    • Understand the benefits and limitations of modules in JavaScript.
    • Learn how to use basic ES6 modules in a browser.

Additional points:

  • The video covers other module systems like CommonJS, but the focus is on ES6 modules.
  • Resources for setting up a local server are provided in the additional reading.
  • The tutorial emphasizes the practical application of ES6 modules in a browser environment.

# JavaScript Modules: Breaking Down Code Barriers

Welcome to this hands-on exploration of JavaScript modules!

In this tutorial, you’ll discover how to organize and reuse code effectively using ES6 modules. Get ready to:

  • Understand the motivation behind modules and their benefits.
  • Learn how to create, import, and export modules in practice.
  • Overcome common challenges and leverage modules in browser environments.
  • Explore advanced module concepts for future learning.

Let’s dive in!

Understanding the Need for Modules:

  • The problem with global functions: Explore the limitations of global namespaces and how they can lead to conflicts and maintainability issues.
  • Encapsulation and reusability: Discover how modules promote code organization, maintainability, and code sharing.

Creating and Using Modules:

  • The type="module" attribute: Learn how to signal a module script in your HTML files using this attribute.
  • Exporting code: Use the export keyword to make functions, variables, and other values available to other modules.
  • Importing code: Bring in exported elements from other modules using the import keyword.

Running Modules in Browsers:

  • Setting up a local server: Address CORS issues and practice running modules locally using a simple server setup.
  • Troubleshooting common errors: Learn to identify and resolve common module-related errors in the browser console.

Advanced Topics (Optional):

  • Dynamic imports: Explore techniques to load modules on demand at runtime.
  • Circular dependencies: Understand and address potential circular dependency issues between modules.
  • Module bundlers: Discover tools like Webpack and Rollup that optimize and package modules for production environments.

Throughout this tutorial, you’ll have opportunities to:

  • Create your own modules and practice importing/exporting code.
  • Experiment with different module setups and scenarios.
  • Reinforce your understanding through interactive exercises.

Ready to take your JavaScript code organization to the next level? Let’s get started!

Which of the following statements about modules in JavaScript are true? Choose all that apply.

Modules allow for code to be reused and more easily replaced.

Correct. Modules were added to JavaScript in version ES6 and allow for code to be imported, reused and more easily replaced.

To use an ES6 module in a browser, you need to set the script type attribute to “module”

Correct. To use an ES6 module in a browser, the script’s type attribute must be set to “module”.

Modules were added to ECMAScript ES6 specification

Correct. Modules were added to JavaScript in version ES6.

Hello and welcome. Photographers often need different camera
lenses for different shooting situations. It wouldn’t be very economical
to have a separate camera for every need that arises,
fortunately most systems are modular meaning the lens can be removed and
replaced with a different one as needed. In JavaScript, complex programs can be
useful for multiple applications and it wouldn’t make sense to rewrite
them over and over thankfully. Since version ES6, they can be saved and
used elsewhere as modules in this video. You will cover what modules are in
JavaScript which includes how they work as well as their current limitations. You’ll also explore how to use
simple ES6 modules in a browser. JavaScript modules are standalone units of
code that you can reuse again and again. Being standalone means that you can add
them to your program, remove them and replace them with other modules and
everything will still work. But before we continue, let’s explore what things were like
before modules entered the picture. In all versions of JS, all functions that are defined
on the window object are global. While useful for simple projects,
this created some issues when third party libraries or
multiple developers became involved. For example,
a global function from one script could override a function from another
one using the same variable name, techniques were developed to bypass these
issues but they were not without flaws. And so for a long time, JavaScript lacked built in natively
supported module functionality. An engineer at Mozilla named
Kevin Bangor tried to fix this through a project called Server JS which
was later renamed to Common JS. CommonJS is designed
to specify how modules should work outside of
the browser environment. It is mostly used on server
side JavaScript namely node.js a downside of CommonJS is that
browsers don’t understand its syntax. That is certain keywords that CommonJS
relies on, such as require and module.exports don’t work
as expected in browsers. You can learn more about other module
systems in the additional reading but now that you know a bit of the history, let me demonstrate ES6 modules in action
to understand how ES6 modules work. We need to go back to
the humble html script tag. The script tag comes with a type
attribute which identifies the type of content that it contains. For JavaScript, it is written as script
type equals followed by text slash JavaScript in double quotes to display
text in a browser on the next line. I’ve typed console.log, followed by
the string hello from script tag in parenthesis and
then a script closing tag. I can even omit the type attribute and
use a basic script tag and the attribute will be set to
text/JavaScript by default. To make that happen I’ve input
an open script tag followed by console.log on the next line and
same sample text. I’ve been added a few more console logs
before closing off the script tag. To verify that these script tags work. I’ll open a local html file in my
browser that is linked to this code when I opened the elements
tab in the developer tools, it displays the script tags while the
console tab shows the console log output. Next let’s explore how we can use
ES6 modules in a browser before starting I will open
a separate code document. Now I’ve changed the value of the type
attribute by typing the script tag, script type equals module. I then imported a module
called greeting.js. But how do you make it work to
demonstrate I’ll open the associated html file in another browser tab. Since I’m running this file locally,
access to my script is blocked by a built in browser security feature
called cross origin resource sharing and I receive an error message
under the console tab. To eliminate this error,
I need to run the html file over a server. I can use a local server for that. For information on how to set up a local
server referred to the additional reading, now my greeting.js module
is being read in and consumed by this html document script tag. In other words, the file script tags
have successfully imported the module. In this video you have learned
about modules in JavaScript ES6. You should now have a better idea of both
their uses and their limitations and you should know how to use
basic ES6 modules in a browser.

Video: JavaScript DOM manipulation

Summary of DOM Manipulation:

  • DOM is like a superpower remote for websites: It allows developers to dynamically change content, style, and structure of webpages.
  • The DOM is a tree-like structure: It represents the HTML document as nested objects, mirroring the page’s elements and attributes.
  • Interacting with the DOM: Developers can manipulate the DOM using:
    • DevTools Elements tab: A graphical interface for inspecting and modifying elements.
    • JavaScript Console: Writing code to access and update the DOM object.
  • Manipulating the DOM in action:
    1. Create an HTML element (e.g., h2) using document.createElement.
    2. Add text and attributes to the element using methods like innerText and setAttribute.
    3. Attach the element to the DOM using document.body.appendChild.
  • Benefits of DOM manipulation:
    • Create interactive and dynamic webpages.
    • Update content without reloading the page.
    • Add custom functionality and features.

Here’s a tutorial on DOM Manipulation:

What is the DOM?

  • The DOM (Document Object Model) is a tree-like representation of a webpage’s HTML structure.
  • It allows developers to interact with and modify the elements of a webpage using JavaScript.
  • Think of it as a blueprint or roadmap of the page, where each element (headings, paragraphs, images, etc.) is a node in the tree.

Why is DOM Manipulation Important?

  • It’s the foundation for creating dynamic and interactive web experiences.
  • Without DOM manipulation, webpages would be static and unchanging.
  • It allows you to:
    • Update content without reloading the entire page
    • Add or remove elements
    • Change styles
    • Create animations and effects
    • Respond to user interactions

How to Manipulate the DOM:

  1. Accessing the DOM:
    • The document object in JavaScript is the gateway to the DOM.
    • It represents the entire HTML document.
  2. Selecting Elements:
    • You can target specific elements using various methods:
      • getElementById(id): Selects an element by its unique ID.
      • getElementsByClassName(className): Selects elements by their class name.
      • querySelector(selector): Selects the first element matching a CSS selector.
      • querySelectorAll(selector): Selects all elements matching a CSS selector.
  3. Modifying Elements:
    • Once you have a reference to an element, you can:
      • Change its content: element.textContent = "New text"
      • Change its attributes: element.setAttribute("attribute", "value")
      • Change its styles: element.style.property = "value"
      • Add or remove classes: element.classList.add("class"), element.classList.remove("class")
      • Show or hide elements: element.style.display = "none" or element.style.display = "block"
  4. Creating and Appending Elements:
    • Create new elements using document.createElement("elementName").
    • Add them to the DOM using methods like:
      • appendChild(element): Adds an element as the last child of another element.
      • insertBefore(newElement, existingElement): Inserts an element before another element.

Common DOM Manipulation Methods:

  • getElementById()
  • getElementsByClassName()
  • querySelector()
  • querySelectorAll()
  • createElement()
  • appendChild()
  • insertBefore()
  • textContent
  • setAttribute()
  • style
  • classList

Example:

JavaScript

// Create a new paragraph element
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph added with JavaScript!";

// Add it to the body of the document
document.body.appendChild(newParagraph);

Practice and Further Learning:

  • Experiment with DOM manipulation in your browser’s console.
  • Explore online tutorials and resources for more in-depth examples and techniques.
  • Build small projects to apply your knowledge and practice common DOM manipulation tasks.
True or false? Editing the local DOM of a webpage does not affect the document stored on the webserver.

True

You are correct! The DOM is an in-memory representation of the active HTML document. Any changes made are local and do not affect the document stored on the webserver.

Did you ever think of the functions your TV
remote does for you? It allows you to make
changes to your TV. You can think of the DOM
like a TV remote that lets you change the webpage
content on the screen. It even allows you to replace only certain parts of the page, such as an image or
the heading or both. A remote however, has
certain limitations. You can only change the channel, contrast, brightness,
and volume. The DOM gives you much finer-grained control
than a TV remote ever could. For example, imagine you can
change what characters in a TV movie look like with a few simple commands while
the movie is playing. The DOM allows you to change properties of objects
on a webpage. You can think of the DOM as a superpower remote
for websites. It gives developers
power in how they can manipulate and
update webpages. The DOM is in the form of a JavaScript object with nested objects for different
parts of the page. These objects have nested
objects of their own until the entire HTML file is mapped out in what looks
like a tree structure. The DOM is the model
of the HTML file saved as a JavaScript object
in your browser’s memory. The browser automatically builds the DOM for every webpage
that it downloads. For example, if you type a URL into your
browser’s address bar, the browser would fetch the webpage that
exists on this domain. If the browser connects
to the server and it allows the browser
to download the page, it will receive
all the HTML code and save it in its memory. The browser will then
show the downloaded page. It would also build that
webpage’s DOM a model of the HTML document your
browser has just downloaded. As a developer, you
can interact with the page’s DOM to make
changes to the webpage. To interact with the DOM, you can use the Elements tab inside the browser’s DevTools. You get to the DevTools by
right-clicking anywhere in a browser window and
then by clicking “Inspect”. The Elements tab allows you
to interact with the DOM of the currently active webpage using a graphical
user interface, also known as a GUI. The browser also allows you to interact with the DOM
using JavaScript. To do this, you should click the Console tab in the
browser’s DevTools. You can focus on the
Console panel by pressing the Escape
key on your keyboard. Once done, you can start typing JavaScript commands to view
and manipulate the DOM. This is similar to how you interact with the DOM
using the Elements panel, only this time you’re
using code to do it. The entire DOM object
is saved inside the document variable and
accessible via the console. Now let me demonstrate how
DOM manipulation works. Using the document object model allows us to manipulate
live websites. For example, I’ve opened
my browser and loaded the example.com webpage
from the Internet. I want to add a
heading 2 HTML element to this webpage using the DOM. Once again, I have the
Developer Tools open in the window to the right on
the Console tab is active. It’s important to remember
that any changes I make to the DOM are relative to my browser’s local
copy of the webpage. I’m not updating the content of the live website so don’t worry, you’re not going to break it. If I reload the webpage, all changes I make to the
DOM will be lost as it will reset to the page that was downloaded
from the server. In order to create my heading 2 I need to update the
document object. To do this, I type document dot and then the
method createElement. Then inside the open
and close parenthesis, I type the name of the HTML element that
I want to create, which is wrapped
around single quotes. What I am doing here is passing the tag names as a
JavaScript string. Finally, I’m going to assign this statement to
a const variable. I type constant h2, and then the assignment
operator, I press “Enter.” Now I have successfully
built my h2 element. You may notice that
the webpage on the left has not been
updated with the heading 2. This is because although, I now have a h2 element saved
in JavaScript’s memory, I still need to attach
it to the DOM structure. Currently, it’s not a part
of the document object. Additionally, my h2 element
also needs some text. Without it, even after adding the h2 element to the document, there would not be
a visible change on the page because the
added h2 element, although, being a
part of the DOM, would have no text inside. In other words, it
would be blank. Let’s fix these two issues now. First, I’ll make some
updates to my h2 element. I’ll add some attributes and some text using the
inner text method. I can run this on
my h2 variable. I type h2.innerText
and then assign a string with a value of
this is an h2 heading. Next, I want my heading
2 element to have an ID and a class
HTML attribute. To do this, I need to use
the set attribute method. I type h2.setAttribute, which takes two parameters. The first one is the
attribute’s name, which is ID, and then the value
of the attribute. For this example, I’ll name as sub-heading and press “Enter.” Notice that inside
the parenthesis, the name and the
value are wrapped in single quotes and
separated by a comma. Next, I need to use the set
attribute method again. This time for the
class attribute. I’ve pasted the
same line of code, and now I just need to
change the word ID to class. For the value, I change this to secondary and press “Enter.” Finally, I’m ready to append
my h2 object to the DOM. First, I can test that
my code is correct by typing h2 and noticing the
HTML structure’s output. This looks good to me so
let’s add it to the DOM. I need to run the
append child method on the document body to do this. Now, I type
document.body.appendChild. Inside the parenthesis, I place my HTML structure
stored in the variable h2. Success. My object is
appended to the body of this webpage and the heading 2 text
displays in the browser. You should now be able
to explain the basics of DOM manipulation and use some of the most common DOM
manipulation methods.

Reading: JavaScript interactivity

Reading

Video: Event handling

Key concepts:

  • Events: User interactions like clicks or taps on a webpage.
  • Event handlers: JavaScript functions that execute in response to events.
  • addEventListener method: A way to attach event handlers to HTML elements.
  • HTML event attributes: An alternative method to specify event handlers directly in HTML.

Steps to create event listeners:

  1. Using addEventListener:
    • Select the target element using document.querySelector.
    • Create an event handler function.
    • Call target.addEventListener(event, handler).
  2. Using HTML event attributes:
    • Add the event attribute (e.g., onclick) to the HTML element.
    • Set the attribute’s value to the name of the event handler function.

Example:

  • Clicking the heading triggers both handleClick (body listener) and handleClick2 (heading listener).
  • Clicking outside the heading triggers only handleClick.

Additional points:

  • Event listeners can be attached to various elements and events (e.g., button clicks, form submissions).
  • Choose the appropriate method (addEventListener or HTML attribute) based on your needs and preferences.

You are using JavaScript code on your website to listen out for events. Which of the following are examples of events that your code can listen out for? Check all that apply.

Button click. Icon tap

Let’s say you are
using a webpage on your computer and
you click a button, or you tap the like icon on a friend’s picture
on your phone. In JavaScript, the
button click and the like icon tap are examples
of user triggered events. Events are happening
all the time. You can use JavaScript code
to listen for these events. You can even choose the parts of the page on which you are
listening for events. Let me describe an example. You might want to listen for a click event on an
Add to Cart button. Once you capture such an event, you might want to run
some JavaScript code. For example, I can add a circle with the number
one on it next to the shopping cart
icon to indicate that there is now one item
in the shopping cart. If the same event gets
triggered or fired again, our event handling code
then handles the event by updating the count in the circle next to the
shopping cart icon. The circle then displays
the number two to indicate that there are
two items in the cart. In JavaScript, the
function that handles captured events is known
as the event handler. Let me demonstrate how to listen foreign event by using the
add event listener method. Okay, so I’m back in the console here and
let me demonstrate two ways to set up
an event listener for HTML elements on a webpage. One of the easiest
ways to listen for an event is to use the add
event listener method. You can do that on a
given HTML element. For example, suppose
I want to listen to the click event on the body
of this example website. First, I need to
get a reference to the body element where we
want to listen to this event. In the console of the
browser developer tools, I type document.queryselector, and then the name of the element inside of the parenthesis. For this example, its body, and I enclose
it with single quotes. Next, I want to assign the
body object to a variable. I type const target equals to assign the body
object to the target variable. I’ve named this variable target because it’s the target
of our click event. Now I can create a function that would be run when this
target is clicked. I type function handle click, and then in the function body, I console log the string,
clicked the body. The next step is to run the addEventListener method
on the target element. I type target.add EventListener. Then inside the parenthesis, I pass it two arguments. The first is the event type
click as a string value, and the second is my
handle click function. Okay, so my code is now ready. Let me test it by
clicking the webpage. Success. Notice that the text
is output to the console. In addition to the
addEventListener method, an alternative way to
listen for events is by using HTML event attributes. Before doing that,
let me first write a second click handler
function named handleClick2. Once again, I console log a string inside
the function body. This time it will output the
phrase clicked the heading. Next, I need to open
the elements panel of the developer tools and expand the view for the div element, then the heading element
should be visible. I right-click the H1 element
and click edit as HTML. Then after the H1, I create the attribute by typing onclick equals followed by my function name handleClick2 with a pair of
parenthesis at the end. Finally, I click
outside the element to save the change and return
to the Console tab. Notice that when I now click on the heading
in the webpage, the phrase clicked
the heading and clicked the body is
output to the console. Basically, this single click has triggered two different
event listeners. But notice that if I click
outside of the heading, it only triggers the
event listener that listens for clicks on
the entire body element. In this video, you learned how to write an
event listener using the addEventListener method
as well as by writing a function directly as a HTML event
attribute. Great work.

Reading: Exercise: Web page content update

Reading

Reading: Exercise: Capture Data

Reading

Reading: Solution: Capture Data

Reading

Reading: Moving data around on the web

Reading

Video: JavaScript Object Notation – JSON

Converting JSON Strings to JavaScript Objects:

  • Use JSON.parse(jsonString) to convert a JSON string into a JavaScript object.
  • This allows you to access and manipulate the object’s properties and methods.

Converting JavaScript Objects to JSON Strings:

  • Use JSON.stringify(object) to convert a JavaScript object into a JSON string.
  • This is useful for sending data to APIs or storing it in a format that can be easily parsed.

Key Points:

  • JSON strings are essentially objects represented as strings with specific formatting.
  • JavaScript objects can hold functions, while JSON strings cannot.
  • Valid JSON does not allow JavaScript comments.
  • Methods are excluded when stringifying a JavaScript object.

Common Use Cases:

  • Retrieving data from APIs often involves converting JSON strings to JavaScript objects for easier manipulation.
  • Sending data to APIs or storing it in a structured format often requires converting JavaScript objects to JSON strings.
You can convert a JSON file to a JavaScript object so that you can work with that object's properties.

True

Correct. When working with JSON it is common to convert it back to a JavaScript object to work with its properties. To do this you need to use the global built-in JSON object and its parse method.

In this video will help you learn to
convert a JSON string to a regular JavaScript object and vice versa. If you type a piece of JSON code
into your browser’s console, it should not produce any errors. For example, a JSON string with one
property named greeting that contains the value of the string hello. If I run this code,
I get back the same result. It’s worth remembering that JSON is
basically just an object represented in the form of a string. It has some specific formatting but
it’s a string nonetheless. So to work with JSON, it is common to
convert it back to a JavaScript object to work with its properties and methods. To do this you need to use
the global built in JSON object and its parse method,
let me demonstrate this now. First I will sign the JSON
string to a variable named JSONstr using the const keyword. Next I’ll run the JSON parse
method on this variable by typing JSON.parse and
then JSONstr inside the parentheses. I press enter and notice that a regular
JavaScript object is returned. I want to save this object as a variable. So I assigned the JSON parse method
to a variable named aPlainObj using the const keyword. Okay, so now that my JSON string is
stored in a regular JavaScript object. I can manipulate it just like
any other JavaScript object. Let me demonstrate this now by reassigning
the value of the greeting property, I type the object name followed by a dot
and then the object property equals hi. Press enter and
notice that the word hi is output. I can confirm this by
inspecting the object and notice that its structure
has been updated. Okay, that’s how you convert a JSON
string to a JavaScript object. You can also go the other way and
convert a regular object to a JSON string. Using the string of my
method of the JSON object. Let me demonstrate this now. For example, let’s start by
declaring an object named data and assign it some properties and values. To run the JSON string of
my method on this object, I’ll type JSON.stringfy and place
the objects name inside the parentheses. The result is a JSON string. Notice that both the objects keys and its values are double quoted
strings in the JSON syntax. It’s important to remember that while
plain JavaScript objects can hold functions, JSON strings cannot. Another limitation is that valid JSON
doesn’t allow the use of JavaScript comments. Also when you stringfy a JavaScript
object containing a method, that method will be excluded
from the stringfy operation. In this video you have learned how to
convert a JSON string to a JavaScript object with the parse method. And how to convert a JavaScript object to
a JSON string using the stringfy method. If you work with retrieving data from APIs
converting the JSON strings to JavaScript objects will be a standard workflow. You can then easily access the objects
properties programmatically this is a vital tool in your tool belt, and
I encourage you to practice this.

Practice Quiz: Knowledge Check – JavaScript in the browser

In the following code, the type attribute can be omitted.

What does the document variable return in JavaScript?

What does the following function return?

After the following code is run, what will happen when the user clicks on a p element in the browser?

What will be printed when the following code runs?

Video: Module summary: Programming Paradigms

Key Topics:

  • Functional Programming: Separating data and functions to solve problems.
  • Object-Oriented Programming (OOP): Using objects and classes to organize code.
  • Scope: Visibility of variables within different code blocks.
  • Object Construction: Building objects using classes and constructors.
  • Inheritance: Extending functionalities from parent to child objects.
  • Modern JavaScript Features: Spread, rest, template strings, and modules.
  • DOM Manipulation and Event Handling: Building interactive web pages.
  • JSON: Data format for transferring and storing information.

Key Takeaways:

  • Understanding different programming paradigms allows for more efficient and maintainable code.
  • Functional programming emphasizes functions and immutability, while OOP focuses on objects and encapsulation.
  • Scope control is crucial for preventing variable conflicts and unexpected behavior.
  • Objects and classes provide structured code organization and reusability.
  • Inheritance facilitates sharing functionalities across related objects.
  • Modern JavaScript features offer enhanced coding capabilities.
  • DOM manipulation and event handling create responsive web interfaces.
  • JSON is a widely used format for data exchange.

Overall:

This module covered a comprehensive range of topics related to programming paradigms in JavaScript, equipping you with essential knowledge for effective development.

You’ve reached the
end of this module on programming paradigms.
Great work. During this module, you
explored the core features of functional programming and
object-oriented programming. Let’s review the module by summarizing the major
items you encountered. The various styles of computer languages are known
as programming paradigms. Having studied programming
paradigms in this module, you should be able to describe functional programming
and how it can be used to
solve a problem by separating data from functions. Having explored
functional programming, you moved on to another
popular paradigm. Object-oriented programming,
often referred to as OOP. You discovered how OOP differs from functional
programming. You studied object-oriented
programming principles. In programming, scope
determines which parts of the code are accessible and
which parts are inaccessible. You learned how the scope
of variables changes when you use the keyword
Var in ES5 JavaScript, and when you use the keywords, Let and Const in ES6 JavaScript. You should now be
familiar with how the scope chain
works in JavaScript. You should also now be able to identify how some of the
different types of scope work, including global and local. Much of the development work in JavaScript involves
building objects. Classes are essentially
a blueprint that you can repeatedly use to
build new objects. You can also pass parameters to the class methods and then use them the same as with
regular functions. Constructors tell JavaScript how you want your
objects to be built. You should now be
able to utilize constructors on built-in
JavaScript objects. You learned that inheritance
exists in JavaScript, and the inheritance model
revolves around the prototype. Additionally, you explored how JavaScript code uses modern
features like spread, rest, template
strings, and modules. You build code that manipulates the DOM and handles events. Finally, you used
JSON in JavaScript. That was a lot to cover, but you should now be
more familiar with programming paradigms in
JavaScript. Great work.

Quiz: Module quiz: Programming Paradigms

Variables declared using ‘let’ can be reassigned.

What will print out when the following code runs?

What will print out when the following code runs?

What will print out when the following code runs?

Consider this code snippet: ‘const [a, b] = [1,2,3,4] ‘. What is the value of b?

What value will be printed out when the following code runs?

Which of the following are JavaScript methods for querying the Document Object Model? Select all that apply.

Which of the following methods convert a JavaScript object to and from a JSON string?

What will be the result of running this code?

What is a constructor?

Reading: Additional resources