[go: up one dir, main page]

0% found this document useful (0 votes)
1 views91 pages

Javascript

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 91

Welcome To Programming

Welcome To Programming!
Up until now, we have built the structure of a web page (HTML) and
designed it (CSS). However, web sites are much more than that.
An important part of web development is making the web pages
interactive.

That is the role of JavaScript. So during this Super Skill, we are going to:

 Get to know how to program in detail.


 Deep dive into JavaScript and learn its tools.
 Learn about data types that exist in javascript.
 Learn how to use these data types to our advantage.

Since their invention in the 1950s, computers have revolutionized our daily
lives. Calculating a route from a website or via GPS, booking a train or an
airplane ticket, or video calling and chatting with friends on the other side
of the world are all actions we can do with the click of a button. All of that
is possible thanks to computers.

Let’s take the term “computer” in its broadest sense. It is a machine that
can perform arithmetic and logical operations. It could mean either a
desktop or a laptop computer (PC, Mac), a computing server, or a mobile
device like a tablet or a smartphone.

Nonetheless, a computer can only perform a series of simple operations


when it is instructed to do so.

They cannot learn, judge, or improvise (if you have watched Terminator,
you might disagree with this.). They simply do what they’re told to ! Their
value comes from how they can quickly compute and process huge
amounts of information.
A computer often requires human intervention. That’s where programmers
and developers come in!
They write programs that give instructions to a computer.

 A computer program (also called an application or software) usually


comprises of one or more text files containing commands in the form
of code. This is why developers are also called coders.
 A programming language is a way to give orders to a computer.
It’s very similar to a human language! Each programming language
has its own vocabulary (keywords that each play a specific role) and
grammar (rules defining how to write programs in that language).
To keep things short and sweet:

 A computer is a machine whose role is to execute quickly and


flawlessly a series of actions given to it.
 A program is a list of actions given to a computer. These actions
take the form of textual commands. All these commands form the
program’s source code.
 The programmer’s task is to create programs. To accomplish this
goal, he can use different programming languages.
 Before writing code, one must think ahead and decompose the
problem to be addressed in a series of elementary operations
forming an algorithm.
Fill in the blanks Solution
A programmer writes, using a programming language, a list of commands forming
a code/program. The code is eventually executed by a computer or any other
machine.

Introduction to Web to Algorithms


Introduction To Algorithms
A quick search on Google will give you the following definition:

An algorithm is a process or set of rules to be followed in calculations or


other problem-solving operations, especially by a computer.
Let’s imagine together a scenario where we’re in a library.
If you were to borrow a book you needed to study from the Engineering
section, how would you go about doing that?

Would you:

 Pick up every book on the shelf until you find what you need?
 Pick up books randomly until you find the right one?
 Try to find it by alphabetical order?
 Use the library’s search guide as a reference?

Bear in mind that these are all ways to eventually achieve the goal. Also,
each method highlighted above can be broken down into smaller steps
that cumulatively achieve the task at hand. For starters, you would have
to:
 Walk up to the shelf.
 Pick up the first book.
 Check if it matches what you’re looking for.
 If it does, yayyyyy!!! (that was quick).
 If it doesn't, you drop the book.
 pick up another one and check again.

This process is continuously repeated until you find the desired book. This
step by step break down of the whole process into actionable steps is what
we call pseudocode in computer programming.

Introduction To Algorithms
The four ways we considered, however, can be examined carefully to
determine the most efficient way. Specifically, by calculating/estimating
the time and energy spent in the course of searching through each
method. The most optimal solution will therefore be the one that
consumes the least amount of time and energy.

The main properties of an algorithm which we will now consider:


1.Input
An algorithm must possess 0 or more well-defined inputs supplied
externally to the algorithm.
2. Output
An algorithm should have 1 or more well-defined outputs as desired.
3. Correctness
Every step of the algorithm must generate a correct output.
4. Definiteness
Algorithms should be clear and unambiguous. That’s why every step of the
algorithm should be clear and well defined.
5. Finiteness
The algorithm should have a finite number of steps that must be carried
out to achieve the task at hand.

Assessment: Quiz
An algorithm doesn't have to be supplied with external inputs.

True False
Not every single step of the algorithm has to generate a correct output as long as the
main output is correct.

True False
The efficiency of an algorithm is defined by how much time is spent and how much
energy & resources are consumed in solving a given problem.

True False
Introduction To JavaScript
Introduction To JavaScript
JavaScript is the most widely used scripting language on Earth. It has the
largest library ecosystem of any programming language.

JavaScript is the core language of the web and the only programming
language that can run in all major web browsers.
The programs in JS are called scripts. They can be written right into a web
page’s HTML and run automatically as the page loads.

Keep in mind, JavaScript has nothing to do with Java.

Inside the browser, JavaScript can do everything related to webpage


manipulation, interaction with the user, and the webserver.

For instance, inside the browser, JavaScript is able to:

 Add new HTML to the page, change the existing content, modify
styles.
 React to user actions, run on mouse clicks, pointer movements, key
presses.
 Send requests over the network to remote servers, download and
upload files (so-called AJAX and COMET technologies).
 Get and set cookies, ask questions to the visitor, show messages.
 JavaScript was standardized in 1997 under the name ECMAScript.
Since then, the language has undergone several rounds of
improvements to fix awkwardness and support new features.
 This course uses the ES2015 standardized version of JavaScript, also
called ES6.
 This version brings a lot of interesting novelties to the table. It is
now well-supported by most environments and platforms, starting
with web browsers (more details in this compatibility table).

Fill in the blanks Solution


When JavaScript was created, it initially had another name: "LiveScript". But Java was
very popular at that time, so it was decided that labeling this new language as a
“younger brother” of Java would help. But as it evolved, JavaScript became a fully
independent language with its own features and characteristics called ECMAScript,
and now it has no relation to Java whatsoever.

Creating Your First JavaScript


Learning programming often begins with executing a simple “Hello
World!” program.

Let’s print the “Hello World!” line in the console using JavaScript with this
one line of code.

Go to this link (It's a code editor online.) In JavaScript window, delete all
the code and copy-paste the following code.

Go ahead, run it and see for yourself.

P.S: No need to worry, we are going to see what's console.log in another


part.
console.log("Hello World");

Solution
Reorder the steps you'll take to create your first JavaScript:
In your favorite text editor, open the file as an .html file.

Click in the empty line just before the closing </body> tag and type <script>.

Press the return key to create a new blank line, and type: alert('I promise not to hack
the planet with the new skills I’m about to acquire');

Press the return key once more, and type </script>.

Launch a web browser and open the .html file to preview it.

Click the alert box’s OK button to agree and close it.

Adding JavaScript To a Web Page


In HTML, JavaScript code must be inserted between starting and
closing <script> tags.
In this example, we’ll be creating an HTML element, using JavaScript to
display an alert welcoming the user.
Scripts (such as this one) can be placed in the <head>, or just before the
closing tag of the <body> section of an HTML page, or in both.

PS : It’s highly recommended that they are inserted right before the
</body> tag, so that the page can load all the other HTML elements
before the JS.

<script language="javascript">

alert(“Hello there random user! :)”)

</script>

Solution
Reorder to indicate the ideal script tag position:
<head>

</head>

<body>

<script language="javascript">alert(“Come in, We’re Open”)</script>

</body>
External JavaScript
We can also place scripts in external files, this is practical when the same
code is meant to be used by different web pages, and most importantly,
for respecting the “Separation of Concerns” design principle.

Thus, we will keep our HTML files for structures, and our logic part will be
kept in files of their own. In our case, they will be JavaScript files that will
have the extension .js.

To be able to use these external scripts, we’ll put the name of the script
file in the src (source) attribute of a <script> tag like this:
PS: The script will behave as if it was located exactly where
the <script> tag is located.
<script src="myScriptFile.js"></script>

Assessment: Quiz
Placing scripts in external files:

Respects the separation of concerns principles between structure (HTML) and


logic (JS). Is unnecessary work. Makes HTML and JS easier to read & maintain.
Slows down page loads.
The path of the external file is placed in script tag.

True False
The script tag must be placed in the head tag.

True False

Alert, Prompt & Confirm


There are several methods to make JavaScript output and/or grab data
(from the user). They either modify or replace existing HTML,
help debug, or retrieve HTML content. Let’s take a look at some of them:

 alert() is a simple function to display a message to a dialog box


(also called alert box).
 alert("This is an alert box");
 prompt() The alert() method cannot interact with the visitor. To
interact with the user we use prompt(), which asks the visitor to
input information and stores the information in a variable.

var visitorName = prompt("What's your name : ")

console.log(visitorName)

 confirm() displays a dialog box with two buttons, OK and Cancel


and a text as a parameter. If the user clicks on OK button, confirm()
returns true and on clicking Cancel button, confirm() returns false.

var isCoolWithIt = confirm("Are you ok with it?")


console.log(isCoolWithIt )

Fill in the blanks Solution


alert() displays an alert box. prompt() stores the input from a user in a variable.
confirm() returns true if the user clicks on Ok, and it returns false if he clicks
on Cancel.

console.log
Behold the console.log()!
What we’ve studied is all fine and dandy, but remember that
mighty console.log()? Well that’s going to be your best ally and companion
during your upcoming journey in the valley of JavaScript.

You should use the console.log() method to print to console your


JavaScript. The JavaScript console log function is mainly used for
code debugging as it makes the JavaScript print the output to the
console.

To open the browser console, right-click on the page, select inspect,


click console, and voila! there’s where the magic happens!
Assessment: Quiz
What will this print to the console?

var variable = "content";


console.log(variable)

variable content
The console.log method is used to display a message to the window screen.

True False
The principal role of console.log method is to help developers in the debugging
process.

True False

Comments in JavaScript
Commenting allows us to write stuff that will be ignored by the interpreter
and won’t be run as code.
To achieve this we use:

 “//” to comment anything on the same line after the double slash.
 “/*” & “*/” to comment multiple lines.
 var a = 2 + 2 // I’m a single line comment
 /*
 And I’m a multi-lines comment,
 Anything in here will be ignored by the Javascript
 Interpreter.
 var b = 3 + 3
 */

Assessment: Quiz
In JavaScript, we can write comments using: (Select only one answer)

// /**/ All of the above None of the above


Comments are used to indicate to the interpreter useful information about the
program.

True False
Comment can be written only in one line.

True False

Basic Data Types


Data Types
Most programming languages help you create values that symbolize a
number, a character in a text, or a longer text. You can also symbolize the
concept of true and false values using booleans. You can even create
values that symbolize the absence of a value.

In JavaScript, there are six primitive types:

1. boolean (true or false)


2. number (including integers like 1, -2, and floating point numbers
like 3.14, 2e-3)
3. string ( Strings are used for storing text. Strings must be inside of
either double or single quotes.)
4. null (null has one value: null. It is explicitly nothing.)
5. undefined (A variable that has no value is undefined)
6. Symbol (We’ll get to this later on in the course)

PS: Notice how typeofnull incorrectly prints “object”? Well that’s a bug in
JS. Which brings us to the second kind of data types in JavaScript:

Composite or Non Primitive Type, like the Object we just saw.

Objects can be: “Object literals”, “Arrays”, “Function”, “RegEx”, “Dates”...

For the time being, our main focus is Object Literals.


console.log(typeof(true)) // prints boolean

console.log(typeof(9000)) // prints number

console.log(typeof("Übermensch")) // prints string

console.log(typeof(anUndefinedVar)) // prints undefined

console.log(typeof(null)) // prints object

A JavaScript object literal is a comma-separated list of key-value


pairs wrapped in curly braces. These values can reference any type of
data, including objects and/or primitive values.

We’ll be covering objects (& arrays) in more detail later on in this course.
For now, let’s simply keep in mind that Object literals can encapsulate a
multitude of data, enclosing it in a tidy package, and having the structure
shown in the Code Box.
var person1 = {

name: “foulan”,

age: 9000,

isStudent: true

Assessment: Quiz
The following code will print to the console: number
1
console.log(typeof('Hello'))

True False
The string in JavaScript is only represented between single quotation mark ( ‘ ).

True False
The boolean data type can have only true or false.

True False

Arithmetic Operators
Dealing with integers is straightforward. You have the four arithmetic
operations ( +, -,*, /*) available
for addition, subtraction, multiplication, and division respectively.

The % operator is called modulus. a % b returns the remainder of the


division a / b. In our example, 7 / 5 is 1, and the remainder is 2. The value
2 is returned.

The ** operator is called the exponential operator. 5 ** 2 is five raised to


the second power (that's 25 by the way).
console.log(5+2);

// 7

console.log(7%5);

// 2

console.log(5**2);

// 25

NaN:
The division 0 / 0 or using mismatching types creates a special number
called not a number or NaN.

Infinity Type:
JavaScript registers very large numbers as infinity. For instance, ten to the
power of 309 is represented as infinity. Division by zero also yields infinity.
// NaN

console.log(0 / 0);

console.log('Some random string' * 2);

// Infinity

console.log(1 / 0);

console.log(Infinity * Infinity);

console.log(1e+309);

Increment and Decrement:


Increment and decrement operators increase or reduce the numerical
value of a variable by one. They are represented by two plus signs (++) or
two minus signs (--), (often used with loops).
PS: Note that increment and decrement operators can only be used on
variables; attempting to use them on a raw number will result in an error.
(in other words, you can’t do this => 5++, or this => 7--)
var num = 0;

console.log(num)

num ++

console.log(num)

num --

console.log(num)

Assessment: Quiz
What should be the initial value of num for the result to end up equal to 64:

var num
var num2 = 5
num++
num2--
var sum = num + num2
var result = sum ** 2
console.log(result)

0 1 2 3
The modulo operator is represented by:

% $ mod
NaN refers to Not a Number.

True False

Assignment Operators
An assignment operator assigns a value to its left operand based on the
value of its right operand. The first operand must be a variable and basic
assignment operator is equal (=), which assigns the value of its right
operand to its left operand. That is, a = b assigns the value of b to a.
var a = 5 // assigned a value of 5 to a

var b = a // assigned a (value of 5) to b, now b has a value of 5


var c = b // assigned b (value of 5) to c, now c has a value of 5

console.log(c) // prints 5

/* => we dragged the value of 5 from a all the way to c,

through a series of //assignments (using the assignment operator “=”)*/

Assignment Operators
We can combine arithmetic operators with the regular assignment
operator "=" and create shorthand annotations for standard operations:

Shortha Expressi Description


nd on

a +=b a=a+b Adds 2 numbers and assigns the result to the first.

a -= b a=a-b Subtracts 2 numbers and assigns the result to the first.

a *=b a=a*b Multiplies 2 numbers and assigns the result to the first.

a /=b a=a/b Divides 2 numbers and assigns the result to the first.

a %=b a=a%b Computes the modulus of 2 numbers and assigns the result to
the first.

var a = 5

var b = 7

a += b

console.log(a) // prints 12

Assessment: Quiz
What does result evaluate to?
var a = 3;
a += 2;
a -= 1;
a **= 2;
a /= 4;
a %= 3;
var result = a;

0 1 Infinity NaN
An assignment operator assigns a value of left operand to the right operand:

True False

The value of a is:


var a = 0;
a += 5;

5 1 0

Comparison Operators
Remember booleans values? Booleans are either true or false.

We can compare two numbers with >, >=, ==, ===, <=, <.
(we will discuss the difference between == and === in the next slide.).
For the rest of the operators, the result of the comparison is a boolean.

The ! operator:
The ! operator negates its operand. True becomes false, and false
becomes true.
console.log(5 <= 5); // true

console.log(5 < 5); // false

The comparison operators take simple values (numbers or string) as


arguments and evaluate either true or false. Here is a list of comparison
operators.
Operator Comparis Description
on

Equal (==) x == y Returns true if the operands are equal.

Not equal (!=) x != y Returns true if the operands are not equal.

Strict equal (===) x === y Returns true if the operands are equal and of the
same type.

Strict not equal (! x !== y Returns true if the operands are not equal and/or
==) not of the same type

Greater than (>) x>y Returns true if the left operand is greater than the
right operand..

Greater than or x >= y Returns true if the left operand is greater than or
equal (>=) equal to the right operand

Less than (<) x<y Returns true if the left operand is less than the right
operand

Less than or equal x <= y Returns true if the left operand is less than or equal
(<=) to the right operand

Truthy & Falsy:

Before we continue, let’s explore in detail the notions of truthy and falsy.

Truthy: Something which evaluates to TRUE.


Falsy: Something which evaluates to FALSE.
It’s mostly logical. One (1) is truthy, Zero (0) is falsy. Ann object of any
kind (including functions, arrays, RegExp objects, etc.) is always
truthy. The easiest way to determine if something is truthy is to determine
that it’s not falsy.

There are only six falsy values in JavaScript:


undefined, null, NaN(Not A Number), 0, ""(empty string), and false, of
course.
console.log(Boolean(undefined));

console.log(Boolean(null));

console.log(Boolean(NaN));

console.log(Boolean(""));

console.log(Boolean(0));

console.log(Boolean(false));

Assessment: Quiz
What does the following code print out?

var x;
console.log(Boolean(x));

true false

What does the following code print out?

var x = 5;
var y = "5";
console.log(x != y);

true false

What does the following code print out?

console.log(null === true)

true false

Logical & Boolean Operators


There’s a big misunderstanding surrounding the logical operators AND and
OR in JavaScript. They do not return true or false! More accurately:

Operator Usag Description


e

Logical AND a && Returns the first value if falsy, otherwise returns the second
(&&) b value whatever it may be.

Logical OR a || b Returns the first value if truthy, otherwise returns the second
(||) value whatever it may be.

var x = 1 // x is truthy

var y = 0 // y is falsey

var z = null // z is falsey

console.log(x && y) // prints 0

console.log(z && y) // prints null

console.log(z || x) // prints 1

console.log(y || z) // prints null

That being said, logical operators are often used alongside


comparison operators to return the evaluation of expressions
instead of merely variables, this is especially handy when we’re
setting conditions. (We’ll explore those later on, don’t worry).
var x = 0;

var y = 10;

var z = 5;

console.log(z > x && z < y) // prints true

console.log(z > x && z <= y) // prints true

console.log(z > x && z != y) // prints true


One last thing, remember the “!” operator? We said that it negates its
operand, true becomes false, and false becomes true.

Well, we can use the “!” operator to convert a value to a boolean by


negating it twice:
assuming v is truthy, !!v becomes true.
assuming w is falsy, !!w becomes false.
console.log(!!NaN) // prints false

console.log(!!undefined) // prints false

console.log(!!Infinity) // prints true

console.log(!!5) // prints true

Assessment: Quiz
What does the following code print out ?

console.log(!!NaN == !!undefined && 6 >= !!Infinity)

true false
The && operator returns the first operand if it is true or the second operand if the
first is false.

True False

The || operator returns the first operand if it is true or the second operand
if the first is false.

True False

String Operators
When working with JavaScript strings, oftentimes we need to join two or
more strings together into a single string. Joining multiple strings together
is known as concatenation.

The concatenation operator (+) concatenates two or more string values


together and returns another string which is the union of the two operand
strings.

The shorthand assignment operator (+=) can also be used to concatenate


strings.
var x = "google";
x += "." + "com"

console.log(x) // prints “google.com”

This, however, can get tedious at times. Luckily for us and thanks to ES6,
there’s a new way to concatenate strings.

Template Strings:

Template Strings use backticks (`` ) rather than the single or double
quotes we're used to with regular strings.

One of their first real advantage is string substitution. Substitution allows


us to take any valid JavaScript expression (including for example, the
addition of variables) and insert it inside a Template Literal using the $
{} syntax. The result will be an output that’s part of the same string.

var name = "Lucy";

console.log(`Yo, ${name}!`) // prints “Yo, Lucy!”

Assessment: Quiz
What does the following code print out?

var x = "Hello"
var y = "World"
console.log(x + y)

Hello World HelloWorld error

The + operator returns a concatenated string.

True False
The template string can give us the same result as the + operator.

True False

Program Flow: Functions


A function is basically a piece of code that can be reused without having
to write it again and again.

Think of a function like a mathematical function giving you a relationship


between input and output variables. If you don’t like math, think of a
function like a vending machine. You insert coins and a number, and it
gives you cold soda.
The function definition example in the code box describes the relationship
between its input variables a and b, and the return value of the function.

The return statement returns the value of the function. When calling
the add function with arguments a and b, it computes the value a+b and
returns it.

Example:
function add(a, b) {

return a + b;

console.log(add( 5,2)); // prints 7

Solution
Rearrange the segments to create a function that takes 2 arguments and returns
their sum:
function sum(a,b){

var sum = 0;

sum = a + b;

return sum

User-Defined Functions
Function declarations:
In most programming and scripting languages, there are some built-in
functions that are kept in a library. The real interesting part is that we can
write our own functions, (also called 'User Defined Functions' or 'UDF'.) to
perform specialized tasks.

Before using a function, we must first define it somewhere in the scope


from which we wish to call it. Defining your own function in JavaScript is a
simple task.

A classical function declaration begins with the keyword function, followed


by:

 The name of the newly created function


 A list of parameters the function accepts, enclosed in parentheses and
separated by commas.
 A block of JavaScript code enclosed in curly braces, { }, to be executed
when the function is called.
 The opening curly brace ({) indicates the beginning of the function code
and the closing curly brace (}) marks the termination of a function.
 function functionName(param1,param2..paramN){

 // block of JavaScript code

 }

Function expressions: (Making functions while using a variable as a


reference)
We can also define functions without placing the name between the
function keyword and the argument list. This structure is great if you want
to create a reference to it using a variable.
/!\ Remember, substract is still a variable, it’s just that in this case it
contains a function.
var subtract = function( a, b ) {

return a - b;

To sum it up, we can declare a function in two ways. Let’s say we want to
define a function that calculates the cube of argument passed to it, you
can do it in one of two ways:

PS: In arithmetic and algebra, the cube of a number n is its third power
the result of the number multiplied by itself twice: n3 = n × n × n.

The function "cube" takes one argument, called n. There is only one
JavaScript statement in function body which instructs to return the
argument (n) of the function after multiplying it by itself twice. Here, the
return statement returns the calculated value.
// Example 1: (Classic Function Declaration)

function cube(n){

return n*n*n;

// Example 2: (Function Expression)

var cube = function(n){


return n*n*n;

Fill in the blanks Solution


The critical difference between function declarations and function expressions lies in
how the browser loads them into the execution context. Function declarations load
before any code is executed. Function expressions load only when the interpreter
reaches that line of code. So if you try to call a function expression before it's loaded,
you'll get an error! If you call a function declaration instead, it'll always work,
because no code can be called until all declarations are loaded.

Function Parameters
Parameters are variables listed as a part of the function definition.
Arguments are values passed to the function when it is invoked.

In JavaScript, parameters of functions default to undefined. Default


function parameters allow named parameters to be initialized with
default values if no value or undefined is passed.
var add = function( a, b ) {

return a + b;

console.log(add(0,1)) // prints 1

console.log(add()) // prints NaN

var add = function( a = 0, b = 1 ) {

return a + b;

console.log(add())

/* prints 1 even though no arguments were given to this function call


*/

Fill in the blanks Solution


Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function at
the execution.

Calling Functions & The Return


Statement
“Calling”, “Invoking” or “Executing” are terms used interchangeably when
executing a predefined function. Functions can be called using their
references (((≃ their names))). And necessary arguments are passed to
the function during this phase (see code box).

Note: When a function does not return anything, its return value
becomes undefined
// 1_Defining some functions

function add( a, b ){

return a+b;

var subtract=function( a, b ) {

return a-b;

var multiply=function( a, b ) {

a*b; // notice the absence of “return” here

// 2_Calling the predefined functions

add(2, 3) // returns 5

subtract(2, 3) // returns -1

multiply(2, 3) // returns undefined


Assessment: Quiz
We need to create a greet function that greets the user. The function takes a string
as an argument and returns “Hello *USERNAME*” (with the user’s name in all caps).
Exp: the function greet(“adam”) returns “Hello ADAM”.

function greet(name){ return `Hello ${name.toUpperCase()}` function greet()


{ return `Hello ${name.toUpperCase()}` const greet = name => `Hello $
{name.toUpperCase()}` let greet = name => "Hello" + name.toUpperCase()
Every declared function has a return statement even if it is not written.

True False
A function is invoked by calling its name followed by parentheses. If arguments are
passed, they should be added inside the parentheses..

True False

Program Flow: Conditional Statement


Program Flow
So far we have covered the different types of basic functions and
arithmetics (addition,subtraction, etc.) and logical (true or false)
operations in JavaScript.

We can use these to write a sequence of instructions that perform a


calculation.

However, in software development, there are three types of control


structures:

1. Sequence: writing instructions one after the other.


2. Selection: either execute one set of instructions or another.
3. Iteration: execute a set of instructions for a finite or infinite number
of times.
As we already know how to sequence instructions one after another,
it is time to learn about selection and iteration. Let’s start with
selection (the if statement).
Fill in the blanks Solution
The control structures within JavaScript allow the program flow to change within a
unit of code or function. These statements can determine whether or not given
statements are executed, (the selection) - and provide the basis for the repeated
execution of a block of code( iteration )

The If Statement
The most basic structure of a conditional execution is:
if(condition){
Instruction 1;
Instruction 2;
Etc..;
}

The instructions inside the if-branch are only executed if condition


is truthy.

Let’s write a function that checks if the argument that’s being passed to it
is a number:
// 1_Defining the function

function checkIfNumber( x ){

if ( typeof x === 'number' ){

console.log( x + ' is a number.' );


}

// 2_Calling the function

checkIfNumber(5) // prints “5 is a number.”

checkIfNumber(“5”) // doesn't do anything, “5” was passed here as a


string (non-numeric value).

checkIfNumber() // doesn’t do anything, no argument was passed to the


function

Assessment: Quiz
if(EarthIsRound){ return truth; } // truth is :

Earth is flat, i’m woke There’s no Earth, we live in a simulation Yep, this is
how you write conditions in JS
The code inside an if block will be executed only if the condition is truthy

True False
Inside an if block we can write only one instruction

True False

The Else Statement


This is all fine but it’s still slightly awkward that we don’t print anything in
case the input is not a number. Let’s fix this, we already know all we need
to write a program that does this. The thought process is as follows:

 If x is a number, print it.


 Else (otherwise if x is not a number), print the message “Oops that's not a
number.”

Notice that the else branch is only executed if the original condition is not
true.
// 1_Defining the function
function checkIfNumber( x ){

if ( typeof x === 'number' ){

console.log( x + ' is a number.' );

} else {

console.log("Oops that's not a number.");

// 2_Calling the function

checkIfNumber(5) // prints “5 is a number.”

checkIfNumber(“5”) // prints “Oops that's not a number”

checkIfNumber() // prints “Oops that's not a number”

Solution
Order this code:
if (condition) {

lines of code to be executed if the condition is true }

else {

lines of code to be executed if the condition is false}

The Else If Statement


We can cascade this approach even further using else if, to check for as
many other conditions as we please, after the first if, and before the
last else.

So, if the first condition fails, it will test the next else if condition, if that
fails too, then the next one will be tested and it will continue sequentially
until all the else if fails and it will finally execute the else statement.
The following function (decodeColor) uses this logic to print out a color
depending on the code (number) being passed to it as an argument.
// 1_Defining the function

function decodeColor( code ) {

if ( code === 1 ) {

console.log( 'Red' );

} else if ( code === 2 ) {

console.log( 'Yellow' );

} else if ( code === 3 ) {

console.log( 'Green' );

} else {

console.log( 'Unknown code' );

// 2_Calling the function

decodeColor(1) // prints Red

decodeColor(2) // prints Yellow

decodeColor(3) // prints Green

decodeColor('blah') // prints Unknown code

Solution
Order this code:
if (condition1) {

lines of code to be executed if the initial condition is true}


else if (condition2){

lines of code to be executed if the secondary condition is true AND initial condition is
false}

else {

lines of code to be executed if all conditions are false}

The Switch Statement


Long chains of if-else statements can become monotonous very quickly
when handling multiple scenarios. Luckily for us, there's an abbreviated
version for this: the switch operator.

We have a variable inside the switch. This variable may have values. We
jump to the case label for which the passed argument is equal to the label
value. Then we start executing the code.

Otherwise there’s always our default which will handle any other scenario
that is not covered by our cases.
// 1_Defining the function

function decodeColor( code ) {

switch( code) {

case 1:

console.log( 'Red' );

break;

case 2:

console.log( 'Yellow' );

break;

case "x":

console.log( 'Green' );

break;

default:

console.log( 'Unknown code' );


}

// 2_Calling the function

decodeColor(1) // prints Red

decodeColor(2) // prints Yellow

decodeColor("x") // prints Green

decodeColor(3) // prints Unknown code

Ahaa! You must’ve noticed that we used a break there. Now why is the
break so important?

Simply put, if there was no break at the end of the code segment
belonging to a label, execution would continue on to the next code line. It
does not matter that it is now under another label. Code just continues
executing everything after the first valid scenario. Let’s try it in the code
box, we will execute the same function as before but without the break(s)
now.

This is why we have a break statement at the end of each code segment
belonging to a label. The break statement jumps out of the
closest switch statement, and our program continues execution after
the switch statement.
// 1_Defining the function

function decodeColor( code ) {

switch( code) {

case 1:

console.log( 'Red' );

case 2:
console.log( 'Yellow' );

case "x":

console.log( 'Green' );

default:

console.log( 'Unknown code' );

// 2_Calling the function

decodeColor(2) // prints Yellow

// Green

// Unknown code

That being said, we can still omit the break if we’re going to use
the return statement instead.
The return statement will only execute what’s valid for a given
scenario/case and then exists the switch statement without executing the
rest of the lines inside of it (the switch statement and the rest of its cases).
// 1_Defining the function

function decodeColor( code ) {

switch( code) {

case 1:

return 'Red';

case 2:

return 'Yellow';

case "x":

return 'Green';

default:

return 'Unknown code';


}

// 2_Calling the function

console.log(decodeColor(2)) // prints Yellow

/*

PS: we now have to explicitly console.log the returned value of

our function to “see” it.

Merely executing the function won’t print anything on the

console (although everything is working fine and as it should)

*/

Assessment: Quiz
Is this code correct?

var a= 3

switch (a) {
case 4:
alert( 'Exactly!' );
break;
default:
alert( "I don't know such values" );
break;
case 3:
alert( 'Too small' );
break;
case 5:
alert( 'Too large' );
break;
}

// This code will return “Too small” with no shame

True False
The switch statement can replace the if else statement.

True False
The break keyword is used to break from the switch statement.

True False

Program Flow: Loops


Now let’s check iteration, through the concept of loops.
A loop allows us to execute the same expression as many times as we
want, by just writing down the code once.

Fill in the blanks Solution


Looping in programming languages is a feature which facilitates the execution of a
set of instructions/functions repeatedly while some condition evaluates to true.

The While Loop


A while loop will first check its condition, if it evaluates to true, it will
execute the statement within its body. Then re-check the condition and
continue re-executing the statement(s) as long as (the condition)
evaluates to true.
When or if the condition evaluates to false, the while statement won’t
execute any code inside its body and the flow will just continue executing
the rest of our code.

while (condition){
Statement(s)
}
 The variable i keeps track of how many times the loop is executed.
 First the JavaScript interpreter examines the condition in the while loop.
As i is 0 and numbers.length is 10, we conclude the condition to
be true.
 If the condition is true, we execute the body of the while loop. So we
iterate through the array and sum up all elements inside, while
incrementing the loop variable ‘i’ with 1.
 Then we compare 1 against the length of the array, 10. As 1 is smaller
than 10, we execute the loop body again. The sum variable now stores 19
+ 65 = 84. The value of i becomes 2.
 We continue this until i becomes 10. Then we realize the condition i <
numbers.length becomes false. Once the condition of the while loop
becomes false, we continue with the code after the while loop.
 // Let’s sum the values of a small array

 var numbers = [19, 65, 1, 2, 6, 1, 9, 9, 2, 1];

 var sum = 0;

 var i = 0;

 while ( i < numbers.length ) {

 sum += numbers[i];

 i += 1;

 }

 console.log( 'The loop was executed ' + i + ' times' );

 // prints The loop was executed 10 times

 console.log(sum);

 // prints 115

Assessment: Quiz
"while" iterates until the specified condition is false ?

True False
The while loop should execute the statement inside its body at least once.

true false
Is the following code correct?

var i = 0;
while (i < 5) loop {
console.log(i)
}
i++

true false

The Do While Loop


The Do...While Loop
The do-while loop executes the loop body at least once and
checks the condition after the execution and before the end.
// Let’s sum the values of a small array

var numbers = [19, 65, 1, 2, 6, 1, 9, 9, 2, 1];

var sum = 0;

var i = 0;

do {

sum += numbers[i];

i += 1;

} while ( i < numbers.length )

console.log( 'The loop was executed ' + i + ' times' );

// prints The loop was executed 10 times

console.log(sum);

// prints 115

PS: We mainly use do-while loops for input validation. The user inputs a
value, then we check its validity. Try to keep this in mind for when we
reach the DOM part of JS.

This is where the do-while loop makes sense, because we can be sure we
need to enter data at least once. In the example summing-up array
members, using the do-while loop is technically possible, but it does not
make sense, because the simple while loop is easier.

Fill in the blanks Solution

Even Though do while loop and While loop look similar, they differ in their execution:
The while loop tests the condition at the beginning of the loop, and if the condition is
True, statements inside the loop will execute. It means that this loop executes the
code block only if the condition is True At the end of the loop, the do-while loop tests
the condition. So, it executes the statements in the code block at least once even if
the condition Fails.

The For Loop


The for loop is another loop that is perfect for iteration. This loop
combines several lines of code into one. While its execution is identical to
the while loop, the for loop has everything you need in one line. You don’t
have to mix your loop body with the increment of the loop variable.

The execution of the for loop is as follows:

1. Initialization of a loop variable.


2. Check condition. If condition is falsy, exit the for loop.
3. Execute the statements in the loop body if condition is true.
4. Increment the loop variable, then go back to step 2.
Assessment: Quiz
A for loop's header can be all blank like for (;;)

True False
A for loop's third statement has to always be with the ++ increment operator.

True False
How many times does the following loop run?

var i = 5;
for (; i < 5; i++) {
console.log(i);
}

5 times 4 times 0 times

The For..In & For...Of Loops


Why bother iterating an "i" variable if a loop can take care of it for us?

 The for… in loop


The for… in loop enumerates all the available indices of the values
present in the array in ascending order.
 The for… of loop
Why bother using a variable for iteration at all, if we could
enumerate the values of the array?.
In ES6, there is a loop called the for…of loop, which does exactly
that.
 // Let’s sum the values of a small array

 var numbers = [19, 65, 1, 2, 6, 1, 9, 9, 2, 1];

 var sum = 0;

 // Using the for… in loop

 for ( var i in numbers) {

 sum += numbers[i];

 }

 console.log(sum)

 // prints 115

 // Let’s sum the values of a small array

 var numbers = [19, 65, 1, 2, 6, 1, 9, 9, 2, 1];

 var sum = 0;

 // Using the for… of loop

 for ( var value of numbers) {

 sum += value;

 }

 console.log(sum)

 // prints 115

Fill in the blanks Solution


An array is iterated using: for (let el of a){ //do stuff with el } An object being used as
an associative array is iterated using: for (let key in o){ //do stuff with o[key] }

Break & Continue


We are almost done with loops. There remains only two small
constructs: Break and Continue.
We can use break or continue inside the loops:

 break exits the closest loop it is in, and continues with the next command.
 continue skips and jumps out from the loop body, and jumps back to the
condition of the loop.
 // Let’s sum every second element of the numbers array:

 var numbers = [19, 65, 1, 2, 6, 1, 9, 9, 2, 1];

 var sum = 0;

 for ( var i in numbers ) {

 if ( i % 2 == 0 ) continue;

 sum += numbers[i]

 }

 console.log(sum);

 // prints 78

 /*

 PS: Notice that we could've written i += 2 in a simple for loop to


jump to every second value.

 We’re using continue here just for the sake of the example.

 Whenever i is even, continue moves execution back to the next


iteration of i in numbers.

 */

 /*

 You already know what a break statement looks like, because we


learned it when dealing with the switch statement.

 It is doing the same thing in loops. Suppose we want to break out


from the loop whenever the sum exceeds 100:

 */

 var numbers = [19, 65, 1, 2, 6, 1, 9, 9, 2, 1];

 var sum = 0;

 for ( var i in numbers) {

 sum += numbers[i];
 if ( sum >= 100 ) {

 break;

 }

 }

 console.log(sum)

 // prints 103

Fill in the blanks Solution


The continue statement terminates execution of the statements in the
current iteration of the labeled loop, and continues ts execution with the next
iteration. While The break statement terminates the current loop, switch, or label
statement and transfers program control to the statement following the terminated
statement.

Introduction To Arrays
Arrays provide us with a way to create and maintain a list of data.
An array is an ordered list of items. Even better, these items don’t have to
be the same type.
// Declaring an array called storage containing 3 items of different
types:

var storage = [ 1, 'Monday', null ];

// Accessing elements

console.log(storage[0]); // prints 1

console.log(storage[6]); // prints undefined

// Array length

console.log(storage.length) // prints 3

Accessing elements
Each element of the array can be accessed using an index starting from
zero. The syntax for indexing is shown in the Code Box.
In the second example, we indexed out of the array. As we indexed
beyond the length of the array, the program returned undefined for
storage[6].

Array length
Arrays have lengths reflecting how many items they contain. Just keep in
mind that to access the last element of an array we will have to use
arrayName.length -1 as the index, (remember array indexes start counting
from 0). And anything beyond that will return undefined.

Assessment: Quiz
Use the console.log() method to display the rooster from the following array:

var animals = ['🐷', '🐑', '🐔', '🐇'];

console.log(animals[1]); console.log(animals[2]); console.log(animals[3]);


console.log(animals[4]);
The array data type can only regroup one type of data.

True False
The array start index is 1.

True False

Adding and Removing Elements


After being introduced to the concept of arrays, let’s see how we can add
& remove elements:

 .push adds elements to the end of the array.


 .unshift adds elements to the beginning of the array.
 .pop removes the last element from the array and returns it.
 .shift removes the first element from the array and returns it
 var days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

 console.log(days);

 // prints ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

 days.push( 'Saturday' );

 console.log(days);

 // prints ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',


'Saturday' ]

 days.unshift( 'Sunday' );

 console.log(days);

 // prints ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',


'Friday', 'Saturday' ]

 days.pop();

 console.log(days);

 // prints ['Sunday', 'Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday' ]

 days.shift();

 console.log(days);

 // prints ['Monday', 'Tuesday', 'Wednesday', 'Thursday',


'Friday' ]

Adding and Removing Elements


Deleting, overwriting and adding elements to any index:

We can delete any element from the array.The value undefined will be
placed instead of this element.

Also, the values of an array can be set using their indices, and equating
them to a new value. We can overwrite existing values, or add new values
to the array. The indices of the added values do not have to be
continuous.
var days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

console.log(days);

// prints ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

delete days[2];

console.log(days);

// prints ['Monday', 'Tuesday', undefined, 'Thursday', 'Friday']

days[2] = 'Wednesday';

console.log(days);

// prints ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

delete days[7];
console.log(days);

// prints ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

Assessment: Quiz
In the given array, determine the output printed to the Javascript console, by:
console.log( array[3] ); (All questions are part of the same program. Each instruction
in every question is in sequence with the previous instructions.)

var array = [ 7, 15, 32, 9, '3', '11', 2 ];

32 9

In the given array, determine the output printed to the Javascript console, by:
console.log( array[7] ); (All questions are part of the same program. Each
instruction in every question is in sequence with the previous instructions.)

var array = [ 7, 15, 32, 9, '3', '11', 2 ];

Undefined 2

Arrays can be created using the: (Select only one answer)

Array() constructor [] literals All of the above


What would arr.indexOf(0) and arr.indexOf(1) return respectively, if arr holds the
array [1, 5, 8]?

1 and -1 -1 and 1 -1 and 0 1 and 5

Introduction To Objects
Objects in JavaScript are standalone entities that can be likened to objects
in real life. For example, a book can be represented as an object in JS,
which you would describe by its title, author, number of pages, and genre.
Similarly, a car might be an object that you would describe by
its color, manufacturer, model, and horsepower.

Objects are an integral and crucial part of most JavaScript programs. For
example, a user account object may contain data such as usernames,
passwords, and e-mail addresses. Another common useful case is a web
shopping platform’s shopping cart that could consist of an array of many
objects containing all the pertinent information for each item, such as
name, price, and weight and shipping information. A to-do list is another
common application that might consist of objects.
Fill in the blanks Solution
The object is a complex data type that allows you to store collections of data. An
object contains properties, defined as a key-value pair. A property key (name) is
always a string, but the value can be any data type, like strings, numbers, booleans,
or complex data types like arrays, function and other objects.

Creating an Object
There are two ways to construct an object in JavaScript:

 The object literal, which uses curly brackets: {}


 The object constructor, which uses the new keyword
Both of these approaches will create an empty object. Using object literals
is the more common and preferred method, as it is less prone to
inconsistencies and unexpected results.
 // Initializing an object literal with curly brackets

 var objectLiteral = {};

 // Initializing an object constructor with new Object

 var objectConstructor = new Object();

Creating an Object
Let’s create an example object, contained in the variable gimli, to describe
a character.
Our new object is gimli, which has three properties. Each property
consists of a name:value pair, also known as key:value pair. Weapon is
one of the property names, which is linked to the property value "axe", a
string. It has one method, with a method name of greet and its value
consists of the function’s contents.

PS: Within greet, you may notice the this keyword. When using this inside
of an object, it refers to the current object, in this case gimli.
// Initializing a gimli object

var gimli = {

name: "Gimli",

race: "dwarf",

weapon: "axe",

greet: function() {

return `Hi, my name is ${this.name}!`;

},

};

console.log(gimli)

// prints {name:"Gimli", race:"dwarf", weapon:"axe", greet:f greet


{...}}

// PS: This output may render differently depending on what console you
are using, but you should notice that all of the values passed to the
object are shown in the output.

Fill in the blanks Solution


var adam = { name: "Adam", age: 18, wasExpelledFromHeaven: true }

Properties & Methods


Objects can have properties and methods:

 A property is the association between a name (key) and value within an


object, and it can contain any data type. A property generally refers to the
characteristic of an object.
 A method is a function that is the value of an object property, and
therefore a task that an object can perform.

An easy way to remember the difference between object properties and


methods is to think of a property as a noun, and a method as a verb.
Name, race and weapon are all nouns associated with an object, and
therefore, they are properties. fight() or talk() are verbs that might be
used as a method function definition.

Assessment: Quiz
Remember the adam object from the last assessment? lets add to it a method greet
that returns the string “Hi, my name is Adam”:

var adam = {
name: "Adam",
age: 18,
wasExpelledFromHeaven: true,
//...your answer here...
}

method = greet: function(){return “Hi, my name is Adam”} greet: “Hi, my


name is Adam” greet: function(){return “Hi, my name is Adam”}
An object in JavaScript is characterized by properties and methods.

True False
An object method is a function that objects can perform.

True False

Accessing Object Properties


There are two ways to access an object’s properties:
 Dot notation: .
In our example, if we want to retrieve the property value of weapon, we
can do so with object dot notation by typing the variable name of the
object, followed by a dot (.) and the property or method name.
 Bracket notation: [ ]
We can retrieve the same data with object bracket notation. Similar to how
you might index and access a string, the syntax for bracket notation is two
square brackets ([ ]) encasing the property name.

// Initializing a gimli object

var gimli = {

name: "Gimli",

race: "dwarf",

weapon: "axe",

greet: function() {

return `Hi, my name is ${this.name}!`;

},

};

// Retrieving the value of the weapon property using the dot notation

console.log(gimli.weapon); // prints “axe”

// Retrieving the value of the weapon property using the bracket


notation

console.log(gimli["weapon"]); // prints “axe”

Accessing Object Properties


Both dot notation and bracket notation are used regularly. Dot notation is
faster and more legible, but it has more limitations. Bracket notation
allows access to property names stored in a variable, and must be used if
an object’s property contains any sort of special character.

In order to retrieve an object method, you simply call it in the same way
you would call a regular function, just by attaching it to the object
variable.
// Initializing a gimli object

var gimli = {

name: "Gimli",
race: "dwarf",

weapon: "axe",

greet: function() {

return `Hi, my name is ${this.name}!`;

},

};

// Calling an object method using the dot notation

console.log(gimli.greet());

// prints "Hi, my name is Gimli!"

Fill in the blanks Solution


Yep, we’re still using that adam object as an example, we now want to print to the
console the following phrase “Hi, my name is Adam and I’m 18 years old”. const
adam = { name: "Adam", age: 18, wasExpelledFromHeaven: true, greet: function()
{return "Hi, my name is Adam"} } console.log(`${ adam.greet() } and I'm $
{ adam["age"] } years old`)

Adding & Modifying Object Properties


In order to add a new property to an object, you assign a new value to
a property with the assignment operator (=).
For example, we can add a numerical data type to the gimli object as the
new age property. Both the dot and bracket notation can be used to add a
new object property.

We can also add a new method to the object by using the same
process. We can then call the newly created method the same way we did
before.
// Initializing a gimli object

var gimli = {

name: "Gimli",

race: "dwarf",

weapon: "axe",

greet: function() {

return `Hi, my name is ${this.name}!`;


},

};

// Adding a new age property to gimli using the dot notation

gimli.age = 139;

// Adding new age property to gimli using the dot notation

gimli["age"] = 139;

// Adding a new fight method to gimli

gimli.fight = function() {

return `Gimli attacks with an ${this.weapon}.`;

console.log(gimli)

// prints {name: "Gimli", race: "dwarf", weapon: "axe", age: 139,


greet: ƒ, fight: ƒ}

// Calling the newly created method fight

console.log(gimli.fight());

// prints "Gimli attacks with an axe."

Using the same methods we’ve mentioned in the previous screen, an


object’s property can be modified by assigning a new value to an existing
property.

What you should keep in mind at this point, is that through the assignment
operator =, we can also modify the properties and methods of a JavaScript
object.
// Updating weapon from axe to battle axe

gimli.weapon = "epic battle axe";

// Calling the previously created method fight AGAIN

console.log(gimli.fight());
// prints "Gimli attacks with an epic battle axe."

Assessment: Quiz
The value of an object property can’t be modified.

True False
After creating an object, we can add a new property to it.

True False
Is the following code correct?

var gimli = {
name: "Gimli",
race: "dwarf",
weapon: "axe",
greet: function() {
return `Hi, my name is ${this.name}!`;
},
};
gimli.age = 200;

True False

Removing Object Properties


In order to remove a property from an object, you use the delete keyword.
delete is an operator that removes a property from an object.
In the example below, we will remove the weapon property from gimli
using delete.

The delete operation returns true if the property was successfully removed
or if it was used on a property that doesn't exist or else it will return false.
/!\ In the output below, the weapon name and its associated value (“axe”)
are no longer available, confirming that we have successfully deleted the
property.
// Initializing a gimli object

var gimli = {

name: "Gimli",

race: "dwarf",

weapon: "axe",
greet: function() {

return `Hi, my name is ${this.name}!`;

},

};

// Removing weapon from gimli

delete gimli.weapon; // Output: true

// We can test the output of gimli to see if it succeeded.

console.log(gimli);

// prints {name: "Gimli", race: "dwarf", greet: ƒ }

Objects are an extremely useful and versatile feature of the JavaScript


programming language. They are some of the main building blocks of
writing code in JavaScript, and are a practical way to organize related data
and functionality. To-do lists, shopping carts, user accounts, and locations
on a GPS map are few of the many examples of real-world JavaScript
objects that you might encounter.

Fill in the blanks Solution


The delete operator deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.The delete
operator is designed to be used on object properties. It has no effect on variables or
functions.Note: The delete operator should not be used on predefined JavaScript
object properties because it can crash your application.

Conclusion
JavaScript RECAP
Time to do a victory dance! We have made amazing progress in our
journey through web development.

Now, we have learned the basics of the remarkable JavaScript language,


we’ve learned how to create a JavaScript program, how to execute it and
how to link it to an HTML file. We also learned a number basic structures in
JavaScript.

Buckle up and wear your seatbelts for this next part! The adventure is still
in its beginnings!
DOM

What is DOM?
What is DOM?
In the last skill, we have learned the basics of JavaScript. But, we have
never explored the relationship between JavaScript and the web page.
Therefore, in this Super Skill we’ll be answering these questions:

 What is DOM?
 How to access DOM elements?
 How to manipulate the DOM elements? What are events and how to treat
them in JavaScript?
 How to treat form in JavaScript?

What is DOM in JavaScript?


JavaScript can access all the elements in a webpage using Document
Object Model (DOM).

As a matter of fact, the web browser creates a DOM of the webpage when
the page is loaded.

Using DOM, JavaScript can perform multiple tasks like :

 Create new elements and attributes.


 Manipulate and access the existing elements and attributes and even
remove existing elements and attributes.
 React to existing events.
 Create new events in the page.
Fill in the blanks Solution
The DOM represents a document with a logical tree. Each branch of the tree ends in
a node, and each node contains objects. DOM methods allow programmers access to
the tree. Using them, you can change the document's structure, style, or content.
Nodes can also have event handlers attached to them. Once an event is triggered,
the event handlers get executed.

DOM Selectors
DOM representation
JavaScript is most commonly used to get or modify the content or value of
the HTML elements on the page. As well as applying different effects like
show, hide, animations etc... But, before you can perform any action we
need to find or select the targeted HTML element.
Here is a definition before we dive any deeper into the course:

Document interface represents any loaded web page in the browser and
serves as an entry point into the web page's content and that exactly is
the DOM tree. The DOM tree includes elements such as <body> and <table>,
among many others. It provides general functionality to the document, like
how to obtain the page's URL and create new elements in the document.
<!DOCTYPE html>

<html lang="en">
<head>

<script>

console.log(document);

</script>

<title>Document</title>

</head>

<body>

<h1>Hello from Mars!</h1>

</body>

</html>

Document
querySelector():
The Document method querySelector() returns the first element within the
document that matches the specified selector or group of selectors. If no
matches are found, null is returned.
Syntax: element = document.querySelector(selectors)
<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>
<body>

<h1>Hello from Mars!</h1>

<script>

var el = document.querySelector('h1');

console.log('el:', el);

</script>

</body>

</html>

Output

getElementById()
The Document method getElementById() returns an object representing
the element whose id property matches the specified string. Since
element IDs are required to be unique if specified, they're a useful way to
get access to a specific element quickly.
Syntax: element = document.getElementById(id)
<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>

<body>

<h1>Hello from Mars!</h1>

<span

>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore,


quos

eveniet.

</span>

<span id="middleSpan">
Quisquam veritatis, quam velit quos eligendi perferendis fugiat
eveniet

</span>

<span>

sapiente ratione assumenda iste repudiandae quidem dicta aliquid.

Voluptatibus, error?

</span>

<script>

var el = document.getElementById('middleSpan');

console.log('el:', el);

</script>

</body>

</html>

Output:

querySelectorall()
The Document method querySelectorAll() returns a static (not live)
NodeList representing a list of the document's elements that match the
specified group of selectors.
Syntax: elementList = parentNode.querySelectorAll(selectors);
<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>

<body>

<h1>Hello from Mars!</h1>

<span
>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore,
quos

eveniet.

</span>

<span id="middleSpan">

Quisquam veritatis, quam velit quos eligendi perferendis fugiat


eveniet

</span>

<span>

sapiente ratione assumenda iste repudiandae quidem dicta aliquid.

Voluptatibus, error?

</span>

<script>

var el = document.querySelectorAll('span');

console.log('el:', el);

</script>

</body>

</html>

Output

getElementsByClassName()
The getElementsByClassName method of Document interface returns an
array-like object of all child elements which have all of their assigned class
name(s).

When called on the document object, the complete document is searched,


including the root node. You may also call getElementsByClassName() on
any element; it will return only elements which are descendants of the
specified root element with the given class name(s).

Syntax: elementList = document.getElementsByClassName(names);


<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>

<body>

<h1>Hello from Mars!</h1>

<span class="text-desc">

Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore,


quos

eveniet.

</span>

<span class="text-desc">

Quisquam veritatis, quam velit quos eligendi perferendis fugiat


eveniet

</span>

<span>

sapiente ratione assumenda iste repudiandae quidem dicta aliquid.

Voluptatibus, error?

</span>

<script>

var el = document.getElementsByClassName('text-desc');

console.log('el:', el);

</script>

</body>

</html>
Output

getElementsByTagName()
The getElementsByTagName method of Document interface returns an
HTMLCollection of elements with the assigned tag name. The complete
document is searched, including the root node. The returned
HTMLCollection is live, meaning that it updates itself automatically to stay
in sync with the DOM tree without having to call
document.getElementsByTagName() again.
Syntax: elementList = document.getElementsByTagName(name);
<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>

<body>

<h1>Hello from Mars!</h1>

<span class="text-desc">

Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore,


quos

eveniet.

</span>

<span class="text-desc">

Quisquam veritatis, quam velit quos eligendi perferendis fugiat


eveniet

</span>

<span>

sapiente ratione assumenda iste repudiandae quidem dicta aliquid.

Voluptatibus, error?
</span>

<script>

var el = document.getElementsByTagName('span');

console.log('el:', el);

</script>

</body>

</html>

Output:

Assessment: Quiz
How can you retrieve an element with the id #first?

document.getElementById("first") document.querySelector("#first") Both 1


and 2
Select the first element with the selector statement .main .title .t1.

document.querySelector(".main .title .t1") document.querySelectorAll(".main .


title .t1") document.getElementsByClassName("main")
The getElementsByClassName returns:

HTML collection NodeList element

DOM Attribute
What are DOM Attributes?
The attributes are special words used inside the start tag of an
HTML element to control the tag's behavior or provide
additional information about the tag.
JavaScript provides several methods for adding, removing or
changing an HTML element's attribute. In the following sections
we will learn about these methods in detail.
Get the attribute value of an element
The getAttribute() method is used to get the current value of an element’s
attribute.

If the specified attribute does not exist on the element, it will return null.
Here's an example:
<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>

<body>

<h1>Hello from Mars!</h1>

<span class="text-desc" id="main-paragraph">

Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore,


quos

eveniet.

</span>

<span class="text-desc">

Quisquam veritatis, quam velit quos eligendi perferendis fugiat


eveniet

</span>

<span id="without-style">

sapiente ratione assumenda iste repudiandae quidem dicta aliquid.

Voluptatibus, error?

</span>

<script>

var mainEl = document.getElementById('main-paragraph');

console.log('el:', mainEl);

var elClassName = mainEl.getAttribute('class');

console.log('elClassName:', elClassName);
var withoutStyleEl = document.getElementById('without-style');

console.log('el:', withoutStyleEl);

var withoutStyleElClassName =
withoutStyleEl.getAttribute('class');

console.log('withoutStyleElClassName:', withoutStyleElClassName);

</script>

</body>

</html>

The output would be :

Setting an Element’s Attribute Value


The setAttribute() method is used to set the attribute of the specified
element.

If the attribute already exists on the element, the value is updated.


Otherwise a new attribute is added with the specified name and value. The
JavaScript code in the following example will add a class and
a disabled attribute to the button element.
<body>

<button type="button" id="myBtn">Click Me</button>

<script>

// Selecting the element

let btn = document.getElementById('myBtn');

// Setting new attributes

btn.setAttribute('class', 'click-btn');
btn.setAttribute('disabled', '');

</script>

</body>

The output would be :

Removing Element's Attribute Value:


The removeAttribute() method is used to remove an attribute from the
specified element.
<body>

<button type="button" class="click-btn" id="myBtn">Click Me</button>

<script>

// Selecting the element

let btn = document.getElementById('myBtn');

// removing class attribute

btn.removeAttribute('class');

console.log('btn:', btn);

</script>

The output would be :


Assessment: Quiz
The attributes are only limited to DOM.

True False
The getAttribute method returns null when it does not find any attribute with the
specified name.

True False
The setAttribute method accepts only one parameter.

True False

DOM Manipulation
Styling DOM éléments
We can also apply style on HTML elements to change the visual
presentation of HTML with the dynamic use of JavaScript.

We can set all the styles for the elements including fonts, colors, margins,
borders, background images, text alignment, width and height, position,
and so on.
<body>

<p id="intro">This is a paragraph.</p>

<p>This is another paragraph.</p>

<script>

// Selecting element

var elem = document.getElementById('intro');

// Appling styles on element

elem.style.color = 'blue';

elem.style.fontSize = '18px';

elem.style.fontWeight = 'bold';

console.log('elem:', elem);

</script>
</body>

The output would be :

Adding element
We can explicitly create new elements in an HTML document, using the
document.createElement() method.
This method creates a new element but it doesn't add it to the DOM.
We will be doing that in a separate step, as shown in the following
example:
<body>

<div id="main">

<h1 id="title">Hello World!</h1>

<p id="hint">This is a simple paragraph.</p>

</div>

<script>

// Creating a new div element

var newDiv = document.createElement('div');

// Creating a text node

var newContent = document.createTextNode('Hi, how are you doing?');

// Adding the text node to the newly created div

newDiv.appendChild(newContent);

// Adding the newly created element and its content into the DOM

var currentDiv = document.getElementById('main');

document.body.appendChild(newDiv, currentDiv);

</script>

</body>

The output would be :


Getting or Setting HTML Contents to
DOM
We can get or set the contents of the HTML elements easily with the
innerHTML property.
This property sets or gets the HTML markup contained within the element
i.e. content between its opening and closing tags. Check out the following
example to see how it works:
<body>

<div id="main">

<h1 id="title">Hello World!</h1>

<p id="hint">This is a simple paragraph.</p>

</div>

<script>

// Getting inner HTML conents

var contents = document.getElementById('main').innerHTML;

console.log('contents', contents);

// Setting inner HTML contents

var mainDiv = document.getElementById('main');

mainDiv.innerHTML = '<p>This is <em>newly inserted</em>


paragraph.</p>';

</script>
</body>

The output would be :

Remove element
Similarly, we can use the removeChild() method to remove a child node
from the DOM.
This method also returns the removed node. Here's an example:
<body>

<div id="main">

<h1 id="title">Hello World!</h1>

<p id="hint">This is a simple paragraph.</p>

</div>

<script>

var parentElem = document.getElementById('main');

var childElem = document.getElementById('hint');

parentElem.removeChild(childElem);

console.log("parentElem", parentElem)

</script>

</body>
The output would be :

Solution
Reorder the code in order for it to properly function:
<script>

let newDiv = document.createElement('div');

let newContent = document.createTextNode('Hi, how are you doing?');

newDiv.appendChild(newContent); let currentDiv =


document.getElementById('main');

document.body.appendChild(newDiv, currentDiv);

</script>

DOM events
Add Events
Events are actions that occur as a result of the user’s action or as result of
state change of the elements of a DOM tree. For
example: click, load, focusin, focusout. These are all events that help us
react with JavaScript.
We can assign JS functions to listen for these events in elements and react
or respond when the event occurs.

Here is a list of events. There are three ways you can assign a function to
a certain event.
If foo() is a custom function, you can register it as a click event listener (it
will be called when the button element is clicked) in three ways:
// first way

<button onclick=foo>Alert</button>

// the second way

<div id="main">

<button>Alert</button>

</div>
<script>

// Getting the button

var btn = document.querySelector('button');

btn.onclick=foo;

</script>

// the third way

<div id="main">

<button >Alert</button>

</div>

<script>

// Getting the button

var btn = document.querySelector('button');

btn.addEventListener('click', foo);

</script>

Remove Events
The removeEventListener() method detaches an event listener that
was previously added with the addEventListener() method from the
event it is listening to.
<div id="main">

<button onclick="foo">Alert</button>

</div>

<script>

// Getting the button

let btn = document.querySelector('button');

// Remove the event listener

btn.removeEventListener('click',foo);

</script>
Event types
The browser triggers many events. A full list is available in MDN, but here
are some of the most common event types and event names:

 mouse
events (MouseEvent): mousedown, mouseup, click, dblclick, mousemo
ve, mouseover, mousewheel, mouseout, contextmenu
 keyboard events (KeyboardEvent): keydown, keypress, keyup
 form events: focus, blur, change, submit
 window events: scroll, resize, hashchange, load, unload

Expamle:
<!DOCTYPE html>

<html lang="">

<head>

<meta charset="">

<meta name="viewport" content="width=, initial-scale=">

<title></title>

</head>

<body>

<div class="d-flex h-100">

<p>try pressing some keys:</p>

<p id="log"></p>

</div>

<script>

document.addEventListener('keydown', logKey);

function logKey(event) {

log.textContent += " " + e.code;

</script>

</body>
</html>

Output:
When pressing the key a, this function display the following:

Solution
Reorder the code in order for it to properly function:
<button id="myBtn">Click Me</button>

<script>

function firstFunction() {

alert("The first function executed successfully!");}

function secondFunction() {

alert("The second function executed successfully");}

let btn = document.getElementById("myBtn");

btn.onclick = firstFunction;

btn.onclick = secondFunction;

</script>

Form validation
The form validation process typically consists of two parts: the required
fields validation which is performed to make sure that all the mandatory
fields are filled in, and the data format validation which is performed to
ensure that the type and format of the data entered in the form are valid.
Well, let's get straight to it and see how this actually works.

HTML
<form name="loginForm" onsubmit="return validateForm(event) ">

<label for="Name">Name:</label>

<input type="text" name="name" placeholder="example@example.com" />

<label for="password">Password:</label>

<input type="password" name="password" placeholder="*********" />

<button type="submit">Login</button>

<button type="reset">cancel</button>

</form>

</body>

JavaScript
function validateForm(e) {

e.preventDefault()

var name = document.loginForm.name.value

var password = document.loginForm.password.value

if (name.length==0)

return alert(`name is required`)

if (password.length<5)

return alert(`password length should more than 5`)

Solution
Reorder the code in order for it to properly function:
function validateEmail() {

var emailID = document.myForm.EMail.value


var atpos = emailID.indexOf('@')

var dotpos = emailID.lastIndexOf('.')

if (atpos < 1 || dotpos - atpos < 2) {

alert('Please enter correct email ID')

document.myForm.EMail.focus()

return false

return true

Conclusion
DOM RECAP
Do a little victory dance because we’re making amazing progress!

Leading up to now, our journey together has taught us how to define


structure and content using HTML, style and describe the presentation of
our structure with CSS, and manipulate our production using DOM and
JavaScript.

Stick around for the next course cause it just keeps on getting more
interesting!

Git & GitHub


Getting Started With Git
Getting Started with Git
You can imagine that web design is like a building and Git is one of the
many important pillars that web design is built on.
So, our primary objective right now is to:

 Understand what Git is.


 Learn how to use the basic Git commands.
 Discover how to configure Git.
 Understand what Github is and how to work with remote repository.

What is VCS?
A version control system is a software tool that helps developer teams
track and manage source code changes over time.

As you edit and add to your code, you tell the version control system to
take a snapshot of your files or save a checkpoint of your progress.
The version control system saves that snapshot permanently so you can
recall it later on if you need it.

Without a VCS, you’re tempted to keep multiple copies of code on your


computer. This is dangerous because it’s easy for a file to get corrupted or
deleted and you’re susceptible to losing months or even years worth of
work.

Version control systems solves that problem by presenting you with all
versions of your code with a clear history of the changes made. This allows
you to go back to older versions of the code and try a different approach.

What is Git?
Git is a free and open source distributed VCS designed to handle
everything from small to very large projects with speed and efficiency.

In plain English, Git is a tool that allows developers to track versions of


their code over time. It does this by creating "snapshots" of the current
state of the code base whenever you tell it to.

Git is essential when collaborating with other developers to ensure that


there are no code conflicts between them and that previous "snapshots" of
the code can be revisited if necessary.

For example, if you are coding and you accidentally break or crash the
app, you’ve just lost all your progress and you’re forced to start from
scratch. However, it’s easier and safer if you're using Git where you can
simply roll back to a previous version of the code.
Fill in the blanks Solution
Having a distributed architecture, Git is an example of a DVCS (hence Distributed
Version Control System). Rather than have only one single place for the full version
history of the software as is common in once-popular version control systems like
CVS or Subversion (also known as SVN), in Git, every developer's working copy of the
code is also a repository that can contain the full history of all changes. In addition to
being distributed, Git has been designed with performance, security and flexibility in
mind.

Basic Git Commands


Installing Git
Git isn’t usually set up by default on your computer, so you need to install
and configure it before you can start using it to manage your code.
It’s important to keep Git up to date, just like all the other software on
your machine. Updates protect you from security vulnerabilities, fix bugs,
and give you access to new features.

The recommended method of installing and maintaining Git is provided for


three major platforms below :

Windows
Download and install Git for Windows. Once installed, you’ll be able to use
Git from the command prompt or PowerShell. We recommend that you
stick with the defaults selected during the installation unless you have a
good reason to change them.
Linux
On the terminal, just run sudo apt install git-all.
Mac
The best thing to do is to install Homebrew, and then from the terminal
run the command brew install git.

Start using Git


Once we have Git installed, we need to "initialize" a repository before we
can start using it.
It’s very easy to do, just follow my lead:

1. Access the wanted folder using the terminal (prompt cmd).


2. To initialize a repository, we only have to run:

git init

The output would be :

P.S : This command just created a hidden folder called .git, where all the magic
happens.

Adding and committing Files


Remember that folder we’ve created? It’s high time we used it. We’ll be
creating a file and placing it in there.
Feel free to add whatever you want!

Check the Status of Your Repository


Now that we have a few files in our repository, let's see how Git processes
them.
To check the current status of your repository, we use the git
status command.

git status

The output would be :


Adding Files for Git to Track
At this point, we do not have any files for Git to track.
We need to add files specifically to Git in order to tell Git to track them.
We add files using the “add” command.
After running git add . Git will add all the repository files to to an
intermediate area called the staging area. We can also add what we
want simply by running git add myFileName
git add .

The output would be :


Removing Files
Let’s say that you have added files to Git and you do not want it to track
any of them.
In a situation like this, you tell Git to stop tracking them.
However, running a simple git rm command will not only remove it from
Git, but will also remove it from your local file system as well! To tell Git to
stop tracking a file while still keep it in your local system, run the following
command:
git rm --cached [file_name]

The output would be :


Committing Changes
Once you have staged your files, you can commit them into Git.
Imagine a commit command as a snapshot in a certain point and time
where you can return back to access your repository at that stage. You
assign a commit message to every commit, which you can pass with the -
m prefix.
git commit -m 'first commit'

The output would be :

Solution
Reorder the following commands:
git init

git add .

git status

git commit -m 'first commit'

Configuring Git
Files status
Git sees every file in your working copy as one of three things:

Tracked
A file which has been previously staged or committed.
Untracked
A file which has not been staged or committed.
Ignored
A file which Git has been explicitly told to ignore.

Ignored files are usually built artifacts and machine generated files that
can be derived from your repository source or should otherwise not be
committed.

PS: If we have a file that we do not want to track, we just put it


inside .gitignore file.

Configuration settings
The .gitconfig file contains a list of configurations that affects the
behaviour of git commands, so in order to manipulate it, we use the
command git config <configuration>. Therefore, to change the name and
email used by Git to identify the user, we run the following command (PS.
change YOUR.NAME and YOUR.EMAIL with your own values.)
git config --global user.name "YOUR NAME"

git config --global user.email "YOUR EMAIL"

Git aliases
Oftentimes, you’ll be finding yourself typing git commands over and over
again. For example, git add, git init and git status are commands you
will be repeatedly using.
The smart thing thing to do then is to use a shortcut and that’s an alias.
Aliases help make your Git experience simpler, easier and more familiar.
To create a temporary alias, which will last as long as your terminal
session is open, you can type:
git config alias.KEYBOARD_SHORTCUT COMMAND

So if we wanted to type git st and have it function like git status, we


would type git config alias.st status. Now we can type git st and have
the same output as if we typed git status.

If you would like your alias to be a part of your global configuration, add
the --global command after git config. For example, to alias git i to git
init globally, you would type git config --global alias.i init.

Assessment: Quiz
The .gitignore is a file containing a list of files that git will not track:

True False
What does the following command do?

git config alias.i init

Initialize a git repo. Set an alias for init Create a version


What does the following command do?

git config --global user.email "YOUR EMAIL"

Initialize a git repo. Set an alias for email Set the user email to whatever you want

GitHub Introduction
What is GitHub?
GitHub is a web-based Git repository hosting service.
Simply put, it is a tool that enables collaboration by hosting shared Git
repositories that teams of developers can all contribute to.
While GitHub uses Git, the functionality it provides is entirely
different from Git. So try make it stick in your mind that Git and GitHub
are not the same thing.

In short, Git is a Version Control System while GitHub is an online platform


for hosting and sharing code, text files and more complex file formats.
Why use GitHub?
GitHub provides a great way for you to store your code in a safe and
remote location (in case something happens to your local machine). It's a
fantastic way to collaborate with other developers both privately and
publicly.

Many large open source projects are hosted on GitHub, which makes it
very easy to examine the code both on GitHub and on local machines.

In the next couple of chapters, we will learn how to move code from our
local repository to a remote repository on GitHub using the push command,
as well as retrieve code from a remote repository on GitHub using
the pull command.

We'll also learn about GitHub specific concepts like forking and pull
requests.

Want to get a sense for how popular GitHub is in the development


community? Here are some projects you may have heard of that are
hosted there:

 Angular
 React
 Ruby on Rails
 Twitter Bootstrap
 Node.js
 JQuery
 Homebrew

Getting started with GitHub


If you don't have an account on GitHub yet, head to github.com and create
an account. Signing up is easy!

Be sure to use whatever email address is in your . gitconfig when you sign
up on GitHub.
If you'd rather sign up with a different email address, change
your .gitconfig accordingly. You'll run into some minor annoyances if
there's a mismatch between the email address in your GitHub profile and
the email address in your .gitconfig.

Fill in the blanks Solution


GitHub is a for-profit company that offers a cloud-based Git repository hosting
service. Essentially, it makes it a lot easier for individuals and teams to use Git
for version control and collaboration. GitHub’s interface is user-friendly enough so
even novice coders can take advantage of Git. Without GitHub, using Git generally
requires a bit more technical intelligence and extensive use of the command line.

Working with Remotes


Creating a remote repository
Once you have a GitHub account, head over to https://github.com/new and
create a repository. In this example, we will be creating a repository
called first_repo. Do not worry about the description or checking the box
to initialize the repository with README.

After you've created the repository, GitHub will give you a few instructions
to get started. The instructions should look something like this (the url
towards the end will depend on your GitHub username):

Pushing code to GitHub


Now after creating a repository in GitHub, we need to add our local code
(after commits) to the remote repo. It’s very simple. First, we need to
attach the address of the GitHub repo to our local project, simply by
running git remote add origin YOUR_REPO_URL.
Now, after providing the remote URL to the local repository to take the
local files to the remote host, we have to run this command git push
origin master.

And voila! Our files are now in GitHub.

Solution
Reorder the following commands:
git init

git add .

git status

git commit -m 'first commit'

git remote add origin YOUR_REMOTE_URL

git push -u origin master

GitHub Workflow
Fork
Now that we know how to push code to GitHub, let's explore one of
GitHub’s important features: forking.

When collaborating with others, you’re unable to push directly to the


original repository (Imagine if you could play with one one of the world’s
largest open source projects and repositories… that would be insane).

So the logical thing to do is make a copy of someone else's remote


repository and make sure it is under our username so that we can push
code to it. This ensures that our experimenting with the repository doesn’t
affect the original version.

To practice forking, head over to any repo on github and on the top right
you will see a button with the text Fork. Click on this button and you will
have a copy of the repository under your name!

Remember, "forking" is strictly a GitHub feature and it is not by any


means related to Git. It is simply a way to make your own copy of a
repository on your account where you have permission to push your code
to GitHub.

Clone
Once you have applied “forking” on the repository, you need to select it
(the remote one you just made) and download the code on your local
computer (i.e. make a local repository). Instead of making a folder and
going through the whole git init process and adding a remote, you can
conveniently use the git clone command, which accepts a link to the
repository and downloads it into a folder (with everything already set up!).

In order to do that, first click on the button clone and that will provide us
with a remote URL. Finally, just copy the URL.
In the terminal, just run git clone THE_COPYED_ADDRESS.
git clone https://github.com/facebook/react.git

Pull Request
Now let's say you are collaborating with an organization on GitHub (where
you forked the repository from) and you would like to merge your changes
with the original repo that you forked (remember you can't just push to it,
because you do not have permission to do so). You can issue a pull
request and the one who can grant permission can either merge or reject
it.

To do this, click on the "New pull request button" and then click on the
"Create pull request". You should then be able to go to the original
repository and see your pull request or "PR".
Fill in the blanks Solution
A fork is a copy of a repository. Forking a repository allows you to freely experiment
without affecting the original project. If you have made changes and you want to add
them and contribute to the project, all you have to do is issue a pull request. This is
where you send the proposed changes to the owner of the project. After reviewing
your request, he either can merge it to the master repository or reject your request.

Conclusion
Kudos to you for making it this far!
We can fairly say we have mastered Git & GitHub!

But, there’s always more to learn.

We can now work with remote repositories and keep track of the differents
versions of our code. We can also work and collaborate with teams in
order to build large projects.

You might also like