You are on page 1of 44

Front End Course

Contents
HTML … .................................................................................................................................................... 6
Introduction ......................................................................................................................................... 6
Tags ...................................................................................................................................................... 6
Anchor tag: ....................................................................................................................................... 6
Audio Tag: ......................................................................................................................................... 6
Break Tag: ......................................................................................................................................... 7
Button Tag: ....................................................................................................................................... 7
Div Tag: ............................................................................................................................................. 7
Footer Tag:........................................................................................................................................ 7
Form Tag: .......................................................................................................................................... 8
Iframe Tag:........................................................................................................................................ 8
H tags: .............................................................................................................................................. 8
hr Tag: .............................................................................................................................................. 8
Image tag:......................................................................................................................................... 8
Input Tag:.......................................................................................................................................... 9
Label tag: ........................................................................................................................................ 10
List Tag:........................................................................................................................................... 10
Link tag: .......................................................................................................................................... 10
Nav tag: .......................................................................................................................................... 10
Ordered List Tag: ............................................................................................................................. 10
Option Tag: ..................................................................................................................................... 11
Script Tag: ....................................................................................................................................... 11
Select tag: ....................................................................................................................................... 11
Span Tag: ........................................................................................................................................ 11
Strong Tag: ...................................................................................................................................... 11
Style Tag: ........................................................................................................................................ 12
Table Tag: ........................................................................................................................................ 12
td Tag:............................................................................................................................................. 12
Text area tag: .................................................................................................................................. 12
Unordered List tag: ......................................................................................................................... 13
Video tag: ....................................................................................................................................... 13
CSS… ...................................................................................................................................................... 14
Three Ways to Insert CSS ................................................................................................................... 14
External CSS:....................................................................................................................................... 14
Internal CSS: ....................................................................................................................................... 14
Inline CSS:........................................................................................................................................... 15
CSS Element Selector: ......................................................................................................................... 15
CSS id Selector: ................................................................................................................................... 15
CSS class Selector: .............................................................................................................................. 15
Background Color: .............................................................................................................................. 16
Background Image: ............................................................................................................................. 16
Borders: .............................................................................................................................................. 16
Margin................................................................................................................................................ 17
Padding: ............................................................................................................................................. 17
Height &Width: .................................................................................................................................. 18
Text Color: .......................................................................................................................................... 18
Text-Align: .......................................................................................................................................... 19
Text-decoration: ................................................................................................................................. 19
Font-Family:........................................................................................................................................ 19
REACT JS ............................................................................................................................................ 20
React JSX ............................................................................................................................................ 20
Example: ......................................................................................................................................... 20
React Components ............................................................................................................................. 20
React Props ........................................................................................................................................ 20
React Events ....................................................................................................................................... 21
Adding Events: ................................................................................................................................ 21
React Conditional Rendering ........................................................................................................... 21
React Router: ...................................................................................................................................... 21
Add React Router ............................................................................................................................ 21
React Hooks........................................................................................................................................ 21
React use State Hook ...................................................................................................................... 21
Import useState................................................................................................................................. 22
Example Initialize useState .............................................................................................................. 22
Example: ......................................................................................................................................... 22
React useEffect Hooks .......................................................................................................................... 22
React use Context Hook ....................................................................................................................... 22
React useCallback Hook ...................................................................................................................... 23
React use Memo Hook .......................................................................................................................... 24
JAVA SCRIPT............................................................................................................................................ 24
Introduction: ...................................................................................................................................... 24
JavaScript Can Change HTML Content ......................................................................................... 24
JavaScript Can Change HTML Styles (CSS) .................................................................................. 24
Example .......................................................................................................................................... 24
Script Tag ............................................................................................................................................ 24
Example .......................................................................................................................................... 24
JavaScript Functions and Events ..................................................................................................... 24
JavaScript in <head> or <body> ...................................................................................................... 25
JavaScript in <head> ........................................................................................................................ 25
Example .......................................................................................................................................... 25
JavaScript Output ............................................................................................................................... 25
JavaScript Display Possibilities ......................................................................................................... 25
Using document.write() .................................................................................................................. 25
Example .......................................................................................................................................... 25
JavaScript Statements ..................................................................................................................... 26
JavaScript Programs ............................................................................................................................ 26
JavaScript Statements ......................................................................................................................... 26
Example .......................................................................................................................................... 26
JavaScript Keywords ........................................................................................................................... 26
JavaScript Syntax ................................................................................................................................. 27
JavaScript Values ................................................................................................................................ 28
JavaScript Literals ............................................................................................................................... 28
JavaScript Variables ............................................................................................................................ 28
JavaScript Operators ........................................................................................................................... 28
JavaScript Keywords ........................................................................................................................... 29
JavaScript Comments.......................................................................................................................... 29
JavaScript Identifiers / Names ............................................................................................................. 29
JavaScript Variables ........................................................................................................................... 29
Variables are Containers for Storing Data ........................................................................................ 29
JavaScript Let .................................................................................................................................. 29
JavaScript Const .............................................................................................................................. 30
Cannot be Reassigned ....................................................................................................................... 30
Example .......................................................................................................................................... 30
Must be Assigned .............................................................................................................................. 30
Correct ........................................................................................................................................... 30
Incorrect ......................................................................................................................................... 30
Constant Objects and Arrays ............................................................................................................... 30
Constant Arrays .................................................................................................................................. 31
Example .......................................................................................................................................... 31
Example .......................................................................................................................................... 31
Constant Objects ................................................................................................................................ 31
Example .......................................................................................................................................... 31
JavaScript Operators .......................................................................................................................... 31
JavaScript Assignment..................................................................................................................... 32
Assignment Examples ..................................................................................................................... 32
Types of JavaScript Operators ......................................................................................................... 32
JavaScript Data Types ........................................................................................................................ 32
JavaScript has 8 Datatypes .............................................................................................................. 32
The Object Datatype ....................................................................................................................... 32
Examples ........................................................................................................................................ 33
JavaScript Functions .......................................................................................................................... 33
Example ......................................................................................................................................... 33
Function Invocation ........................................................................................................................ 33
Function Return .............................................................................................................................. 33
Example .......................................................................................................................................... 34
JavaScript Objects .................................................................................................................................. 34
Real Life Objects, Properties, and Methods ......................................................................................... 34
JavaScript Objects ........................................................................................................................... 34
JavaScript Events............................................................................................................................. 34
HTML Events ................................................................................................................................... 34
Example .......................................................................................................................................... 35
JavaScript Strings ............................................................................................................................... 35
Example ......................................................................................................................................... 35
JavaScript String Methods ................................................................................................................. 35
JavaScript Template Literals ................................................................................................................ 35
JavaScript Numbers ............................................................................................................................. 36
Example ......................................................................................................................................... 36
JavaScript Number Methods ............................................................................................................... 36
JavaScript Number Methods ........................................................................................................... 36
JavaScript Arrays ............................................................................................................................... 36
JavaScript Array Methods................................................................................................................ 36
JavaScript Array toString() ............................................................................................................... 37
Example .......................................................................................................................................... 37
JavaScript Date Objects ....................................................................................................................... 37
Examples ........................................................................................................................................ 37
JavaScript Date Formats .................................................................................................................. 37
JavaScript Date Input ...................................................................................................................... 37
JavaScript Get Date Methods .......................................................................................................... 37
The new Date() Constructor ............................................................................................................. 37
Get the Current Time ...................................................................................................................... 37
Comparison Operators ........................................................................................................................ 38
JavaScript if, else, and else if................................................................................................................ 38
Conditional Statements .................................................................................................................... 38
The if Statement ............................................................................................................................. 38
Syntax ............................................................................................................................................. 38
JavaScript Switch Statement ............................................................................................................... 38
The JavaScript Switch Statement ..................................................................................................... 38
Syntax ............................................................................................................................................. 38
JavaScript For Loop ......................................................................................................................... 39
JavaScript Loops .............................................................................................................................. 39
Instead of writing:........................................................................................................................... 39
You can write: ................................................................................................................................. 39
JavaScript For In .............................................................................................................................. 39
The For In Loop................................................................................................................................ 39
Syntax ............................................................................................................................................. 39
Example .......................................................................................................................................... 39
JavaScript For Of ............................................................................................................................. 40
The For of Loop ................................................................................................................................ 40
Syntax ............................................................................................................................................. 40
JavaScript While Loop ..................................................................................................................... 40
The While Loop ................................................................................................................................ 40
Syntax ............................................................................................................................................. 40
Example .......................................................................................................................................... 40
Example .......................................................................................................................................... 40
JavaScript Break and Continue ........................................................................................................ 40
The Break Statement .......................................................................................................................... 41
Example .......................................................................................................................................... 41
The Continue Statement ..................................................................................................................... 41
Example .......................................................................................................................................... 41
JavaScript Maps .................................................................................................................................. 41
How to Create a Map........................................................................................................................ 41
The new Map () Method ................................................................................................................. 41
Example .......................................................................................................................................... 41
// Create a Map const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); ....... 42
The JavaScript this Keyword ............................................................................................................ 42
Example ......................................................................................................................................... 42
JavaScript Arrow Function................................................................................................................... 42
JavaScript Class Syntax ........................................................................................................................ 42
Syntax ............................................................................................................................................. 42
Example ......................................................................................................................................... 42
JavaScript Modules ............................................................................................................................. 42
Modules ............................................................................................................................................. 42
Example .......................................................................................................................................... 43

HTML …
Introduction
USING HTML TAGS , ELEMENTS for Creating a Web Page…
<html>
<head>
<title>Title of the document</title>
</head>

<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>

</html>

Tags

Anchor tag:

<ahref=" ">uday!</a>

A linked page is normally displayed in the current browser window, unless you specify another
target.

Audio Tag:

<audio controls>
<sourcesrc="horse.ogg" type="audio/ogg">
<sourcesrc="horse.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>
The <audio> tag is used to embed sound content in a document, such as music or other audio
streams.

Break Tag:

<br>

The <br> tag inserts a single line break.

Button Tag:

<button type="button">Click Me!</button>

The <button> tag defines a clickable button.

Div Tag:

<div class="myDiv">
<h2>This is a heading in a div element</h2>
<p>This is some text in a div element.</p>
</div>

The <div> tag defines a division or a section in an HTML document.

The <div> tag is used as a container for HTML elements - which is then styled with CSS or
manipulated with JavaScript.

Footer Tag:

<footer>
<p>Author: Hege Refsnes</p>
<p><ahref="mailto:hege@example.com">hege@example.com</a></p>
</footer>

The <footer> tag defines a footer for a document or section.

A <footer> element typically contains:

 authorship information
 copyright information
 contact information
 sitemap
 back to top links
 related documents

You can have several <footer> elements in one document.


Form Tag:

<form action="/action_page.php" method="get">


<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>

The <form> tag is used to create an HTML form for user input.

The <form> element can contain one or more of the following form elements:

 <input>
 <textarea>
 <button>
 <select>
 <option>
 <optgroup>
 <fieldset>
 <label>
 <output>
 <output>

Iframe Tag:

<iframesrc=" "></iframe>

Use the <iframe> tag to embed another document within the current HTML document

H tags:

<h1>This is heading 1</h1>


<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

The <h1> to <h6> tags are used to define HTML headings.

<h1> defines the most important heading. <h6> defines the least important heading.

hr Tag:

<hr>

The <hr> tag defines a thematic break in an HTML page

Image tag:
<imgsrc="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">

The <img> tag is used to embed an image in an HTML page.

Images are not technically inserted into a web page; images are linked to web pages. The <img>
tag creates a holding space for the referenced image.

The <img> tag has two required attributes:

 src - Specifies the path to the image


 alt - Specifies an alternate text for the image, if the image for some reason cannot be
displayed.

Input Tag:

<input type="text" id="fname" name="fname">

The <input> tag specifies an input field where the user can enter data.

The <input> element is the most important form element.

The <input> element can be displayed in several ways, depending on the type attribute.

The different input types are as follows:

 <input type="button">
 <input type="checkbox">
 <input type="color">
 <input type="date">
 <input type="datetime-local">
 <input type="email">
 <input type="file">
 <input type="hidden">
 <input type="image">
 <input type="month">
 <input type="number">
 <input type="password">
 <input type="radio">
 <input type="range">
 <input type="reset">
 <input type="search">
 <input type="submit">
 <input type="tel">
 <input type="text"> (default value)
 <input type="time">
 <input type="url">
<input type="week"

Label tag:

<label for="html">HTML</label>

Proper use of labels with the elements above will benefit:

List Tag:

<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

The <li> tag defines a list item.

The <li> tag is used inside ordered lists(<ol>), unordered lists (<ul>), and in menu lists
(<menu>).

Link tag:

<linkrel="stylesheet"href="styles.css">

The <link> tag defines the relationship between the current document and an external resource.

The <link> tag is most often used to link to external style sheets or to add a favicon to your
website.

Nav tag:

<nav>
<ahref="/html/">HTML</a> |
<ahref="/css/">CSS</a> |
<ahref="/js/">JavaScript</a> |
<ahref="/python/">Python</a>
</nav>

The <nav> tag defines a set of navigation links.

Notice that NOT all links of a document should be inside a <nav> element. The <nav>
element is intended only for major blocks of navigation links.

Ordered List Tag:


The <ol> tag defines an ordered list. An ordered list can be numerical or alphabetical.

The <li> tag is used to define each list item.

Option Tag:

<select id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

The <option> tag defines an option in a select list.

Script Tag:

<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>

The <script> tag is used to embed a client-side script (JavaScript).

Select tag:

<select name="cars" id="cars">


<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>

The <select> element is used to create a drop-down list.

The <select> element is most often used in a form, to collect user input.

Span Tag:

<p>My mother has <span style="color:blue">blue</span> eyes.</p>

The <span> tag is an inline container used to mark up a part of a text, or a part of a document.

The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id
attribute.

The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is
an inline element.

Strong Tag:

<strong>This text is important!</strong>


The <strong> tag is used to define text with strong importance. The content inside is typically
displayed in bold.

Tip: Use the <b> tag to specify bold text without any extra importance!

Style Tag:

<style>
h1 {color:red;}
p {color:blue;}
</style>

The <style> tag is used to define style information (CSS) for a document.

Inside the <style> element you specify how HTML elements should render in a browser

Table Tag:

<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>

The <table> tag defines an HTML table.

An HTML table consists of one <table> element and one or more <tr>, <th>, and <td> elements.

The <tr> element defines a table row, the <th> element defines a table header, and the <td>
element defines a table cell.

An HTML table may also include <caption>, <colgroup>, <thead>, <tfoot>, and <tbody>
elements.

and <tbody> elements.

td Tag:

<tr>
<td>Cell C</td>
<td>Cell D</td>
</tr>

The <td> tag defines a standard data cell in an HTML table.

Text area tag:


<textarea id="w3review" name="w3review" rows="4" cols="50">
At w3schools.com you will learn how to make a website. They offer free tutorials in all web
development technologies.
</textarea>

The <textarea> tag defines a multi-line text input control.

The <textarea> element is often used in a form, to collect user inputs like comments or reviews.

underline tag:

<u>mispeled</u>

The <u> tag represents some text that is unarticulated and styled differently from normal text,
such as misspelled words or proper names in Chinese text. The content inside is typically
displayed with an underline. You can change this with CSS (see example below).

Unordered List tag:

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

The <ul> tag defines an unordered (bulleted) list.

Use the <ul> tag together with the <li> tag to create unordered lists.

Video tag:

<video width="320" height="240" controls>


<sourcesrc="movie.mp4" type="video/mp4">
<sourcesrc="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

The <video> tag is used to embed video content in a document, such as a movie clip or other
video streams.
CSS…

Three Ways to Insert CSS


There are three ways of inserting a style sheet:

 External CSS
 Internal CSS
 Inline CSS

External CSS:
<linkrel="stylesheet"href="mystyle.css">

An external style sheet can be written in any text editor, and must be saved with a .css extension.

The external .css file should not contain any HTML tags.

Internal CSS:

<head>
<style>
body {
background-color: linen;
}

h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>

An inline style may be used to apply a unique style for a single element.

To use inline styles, add the style attribute to the relevant element. The style attribute can contain
any CSS property.
Inline CSS:

<h1 style="color:blue;text-align:center;">This is a heading</h1>

CSS Element Selector:

p{
text-align: center;
color: red;
}

The element selector selects HTML elements based on the element name.

Here, all <p> elements on the page will be center-aligned, with a red text color.

CSS id Selector:

#para1 {
text-align: center;
color: red;
}

The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one unique
element!

To select an element with a specific id, write a hash (#) character, followed by the id of the
element.

CSS class Selector:

.container {
text-align: center;
color: red;
}

The class selector selects HTML elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the class name.
Background Color:

body {
background-color:lightblue;
}

The background-color property specifies the background color of an element.

Background Image:

body {
background-image:url("paper.gif");
}

body {
background-image:url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}

The background-image property specifies an image to use as the background of an element.

By default, the image is repeated so it covers the entire element.

Borders:

p.dotted{border-style: dotted;}
p.dashed{border-style: dashed;}
p.solid{border-style: solid;}
p.double{border-style: double;}
p.groove{border-style: groove;}
p.ridge{border-style: ridge;}
p.inset{border-style: inset;}
p.outset{border-style: outset;}
p.none{border-style: none;}
p.hidden{border-style: hidden;}
p.mix{border-style: dotted dashed solid double;}

The border-style property specifies what kind of border to display.

The following values are allowed:

 dotted - Defines a dotted border


 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value
 inset - Defines a 3D inset border. The effect depends on the border-color value
 outset - Defines a 3D outset border. The effect depends on the border-color value
 none - Defines no border
 hidden - Defines a hidden border.

Margin:

p{
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}

CSS has properties for specifying the margin for each side of an element:

 margin-top
 margin-right
 margin-bottom
 margin-left

All the margin properties can have the following values:

 auto - the browser calculates the margin


 length - specifies a margin in px, pt, cm, etc.
 % - specifies a margin in % of the width of the containing element
 inherit - specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.

Padding:

div {
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}

CSS has properties for specifying the padding for each side of an element:

 padding-top
 padding-right
 padding-bottom
 padding-left

All the padding properties can have the following values:

 length - specifies a padding in px, pt, cm, etc.


 % - specifies a padding in % of the width of the containing element
 inherit - specifies that the padding should be inherited from the parent element

Note: Negative values are not allowed.

Height &Width:

div {
height: 200px;
width: 50%;
background-color:powderblue;
}

The height and width properties may have the following values:

 auto - This is default. The browser calculates the height and width
 length - Defines the height/width in px, cm, etc.
 % - Defines the height/width in percent of the containing block
 initial - Sets the height/width to its default value
 inherit - The height/width will be inherited from its parent value

Text Color:
body {
background-color:lightgrey;
color: blue;
}

h1 {
background-color: black;
color: white;
}

div {
background-color: blue;
color: white;
}

The color property is used to set the color of the text. The color is specified by:

 a color name - like "red"


 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255,0,0)"

Look at CSS Color Values for a complete list of possible color values.

The default text color for a page is defined in the body selector.
Text-Align:

h1 {
text-align: center;
}

h2 {
text-align: left;
}

h3 {
text-align: right;
}

The text-align property is used to set the horizontal alignment of a text.

A text can be left or right aligned, centered, or justified.

The following example shows center aligned, and left and right aligned text (left alignment is
default if text direction is left-to-right, and right alignment is default if text direction is right-to-
left).

Text-decoration:

h1 {
text-decoration-line: overline;
}

h2 {
text-decoration-line: line-through;
}

h3 {
text-decoration-line: underline;
}

p{
text-decoration-line: overline underline;
}

The text-decoration-line property is used to add a decoration line to text.

Tip: You can combine more than one value, like overline and underline to display lines both over
and under a text.

Font-Family:

.p1 {
font-family: "Times New Roman", Times, serif;
}
REACT JS

React JSX

JSX allows us to write HTML elements in JavaScript and place them in the DOM without
any createElement() and/or appendChild() methods.

JSX converts HTML tags into react elements.

Example:
JSX:

constmyElement=<h1>I Love JSX!</h1>;

const root =ReactDOM.createRoot(document.getElementById('root'));

root.render(myElement)

React Components

Create a Class component called Car

classCarextendsReact.Component{

render(){

return<h2>Hi, I am a Car!</h2>;

React Props

Add a "brand" attribute to the Car element:

constmyElement=<Carbrand="Ford"/>;

Use the brand attribute in the component:


functionCar(props){

return<h2>I am a {props.brand}!</h2>;

React Events

Adding Events:

React events are written in camelCase syntax:

onClick instead of onclick.

React event handlers are written inside curly braces:

onClick={shoot} instead of onClick="shoot()".

<button onClick={shoot}>Take the Shot!</button

React Conditional Rendering

We'll use these two components:

functionMissedGoal(){

return<h1>MISSED!</h1>;

functionMadeGoal(){

return<h1>Goal!</h1>;

}
React Router:

Add React Router

To add React Router in your application, run this in the terminal from the root directory of the
application:

npmi -D react-router-dom

React Hooks

React use State Hook


Import useState
To use the useState Hook, we first need to import it into our component.

Example Initialize useState


We initialize our state by calling useState in our function component.

useState accepts an initial state and returns two values:

 The current state.


 A function that updates the state.

Example:
Initialize state at the top of the function component.

import{useState}from"react";

functionFavoriteColor(){

const[color,setColor]=useState("");

At the top of your component, import the useState Hook.

import{useState}from"react";

React useEffect Hooks


useEffect(()=>{

//Runs on every render

});

React use Context Hook


To create context, you must Import createContext and initialize it:

import{useState,createContext}from"react";

importReactDOMfrom"react-dom/client";

constUserContext=createContext()
React useCallback Hook
import{useState}from"react";

importReactDOMfrom"react-dom/client";

import Todos from"./Todos";

constApp=()=>{

const[count,setCount]=useState(0);

const[todos,setTodos]=useState([]);

constincrement=()=>{

setCount((c)=> c +1);

};

constaddTodo=()=>{

setTodos((t)=>[...t,"New Todo"]);

};

return(

<>

<Todostodos={todos}addTodo={addTodo}/>

<hr/>

<div>

Count: {count}

<button onClick={increment}>+</button>

</div>

</>

);

};

const root =ReactDOM.createRoot(document.getElementById('root'));

root.render(<App/>);
React use Memo Hook
To fix this performance issue, we can use the useMemo Hook to memoize
the expensiveCalculation function. This will cause the function to only run when needed.

JAVA SCRIPT

Introduction:

JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().

EXAMPLE:

document.getElementById("demo").innerHTML = "Hello JavaScript";

JavaScript Can Change HTML Styles (CSS)


Changing the style of an HTML element, is a variant of changing an HTML attribute:

Example
document.getElementById("demo").style.fontSize = "35px";

Script Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.

The function is invoked (called) when a button is clicked:

Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph</p>


<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

JavaScript Output

JavaScript Display Possibilities

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using document.write()

For testing purposes, it is convenient to use document.write():

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

JavaScript Statements

let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4

JavaScript Programs

A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.

A JavaScript program is a list of programming statements.

JavaScript Statements

JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":

Example
document.getElementById("demo").innerHTML = "Hello Dolly.";

JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Our Reserved Words Reference lists all JavaScript keywords.

Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop

function Declares a function

return Exits a function

try Implements error handling to a block of statements

JavaScript Syntax
// How to create variables:
var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;
JavaScript Values

The JavaScript syntax defines two types of values:

 Fixed values
 Variable values

Fixed values are called Literals.

Variable values are called Variables.

JavaScript Literals

The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

10.50

1001

2. Strings are text, written within double or single quotes:

"John Doe"

'John Doe'
JavaScript Variables

In a programming language, variables are used to store data values.

JavaScript uses the keywords var, let and const to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

let x;
x = 6;

JavaScript Operators

JavaScript uses arithmetic operators ( + - * / ) to compute values:

(5 + 6) * 10

JavaScript uses an assignment operator ( = ) to assign values to variables:

let x, y;
x = 5;
y = 6;
JavaScript Keywords

JavaScript keywords are used to identify actions to be performed.

The let keyword tells the browser to create variables:

let x, y;
x = 5 + 6;
y = x * 10;

JavaScript Comments

Not all JavaScript statements are "executed".

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed:

let x = 5; // I will be executed

// x = 6; I will NOT be executed

JavaScript Identifiers / Names

Identifiers are JavaScript names.

Identifiers are used to name variables and keywords, and functions.

The rules for legal names are the same in most programming languages.

A JavaScript name must begin with:

 A letter (A-Z or a-z)


 A dollar sign ($)
 Or an underscore (_)

Subsequent characters may be letters, digits, underscores, or dollar signs.

JavaScript Variables

Variables are Containers for Storing Data


JavaScript Variables can be declared in 4 ways:

 Automatically
 Using var
 Using let
 Using const

JavaScript Let

The let keyword was introduced in ES6 (2015)


Variables defined with let cannot be Redeclared

Variables defined with let must be Declared before use

Variables defined with let have Block Scope

JavaScript Const

The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

Cannot be Reassigned
A const variable cannot be reassigned:

Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error

Must be Assigned
JavaScript const variables must be assigned a value when they are declared:

Correct
const PI = 3.14159265359;

Incorrect
const PI;
PI = 3.14159265359;

Constant Objects and Arrays

The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

 Reassign a constant value


 Reassign a constant array
 Reassign a constant object

But you CAN:


 Change the elements of constant array
 Change the properties of constant object

Constant Arrays

You can change the elements of a constant array:

Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];

// You can change an element:


cars[0] = "Toyota";

// You can add an element:


cars.push("Audi");

But you can NOT reassign the array:

Example
const cars = ["Saab", "Volvo", "BMW"];

cars = ["Toyota", "Volvo", "Audi"]; // ERROR

Constant Objects

You can change the properties of a constant object:

Example
// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};

// You can change a property:


car.color = "red";

// You can add a property:


car.owner = "Johnson";

JavaScript Operators

The Addition Operator + adds numbers:


The Assignment Operator = assigns a value to a variable.

JavaScript Assignment

The Assignment Operator (=) assigns a value to a variable:

Assignment Examples
let x = 10;
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;

Types of JavaScript Operators


There are different types of JavaScript operators:

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 String Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
 Type Operators

JavaScript Data Types


JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

The Object Datatype


The object data type can contain:

1. An object
2. An array
3. A date
Examples
// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let last Name = "Johnson";

// Booleans
let x = true;
let y = false;

// Object:
const person = {first Name:"John", last Name:"Doe"};

// Array object:
const cars = ["Saab", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");

JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":

Example
Calculate the product of two numbers, and return the result:

// Function is called, the return value will end up in x


let x = myFunction(4, 3);

function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

JavaScript Objects
Real Life Objects, Properties, and Methods

In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop:

All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but the methods are performed at different times.

JavaScript Objects

You have already learned that JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

let car = "Fiat";

JavaScript Events

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>

JavaScript Strings
JavaScript strings are for storing and manipulating text.

A JavaScript string is zero or more characters written inside quotes.

Example
let text = "John Doe";

JavaScript String Methods


String length String trim()
String slice() String trimStart()
String substring() String trimEnd()
String substr() String padStart()
String replace() String padEnd()
String replaceAll() String charAt()
String toUpperCase() String charCodeAt()
String toLowerCase() String split()
String concat()

JavaScript Template Literals

Synonyms:

 Template Literals
 Template Strings
 String Templates
 Back-Tics Syntax
JavaScript Numbers
JavaScript has only one type of number. Numbers can be written with or without decimals.

Example
let x = 3.14; // A number with decimals
let y = 3; // A number without decimals

JavaScript Number Methods


JavaScript Number Methods
These number methods can be used on all JavaScript numbers:

Method Description

toString() Returns a number as a string

toExponential() Returns a number written in exponential notation

toFixed() Returns a number written with a number of decimals

toPrecision() Returns a number written with a specified length

ValueOf() Returns a number as a number

JavaScript Arrays

An array is a special variable, which can hold more than one value:

const cars = ["Saab", "Volvo", "BMW"];

JavaScript Array Methods


Array length Array join()
Array toString() Array delete()
Array pop() Array concat()
Array push() Array flat()
Array shift() Array splice()
Array unshift() Array slice()

The methods are listed in the order they appear in this tutorial page

JavaScript Array toString()

The JavaScript method toString() converts an array to a string of (comma separated) array values.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Result:

Banana, Orange, Apple, Mango

JavaScript Date Objects

JavaScript Date Objects let us work with dates:

Mon Oct 02 2023 00:06:13 GMT+0530 (India Standard Time)

Year: 2023 Month: 10 Day: 2 Hours: 0 Minutes: 6 Seconds: 13

Examples
const d = new Date();
const d = new Date("2022-03-25");

JavaScript Date Formats


JavaScript Date Input
There are generally 3 types of JavaScript date input formats:

JavaScript Get Date Methods

The new Date() Constructor


In JavaScript, date objects are created with new Date().

new Date() returns a date object with the current date and time.

Get the Current Time


const date = new Date();

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between
variables or values.

JavaScript if, else, and else if


Conditional statements are used to perform different actions based on different conditions.

Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax
if (condition) {
// block of code to be executed if the condition is true
}

JavaScript Switch Statement


The switch statement is used to perform different actions based on different conditions.

The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

JavaScript For Loop


Loops can execute a block of code a number of times.

JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a different
value.

Often this is the case when working with arrays:

Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";

You can write:


for (let i = 0; i<cars.length; i++) {
text += cars[i] + "<br>";
}

JavaScript For In

The For In Loop


The JavaScript for in statement loops through the properties of an Object:

Syntax
for (key in object) {
// code block to be executed
}

Example
const person = {fname:"John", lname:"Doe", age:25};

let text = "";


for (let x in person) {
text += person[x];
}

JavaScript For Of

The For of Loop


The JavaScript for of statement loops through the values of an iterable object.

It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more:

Syntax
for (variable of iterable) {
// code block to be executed
}

JavaScript While Loop

Loops can execute a block of code as long as a specified condition is true.

The While Loop


The while loop loops through a block of code as long as a specified condition is true.

Syntax
while (condition) {
// code block to be executed
}

Example
In the following example, the code in the loop will run, over and over again, as long as a variable (i)
is less than 10:

Example
while (i< 10) {
text += "The number is " + i;
i++;
}

JavaScript Break and Continue

The break statement "jumps out" of a loop.

The continue statement "jumps over" one iteration in the loop.


The Break Statement

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch() statement.

The break statement can also be used to jump out of a loop:

Example
for (let i = 0; i< 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}

In the example above, the break statement ends the loop ("breaks" the loop) when the loop counter (i)
is 3.

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.

This example skips the value of 3:

Example
for (let i = 0; i< 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}

JavaScript Maps

How to Create a Map


You can create a JavaScript Map by:

 Passing an Array to new Map()


 Create a Map and use Map.set()

The new Map () Method

You can create a Map by passing an Array to the new Map() constructor:

Example
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);

The JavaScript this Keyword

Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

JavaScript Arrow Function

Arrow functions were introduced in ES6.

Arrow functions allow us to write shorter function syntax:

let myFunction = (a, b) => a * b;

JavaScript Class Syntax

Use the keyword class to create a class.

Always add a method named constructor():

Syntax
class ClassName {
constructor() { ... }
}

Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}

JavaScript Modules

Modules
JavaScript modules allow you to break up your code into separate files.
This makes it easier to maintain a code-base.

Modules are imported from external files with the import statement.

Modules also rely on type="module" in the <script> tag.

Example
<script type="module">
import message from "./message.js";
</script>

You might also like