0% found this document useful (0 votes)
44 views53 pages

Week 4

FSD Theory notes

Uploaded by

awolf8918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views53 pages

Week 4

FSD Theory notes

Uploaded by

awolf8918
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Week4_Day1_Session2

Understanding JavaScript fundamentals is essential for becoming proficient in web


development. Here's a comprehensive overview covering code structure, variables, constants,
data types, interaction, operators, comparisons, control flow, and functions:

1. Code Structure

Statements

• Statements: Instructions executed by the browser, usually ending with a semicolon (;), though
it's not always mandatory.

javascript
Copy code
let x = 5; // This is a statement
Comments

• Single-line comments: Use // for comments on a single line.

javascript
Copy code
// This is a single-line comment

• Multi-line comments: Use /* ... */ for comments that span multiple lines.

javascript
Copy code
/* This is a
multi-line comment */

2. Variables

• var: Function-scoped variable declaration.

javascript
Copy code
var name = "John";

• let: Block-scoped variable declaration.

javascript
Copy code
let age = 25;
• const: Block-scoped constant declaration; must be initialized at the time of declaration.

javascript
Copy code
const PI = 3.14;

3. Data Types

Primitive Data Types

• String: Sequence of characters.

javascript
Copy code
let name = "Alice";

• Number: Numeric values (integers and floating-point numbers).

javascript
Copy code
let number = 42;
let temperature = 36.6;

• Boolean: Logical values true or false.

javascript
Copy code
let isAdult = true;

• Undefined: Variable that has been declared but not assigned a value.

javascript
Copy code
let x;
console.log(x); // undefined

• Null: Represents the intentional absence of any object value.

javascript
Copy code
let y = null;

• Symbol: Unique and immutable primitive value.


javascript
Copy code
let sym = Symbol('description');
Complex Data Types

• Object: Collection of key-value pairs.

javascript
Copy code
let person = {
name: "John",
age: 30
};

4. Interaction

Alert

• alert(): Displays a message to the user.

javascript
Copy code
alert("Hello, world!");
Prompt

• prompt(): Displays a dialog box that prompts the user for input.

javascript
Copy code
let userName = prompt("Please enter your name:");
Confirm

• confirm(): Displays a dialog box with OK and Cancel buttons.

javascript
Copy code
let isConfirmed = confirm("Are you sure?");

5. Operators

Arithmetic Operators

• +: Addition
• -: Subtraction
• *: Multiplication
• /: Division
• %: Remainder
• **: Exponentiation

javascript
Copy code
let result = 5 + 3; // 8
Assignment Operators

• =: Assign
• +=: Add and assign
• -=: Subtract and assign
• *=: Multiply and assign
• /=: Divide and assign

javascript
Copy code
let x = 10;
x += 5; // x is now 15
Comparison Operators

• ==: Equal to
• ===: Strict equal to
• !=: Not equal to
• !==: Strict not equal to
• >: Greater than
• <: Less than
• >=: Greater than or equal to
• <=: Less than or equal to

javascript
Copy code
let isEqual = (5 == '5'); // true
let isStrictEqual = (5 === '5'); // false
Logical Operators

• &&: Logical AND


• ||: Logical OR
• !: Logical NOT

javascript
Copy code
let isAdult = true;
let hasPermission = false;
let canEnter = isAdult && hasPermission; // false

6. Control Flow

Conditional Statements

• if: Executes a block of code if the condition is true.

javascript
Copy code
if (x > 10) {
console.log("x is greater than 10");
}

• else: Executes a block of code if the condition is false.

javascript
Copy code
if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is 10 or less");
}

• else if: Specifies a new condition if the first condition is false.

javascript
Copy code
if (x > 10) {
console.log("x is greater than 10");
} else if (x === 10) {
console.log("x is exactly 10");
} else {
console.log("x is less than 10");
}
Switch Statement

• switch: Evaluates an expression and matches its value to a case clause.

javascript
Copy code
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Unknown day");
}
Loops

• for: Loops through a block of code a number of times.

javascript
Copy code
for (let i = 0; i < 5; i++) {
console.log(i);
}

• while: Loops through a block of code as long as a specified condition is true.

javascript
Copy code
let i = 0;
while (i < 5) {
console.log(i);
i++;
}

• do while: Also loops through a block of code while a specified condition is true, but the block
of code is executed once before the condition is tested.

javascript
Copy code
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
7. Functions

Function Declaration

• Named function: A function that is declared and can be called by its name.

javascript
Copy code
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice"));
Function Expression

• Anonymous function: A function that is assigned to a variable.

javascript
Copy code
let greet = function(name) {
return "Hello, " + name;
};
console.log(greet("Bob"));
Arrow Function

• Arrow function: A concise way to write functions using the => syntax.

javascript
Copy code
let greet = (name) => "Hello, " + name;
console.log(greet("Charlie"));

Example Putting It All Together

Here's a simple example combining various JavaScript fundamentals:

javascript
Copy code
// Function to calculate the sum of two numbers
function sum(a, b) {
return a + b;
}

// Variables
let num1 = 10;
let num2 = 20;

// Calculate the sum


let total = sum(num1, num2);

// Output the result using an alert


alert("The sum of " + num1 + " and " + num2 + " is " + total);

// Check if the sum is greater than 25


if (total > 25) {
console.log("The sum is greater than 25");
} else {
console.log("The sum is 25 or less");
}

// Loop through numbers 1 to 5 and print them


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

// Interaction using prompt and confirm


let userName = prompt("Enter your name:");
let isConfirmed = confirm("Is your name " + userName + "?");

if (isConfirmed) {
console.log("User confirmed their name as " + userName);
} else {
console.log("User did not confirm their name");
}

This example demonstrates basic function usage, variable declaration, arithmetic operations,
conditionals, loops, and user interaction. By understanding and mastering these JavaScript
fundamentals, you can build more complex and efficient web applications.

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for
humans to read and write and easy for machines to parse and generate. Here’s a
comprehensive guide to understanding and using JSON.

What is JSON?
JSON is a text format for representing structured data based on JavaScript object syntax. It is
commonly used for transmitting data in web applications (e.g., sending data from a server to
a client).

JSON Structure

JSON data is written as key/value pairs.

json
Copy code
{
"name": "John",
"age": 30,
"city": "New York"
}

JSON Data Types

1. String

json
Copy code
{ "name": "John" }

2. Number

json
Copy code
{ "age": 30 }

3. Boolean

json
Copy code
{ "isStudent": false }

4. Array

json
Copy code
{ "hobbies": ["reading", "traveling", "swimming"] }

5. Object
json
Copy code
{
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
}
}

6. Null

json
Copy code
{ "middleName": null }

JSON Syntax Rules

• Data is in name/value pairs.


• Data is separated by commas.
• Curly braces {} hold objects.
• Square brackets [] hold arrays.

JSON vs. JavaScript Object

While JSON and JavaScript objects look similar, there are key differences:

• JSON is a string format for data exchange.


• JavaScript objects are used within JavaScript code.
Week4_Day2

4.1 JAVASCRIPT OBJECTS

In JavaScript, almost "everything" is an object.

1. Booleans can be objects (if defined with the new keyword)


2. Numbers can be objects (if defined with the new keyword)
3. Strings can be objects (if defined with the new keyword)
4. Dates are always objects
5. Maths are always objects
6. Regular expressions are always objects
7. Arrays are always objects
8. Functions are always objects
9. Objects are always objects
10. All JavaScript values, except primitives, are objects.

JavaScript Primitives
A primitive value is a value that has no properties or methods. Examples String, number, Boolean,
null, undefined, symbol, bigint, Immutable. Primitive values are immutable (they are hardcoded
and cannot be changed).

if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.

"Hello" string "Hello" is always "Hello"

3.14 number 3.14 is always 3.14


true boolean true is always true
false boolean false is always false
null null (object) null is always null
undefined undefined undefined is always undefined

Objects are Variables


JavaScript variables can contain single values:

Example
let person = "John Doe";
JavaScript variables can also contain many values. Objects are variables too. But objects can
contain many values. Object values are written as name : value pairs (name and value separated
by a colon).

Example
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
A JavaScript object is a collection of named values. It is a common practice to declare objects with
the const keyword.

Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

JavaScript Object Methods


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

What is this?
In JavaScript, the this keyword refers to an object.Which object depends on how this is being
invoked (used or called).The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.Alone, this refers to the global object.In a function,
this refers to the global object.In a function, in strict mode, this is undefined.In an event, this refers
to the element that received the event.Methods like call(), apply(), and bind() can refer this to any
object.

JavaScript Methods
JavaScript methods are actions that can be performed on objects. A JavaScript method is a
property containing a function definition.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
Methods are functions stored as object properties.

Accessing Object Methods


You access an object method with the following syntax:

objectName.methodName()
You will typically describe fullName() as a method of the person object, and fullName as a
property. The fullName property will execute (as a function) when it is invoked with (). This example
accesses the fullName() method of a person object:

Example
name = person.fullName();
If you access the fullName property, without (), it will return the function definition:

Example
name = person.fullName;

Adding a Method to an Object


Adding a new method to an object is easy:

Example
person.name = function ()
{
return this.firstName + " " + this.lastName;
};

Using Built-In Methods


This example uses the toUpperCase() method of the String object, to convert a text to uppercase:

let message = "Hello world!";


let x = message.toUpperCase();
The value of x, after execution of the code above will be:

HELLO WORLD!
Example
person.name = function ()
{
return (this.firstName + " " + this.lastName).toUpperCase();
};

JavaScript Object Constructors


function Person(first, last, age, eye)
{
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

Object Types (Blueprints) (Classes)


The examples from the previous chapters are limited. They only create single objects Sometimes
we need a "blueprint" for creating many objects of the same "type". The way to create an "object
type", is to use an object constructor function. In the example above, function Person() is an object
constructor function.

Objects of the same type are created by calling the constructor function with the new keyword:

const myFather = new Person("John", "Doe", 50, "blue");


const myMother = new Person("Sally", "Rally", 48, "green");

Note
this is not a variable. It is a keyword. You cannot change the value of this.

Adding a Property to an Object

Example
myFather.nationality = "English";
The property will be added to myFather. Not to myMother. (Not to any other person objects).

Adding a Method to an Object


Adding a new method to an existing object is easy:

Example
myFather.name = function () {
return this.firstName + " " + this.lastName;
};
The method will be added to myFather. Not to myMother. (Not to any other person objects).

Adding a Property to a Constructor


You cannot add a new property to an object constructor the same way you add a new property
to an existing object:

Example
Person.nationality = "English";
To add a new property to a constructor, you must add it to the constructor function:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
This way object properties can have default values.

Adding a Method to a Constructor


Your constructor function can also define methods:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.name = function() {
return this.firstName + " " + this.lastName;
};
}
You cannot add a new method to an object constructor the same way you add a new method to
an existing object.

Adding methods to an object constructor must be done inside the constructor function:

Example
function Person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
this.changeName = function (name) {
this.lastName = name;
};
}
The changeName() function assigns the value of name to the person's lastName property.

Now You Can Try:


myMother.changeName("Doe");
JavaScript knows which person you are talking about by "substituting" this with myMother.

Built-in JavaScript Constructors


JavaScript has built-in constructors for native objects:

new String() // A new String object


new Number() // A new Number object
new Boolean() // A new Boolean object
new Object() // A new Object object
new Array() // A new Array object
new RegExp() // A new RegExp object
new Function() // A new Function object
new Date() // A new Date object
The Math() object is not in the list. Math is a global object. The new keyword cannot be used on
Math.

JavaScript has object versions of the primitive data types String, Number, and Boolean. But there
is no reason to create complex objects. Primitive values are much faster:

Use string literals "" instead of new String().

Use number literals 50 instead of new Number().

Use boolean literals true / false instead of new Boolean().

Use object literals {} instead of new Object().

Use array literals [] instead of new Array().

Use pattern literals /()/ instead of new RegExp().

Use function expressions () {} instead of new Function().

Example
let x1 = ""; // new primitive string
let x2 = 0; // new primitive number
let x3 = false; // new primitive boolean

const x4 = {}; // new Object object


const x5 = []; // new Array object
const x6 = /()/ // new RegExp object
const x7 = function(){}; // new function
String Objects
Normally, strings are created as primitives: firstName = "John"

But strings can also be created as objects using the new keyword:
firstName = new String("John")

Learn why strings should not be created as object in the chapter JS Strings.

Number Objects
Normally, numbers are created as primitives: x = 30
But numbers can also be created as objects using the new keyword:
x = new Number(30)

Learn why numbers should not be created as object in the chapter JS Numbers.

Boolean Objects
Normally, booleans are created as primitives: x = false

But booleans can also be created as objects using the new keyword:
x = new Boolean(false)

Learn why booleans should not be created as object in the chapter JS Booleans.

JavaScript Object Properties


Properties are the most important part of any JavaScript object.

JavaScript Properties
Properties are the values associated with a JavaScript object.

A JavaScript object is a collection of unordered properties. Properties can usually be changed,


added, and deleted, but some are read only.

Accessing JavaScript Properties


The syntax for accessing the property of an object is:

objectName.property // person.age
or

objectName["property"] // person["age"]
or

objectName[expression] // x = "age"; person[x]


The expression must evaluate to a property name.

Example 1
person.firstname + " is " + person.age + " years old.";
Example 2
person["firstname"] + " is " + person["age"] + " years old.";

JavaScript for...in Loop


The JavaScript for...in statement loops through the properties of an object.

Syntax
for (let variable in object) {
// code to be executed
}
The block of code inside of the for...in loop will be executed once for each property.

Looping through the properties of an object:

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

for (let x in person) {


txt += person[x];
}
Adding New Properties
You can add new properties to an existing object by simply giving it a value.

Assume that the person object already exists - you can then give it new properties:

Example
person.nationality = "English";
Deleting Properties
The delete keyword deletes a property from an object:

Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

delete person.age;
or delete person["age"];

Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person["age"];
The delete keyword 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. The delete operator should
not be used on predefined JavaScript object properties. It can crash your application.

Nested Objects
Values in an object can be another object:

Example
myObj = {
name:"John",
age:30,
cars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
You can access nested objects using the dot notation or the bracket notation:

Example
myObj.cars.car2;
or:

Example
myObj.cars["car2"];
or:

Example
myObj["cars"]["car2"];
or:

Example
let p1 = "cars";
let p2 = "car2";
myObj[p1][p2];
Nested Arrays and Objects
Values in objects can be arrays, and values in arrays can be objects:

Example
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}
To access arrays inside arrays, use a for-in loop for each array:

Example
for (let i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
Property Attributes
All properties have a name. In addition they also have a value. The value is one of the property's
attributes. Other attributes are: enumerable, configurable, and writable. These attributes define
how the property can be accessed (is it readable?, is it writable?) In JavaScript, all attributes can
be read, but only the value attribute can be changed (and only if the property is writable).

Prototype Properties
JavaScript objects inherit the properties of their prototype. The delete keyword does not delete
inherited properties, but if you delete a prototype property, it will affect all objects inherited from
the prototype.

JavaScript Object Accessors


JavaScript Getter (The get Keyword)
This example uses a lang property to get the value of the language property.

Example
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language;
}
};

// Display data from the object using a getter:


document.getElementById("demo").innerHTML = person.lang;
JavaScript Setter (The set Keyword)
This example uses a lang property to set the value of the language property.

Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang;
}
};

// Set an object property using a setter:


person.lang = "en";

// Display data from the object:


document.getElementById("demo").innerHTML = person.language;

JavaScript Function or Getter?


What is the differences between these two examples?

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

// Display data from the object using a method:


document.getElementById("demo").innerHTML = person.fullName();
Example 2
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object using a getter:


document.getElementById("demo").innerHTML = person.fullName;
Example 1 access fullName as a function: person.fullName().

Example 2 access fullName as a property: person.fullName.

The second example provides a simpler syntax.

Data Quality
JavaScript can secure better data quality when using getters and setters.

Using the lang property, in this example, returns the value of the language property in upper case:

Example
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language.toUpperCase();
}
};

// Display data from the object using a getter:


document.getElementById("demo").innerHTML = person.lang;
Using the lang property, in this example, stores an upper case value in the language property:

Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang.toUpperCase();
}
};

// Set an object property using a setter:


person.lang = "en";

// Display data from the object:


document.getElementById("demo").innerHTML = person.language;
Why Using Getters and Setters?
It gives simpler syntax
It allows equal syntax for properties and methods
It can secure better data quality
It is useful for doing things behind-the-scenes
Object.defineProperty()
The Object.defineProperty() method can also be used to add Getters and Setters:

A Counter Example
// Define object
const obj = {counter : 0};

// Define setters and getters


Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (value) {this.counter -= value;}
});

// Play with the counter:


obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

JavaScript Object Prototypes


All JavaScript objects inherit properties and methods from a prototype.
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

const myFather = new Person("John", "Doe", 50, "blue");


const myMother = new Person("Sally", "Rally", 48, "green");
We also learned that you can not add a new property to an existing object constructor:

Example
Person.nationality = "English";
To add a new property to a constructor, you must add it to the constructor function:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}

Prototype Inheritance
All JavaScript objects inherit properties and methods from a prototype:

Date objects inherit from Date.prototype


Array objects inherit from Array.prototype
Person objects inherit from Person.prototype
The Object.prototype is on the top of the prototype inheritance chain:

Date objects, Array objects, and Person objects inherit from Object.prototype.

Adding Properties and Methods to Objects


Sometimes you want to add new properties (or methods) to all existing objects of a given type.

Sometimes you want to add new properties (or methods) to an object constructor.

Using the prototype Property


The JavaScript prototype property allows you to add new properties to object constructors:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

Person.prototype.nationality = "English";
The JavaScript prototype property also allows you to add new methods to objects constructors:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
Week4_Day3

4.2 ES6

Arrow functions were introduced in ES6. Arrow functions allow us to write shorter function
syntax:

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

Before Arrow:
hello = function() {
return "Hello World!";
}

With Arrow Function:


hello = () => {
return "Hello World!";
}

It gets shorter! If the function has only one statement, and the statement returns a value, you can
remove the brackets and the return keyword:

Arrow Functions Return Value by Default:


hello = () => "Hello World!";

Note: This works only if the function has only one statement.

If you have parameters, you pass them inside the parentheses:

Arrow Function With Parameters:


hello = (val) => "Hello " + val;

In fact, if you have only one parameter, you can skip the parentheses as well:

Arrow Function Without Parentheses:


hello = val => "Hello " + val;

What About this?


The handling of this is also different in arrow functions compared to regular functions. In
short, with arrow functions there are no binding of this.In regular functions the this keyword
represented the object that called the function, which could be the window, the document, a
button or whatever.With arrow functions the this keyword always represents the object that
defined the arrow function.Let us take a look at two examples to understand the difference.
Both examples call a method twice, first when the page loads, and once again when the user clicks
a button. The first example uses a regular function, and the second example uses an arrow
function. The result shows that the first example returns two different objects (window and
button), and the second example returns the window object twice, because the window object is
the "owner" of the function.

Example
With a regular function this represents the object that calls the function:

// Regular Function:
hello = function() {
document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:


window.addEventListener("load", hello);

// A button object calls the function:


document.getElementById("btn").addEventListener("click", hello);

Example
With an arrow function this represents the owner of the function:

// Arrow Function:
hello = () => {
document.getElementById("demo").innerHTML += this;
}

// The window object calls the function:


window.addEventListener("load", hello);

// A button object calls the function:


document.getElementById("btn").addEventListener("click", hello);

Remember these differences when you are working with functions. Sometimes the behavior of
regular functions is what you want, if not, use arrow functions.

JavaScript Template Literals


Back-Tics Syntax
Template Literals use back-ticks (``) rather than the quotes ("") to define a string:

Example
let text = `Hello World!`;
Quotes Inside Strings
With template literals, you can use both single and double quotes inside a string:

Example
let text = `He's often called "Johnny"`;

Multiline Strings
Template literals allows multiline strings:

Example
let text =`The quick brown fox jumps over the lazy dog`;

Interpolation
Template literals provide an easy way to interpolate variables and expressions into strings. The
method is called string interpolation.

The syntax is:

Variable Substitutions
Template literals allow variables in strings:

Example
let firstName = "John";
let lastName = "Doe";

let text = `Welcome ${firstName}, ${lastName}!`;

Automatic replacing of variables with real values is called string interpolation.

Expression Substitution
Template literals allow expressions in strings:

Example
let price = 10;
let VAT = 0.25;

let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;

Automatic replacing of expressions with real values is called string interpolation.

HTML Templates
Example
let header = "Templates Literals";
let tags = ["template literals", "javascript", "es6"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
html += `<li>${x}</li>`;
}

html += `</ul>`;

Prototype methods

The prototype property allows you to add properties and methods to any object (Number,
Boolean, String and Date, etc.).

Note − Prototype is a global property which is available with almost all the objects.

Use the following syntax to create a Boolean prototype.

object.prototype.name = value
Example
The following example shows how to use the prototype property to add a property to an object.

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Tom");
book.prototype.price = null;
myBook.price = 100;
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
The following output is displayed on successful execution of the above code.
Book title is : Perl
Book author is : Tom
Book price is : 100

Spread Operator
The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or
object into another array or object.

Example
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

The spread operator is often used in combination with destructuring.

Example
Assign the first and second items from numbers to variables and put the rest in an array:

const numbers = [1, 2, 3, 4, 5, 6];

const [one, two, ...rest] = numbers;

We can use the spread operator with objects too:

Example
Combine these two objects:

const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}

const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
}

const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}

MAP
ES6 is a series of new features that are added to the JavaScript. Prior to ES6, when we
require the mapping of keys and values, we often use an object. It is because the object allows us
to map a key to the value of any type.

ES6 provides us a new collection type called Map, which holds the key-value pairs in which values
of any type can be used as either keys or values. A Map object always remembers the actual
insertion order of the keys. Keys and values in a Map object may be primitive or objects. It returns
the new or empty Map.

Maps are ordered, so they traverse the elements in their insertion order.

Syntax
For creating a new Map, we can use the following syntax:

var map = new Map([iterable]);


The Map () accepts an optional iterable object, whose elements are in the key-value pairs.

Map Properties
S.no. Properties Description
1. Map.prototype.size This property returns the number of key-value pairs in the Map
object.
Let us understand the above property of Map object in brief.

Map.prototype.size
It returns the number of elements in the Map object.

Syntax

Map.size
Example

var map = new Map();


map.set('John', 'author');
map.set('arry', 'publisher');
map.set('Mary', 'subscriber');
map.set('James', 'Distributor');

console.log(map.size);
Output

4
Map Methods
The Map object includes several methods, which are tabulated as follows:
S.no. Methods Description
1. Map.prototype.clear() It removes all the keys and values pairs from the Map object.
2. Map.prototype.delete(key) It is used to delete an entry.
3. Map.prototype.has(value) It checks whether or not the corresponding key is in the Map
object.
4. Map.prototype.entries() It is used to return a new iterator object that has an array of
key-value pairs for every element in the Map object in insertion order.
5. Map.prototype.forEach(callbackFn[, thisArg]) It executes the callback function once, which
is executed for each element in the Map.
6. Map.prototype.keys() It returns an iterator for all keys in the Map.
7. Map.prototype.values() It returns an iterator for every value in the Map.
Weak Maps
Weak Maps are almost similar to normal Maps except that the keys in weak maps must be objects.
It stores each element as a key-value pair where keys are weakly referenced. Here, the keys are
objects, and the values are arbitrary values. A Weak Map object only allows the keys of an object
type. If there is no reference to a key object, then they are targeted to garbage collection. In weak
Map, the keys are not enumerable. So, there is no method to get the list of keys.

A weak map object iterates its elements in the insertion order. It only includes delete(key),
get(key), has(key) and set(key, value) method.

Let us try to understand the illustration of the weak Map.

Example
'use strict'
let wp = new WeakMap();
let obj = {};
console.log(wp.set(obj,"Welcome to javaTpoint"));
console.log(wp.has(obj));
Output

WeakMap { <items unknown> }


true
The for...of loop and Weak Maps
The for...of loop is used to perform an iteration over keys, values of the Map object. The following
example will illustrate the traversing of the Map object by using a for...of loop.

Example
'use strict'
var colors = new Map([
['1', 'Red'],
['2', 'Green'],
['3', 'Yellow'],
['4', 'Violet']
]);

for (let col of colors.values()) {


console.log(col);
}

console.log(" ")

for(let col of colors.entries())


console.log(`${col[0]}: ${col[1]}`);
Output

Red
Green
Yellow
Violet

1: Red
2: Green
3: Yellow
4: Violet
Iterator and Map
An iterator is an object, which defines the sequence and a return value upon its termination. It
allows accessing a collection of objects one at a time. Set and Map both include the methods that
return an iterator.

Iterators are the objects with the next() method. When the next() method gets invoked, the iterator
returns an object along with the "value" and "done" properties.

Let us try to understand some of the implementations of iterator along with the Map object.

Example-1
'use strict'
var colors = new Map([
['1', 'Red'],
['2', 'Green'],
['3', 'Yellow'],
['4', 'Violet']
]);

var itr = colors.values();


console.log(itr.next());
console.log(itr.next());
console.log(itr.next());
Output

{ value: 'Red', done: false }


{ value: 'Green', done: false }
{ value: 'Yellow', done: false }
Example-2
'use strict'
var colors = new Map([
['1', 'Red'],
['2', 'Green'],
['3', 'Yellow'],
['4', 'Violet']
]);
var itr = colors.entries();
console.log(itr.next());
console.log(itr.next());
console.log(itr.next());
Output

{ value: [ '1', 'Red' ], done: false }


{ value: [ '2', 'Green' ], done: false }
{ value: [ '3', 'Yellow' ], done: false }
Example-3
'use strict'
var colors = new Map([
['1', 'Red'],
['2', 'Green'],
['3', 'Yellow'],
['4', 'Violet']
]);

var itr = colors.keys();


console.log(itr.next());
console.log(itr.next());
console.log(itr.next());
Output

{ value: '1', done: false }


{ value: '2', done: false }
{ value: '3', done: false }

ES6 Set
A set is a data structure that allows you to create a collection of unique values. Sets are
the collections that deal with single objects or single values.

Set is the collection of values similar to arrays, but it does not contain any duplicates. It allows us
to store unique values. It supports both primitive values and object references.

As similar to maps, sets are also ordered, i.e., the elements in sets are iterated in their insertion
order. It returns the set object.

Syntax
var s = new Set("val1","val2","val3");
Let us understand the concept of set by using the following example:

Example
let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);
console.log(colors);
All the elements of a Set must be unique. Therefore the set colors in the above example only
contain four distinct elements. We will get the following output after the successful execution of
the above code.

Output

Set { 'Green', 'Red', 'Orange', 'Yellow' }


Let us see the properties and methods of the Set.

Set Properties
S.no. Properties Description
1. Set.sizeThis property returns the number of values in the set object.
Set.size
This property of the Set object returns the value that represents the number of elements in the
Set object.

Example

let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


console.log(colors.size);
console.log(colors);
Output

4
Set { 'Green', 'Red', 'Orange', 'Yellow' }
Set Methods
The set object includes several methods, which are tabulated as follows:
S.no. Methods Description
1. Set.prototype.add(value) It appends a new element to the given value of the set
object.
2. Set.prototype.clear() It removes all the elements from the set object.
3. Set.prototype.delete(value) It removes the element which is associated with the
corresponding value.
4. Set.prototype.entries() It returns a new iterator object, which contains an array of each
element in the Set object in insertion order.
5. Set.prototype.forEach(callbackFn[, thisArg]) It executes the callback function once.
6. Set.prototype.has(value) This method returns true when the passed value is in the Set.
7. Set.prototype.values() It returns the new iterator object, which contains the values for each
element in the Set, in insertion order.
Now, we are going to understand the above methods of the Set object in detail.

Set.prototype.add(value)
This method is used to append a new element with the existing value to the Set object.

Example
let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);
colors.add('Violet');
colors.add('Indigo');
colors.add('Blue');
colors.add('Violet');
console.log(colors.size);
console.log(colors);
Output

7
Set { 'Green', 'Red', 'Orange', 'Yellow', 'Violet', 'Indigo', 'Blue' }
Set.prototype.clear()
It clears all the objects from the sets.

Example

let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


colors.add('Violet');
colors.add('Indigo');
colors.add('Blue');
colors.add('Violet');
colors.clear()
console.log(colors.size);
Output

0
Set.prototype.delete(value)
This method is used to remove the corresponding passed value from the set object.

Example

let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


colors.add('Violet');
colors.add('Indigo');
colors.add('Blue');
colors.add('Violet');
colors.delete('Violet');
console.log(colors.size);
console.log(colors);
Output

6
Set { 'Green', 'Red', 'Orange', 'Yellow', 'Indigo', 'Blue' }
Set.prototype.entries()
It returns the object of a new set iterator. It contains an array of values for each element. It
maintains the insertion order.

Example

let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


colors.add('Violet');
colors.add('Indigo');
colors.add('Blue');
colors.add('Violet');
var itr = colors.entries();
for(i=0;i<colors.size;i++) {
console.log(itr.next().value);
}
Output

[ 'Green', 'Green' ]
[ 'Red', 'Red' ]
[ 'Orange', 'Orange' ]
[ 'Yellow', 'Yellow' ]
[ 'Violet', 'Violet' ]
[ 'Indigo', 'Indigo' ]
[ 'Blue', 'Blue' ]
Set.prototype.forEach(callbackFn[, thisArg])
It executes the specified callback function once for each Map entry.
Example

let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


colors.add('Violet');
colors.add('Indigo');
colors.add('Blue');
colors.add('Violet');
function details(values){
console.log(values);
}
colors.forEach(details);
Output

Green
Red
Orange
Yellow
Violet
Indigo
Blue
Set.prototype.has(value)
It returns the Boolean value that indicates whether the element, along with the corresponding
value, exists in a Set object or not.
Example

let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);


colors.add('Violet');
colors.add('Indigo');
colors.add('Blue');
colors.add('Violet');
console.log(colors.has('Indigo'));
console.log(colors.has('Violet'));
console.log(colors.has('Cyan'));
Output

true
true
false
Set.prototype.values()
It returns a new iterator object that includes the values for each element in the Set object in the
insertion order.

Example
let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);
colors.add('Violet');

var val = colors.values();


console.log(val.next().value);
console.log(val.next().value);
console.log(val.next().value);
console.log(val.next().value);
console.log(val.next().value);

Output
Green
Red
Orange
Yellow
Violet
Weak Set
It is used to store the collection of objects. It is similar to the Set object, so it also cannot store
duplicate values. Similar to weak maps, weak sets cannot be iterated. Weak sets can contain only
objects which may be garbage collected.

Weak set only includes add(value), delete(value) and has(value) methods of Set object.

Example
'use strict'
let ws = new WeakSet();
let obj = {msg:"Welcome Back!"};
ws.add(obj);
console.log(ws.has(obj));
ws.delete(obj);
console.log(ws.has(obj));
Output
true
false

Iterators
An iterator is an object which defines the sequence and a return value upon its termination. It
allows accessing a collection of objects one at a time. Set and Map both include the methods that
return an iterator.

Iterators are the objects with the next() method. When the next() method gets invoked, the iterator
returns an object along with the 'value' and 'done' properties.
The 'done' is a Boolean which returns true after reading all of the elements in the collection.
Otherwise, it returns false.

Let's understand the implementations of iterator along with the Set object.

Example
let colors = new Set(['Green', 'Red', 'Orange', 'Yellow', 'Red']);
var itr = colors.keys();
var itr1 = colors.entries();
var itr2 = colors.values();
console.log(itr.next());
console.log(itr1.next());
console.log(itr2.next());
Output

{ value: 'Green', done: false }


{ value: [ 'Green', 'Green' ], done: false }
{ value: 'Green', done: false }
Week4_Day4

TypeScript Tutorial

TypeScript is Typed JavaScript. TypeScript adds types to JavaScript to help you speed up the
development by catching errors before you even run the JavaScript code.

TypeScript is an open-source programming language that builds on top of JavaScript. It works


on any browser, any OS, any environment that JavaScript runs.

Why TypeScript?

1. Static Typing: TypeScript introduces static typing, allowing developers to define the
types of variables, function parameters, and return values. This helps catch type-related
errors at compile time rather than runtime.
2. Enhanced IDE Support: TypeScript provides better code completion, navigation, and
refactoring capabilities in modern IDEs like Visual Studio Code.
3. Improved Maintainability: Static types make it easier to understand and maintain large
codebases, facilitating better collaboration among developers.
4. Modern JavaScript Features: TypeScript supports the latest JavaScript features (ES6 and
beyond) and provides backward compatibility with older JavaScript versions.
5. Optional Type Annotations: Developers can gradually adopt TypeScript in existing
JavaScript projects by adding type annotations incrementally.

Basic Types

TypeScript provides several basic types:

• Boolean

typescript
Copy code
let isDone: boolean = false;

• Number

typescript
Copy code
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

• String
typescript
Copy code
let color: string = "blue";
color = 'red';

• Array

typescript
Copy code
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];

• Tuple

typescript
Copy code
let x: [string, number];
x = ["hello", 10];

• Enum

typescript
Copy code
enum Color { Red, Green, Blue }
let c: Color = Color.Green;

• Any

typescript
Copy code
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;

• Void

typescript
Copy code
function warnUser(): void {
console.log("This is my warning message");
}

Control Flow Statements


TypeScript supports standard control flow statements similar to JavaScript:

• If-Else

typescript
Copy code
let num: number = 10;
if (num > 5) {
console.log("Num is greater than 5");
} else {
console.log("Num is less than or equal to 5");
}

• For Loop

typescript
Copy code
for (let i: number = 0; i < 5; i++) {
console.log(i);
}

• While Loop

typescript
Copy code
let i: number = 0;
while (i < 5) {
console.log(i);
i++;
}

Functions

Functions in TypeScript can have typed parameters and return types:

• Basic Function

typescript
Copy code
function add(x: number, y: number): number {
return x + y;
}
let sum: number = add(5, 3);
• Optional and Default Parameters

typescript
Copy code
function buildName(firstName: string, lastName?: string): string {
if (lastName) {
return firstName + " " + lastName;
} else {
return firstName;
}
}
typescript
Copy code
function buildName(firstName: string, lastName: string = "Smith"): string {
return firstName + " " + lastName;
}

• Rest Parameters

typescript
Copy code
function buildName(firstName: string, ...restOfName: string[]): string {
return firstName + " " + restOfName.join(" ");
}
Week4_Day6_Session1

1. React

React is one of the simplest frameworks to learn and perfect for a developer. It was initially developed at

Facebook as a fixture to code maintenance issues due to the constant additions of new features and design

updates of the Facebook app.

2. Angular
If there is a list of best front-end UI frameworks, it is incomplete without Angular. Also, Angular is probably the

only framework on this list that is based on a TypeScript. Launched back in 2016, the framework was developed

by Google mainly to bridge the gap between the conventional concept that generate results and the

constantly increasing demands of technological advancements.

3. Flutter
Flutter is one of the fastest-growing open-source frameworks. Flutter was developed for the first time in 2015,

especially for Android developers. But for the following three years, Google took over the team behind Flutter

to support Android and iOS. Finally, they released the first official version of Flutter called Flutter 1.0 for iOS

and Android in 2018.

4. Vue.js
Vue has become one of the most popular front-end frameworks recently. It is a straightforward and simple

framework that is good at eradicating any complexities mainly faced by other framework developers. Apart

from this, it is a component-based framework comparatively smaller in size and offers visual DOM. A lot

of custom essay writing companies claim to use it for building their user interface.

5. JQuery
Introduced back in 2006, JQuery is one of the very first front-end frameworks. But despite its old-school launch,

it has still made it on this list decades later and is relevant to this day because of its tremendous performance

over the years.

6. Emberjs
Emberjs is a component-based, two-way data binding framework developed in 2011. It has been designed in-

particular to tackle increasing technological advancements seamlessly. However, unlike others on this list, you

may find Emberjs as one of the toughest frameworks to learn and understand. Despite its efficient architecture,

it is rigid and conventional in structure. Also, the developer community is smaller, considering that it is under-

explored, given many other better options.

7. Semantic UI
Semantic UI is on its way to becoming one of the most popular front-end frameworks despite being relatively

new. What made it stand out amongst many others known globally was its intuitive UI and simple functionality

and usability.

8. Backbonejs
Backbonejs is one of the easiest frameworks out there. You can develop single-page applications quickly and

efficiently. Based on MVC (Model-View-Controller) architecture, the view allows component logic

implementation. It allows developers to use third-party tools like Thorax, Marionette, Chaplin, Handlebars, and

many more that make the best use of the framework swift and easy.

9. Foundation

Among the back-end and front-end frameworks we have discussed on this list, Foundation is something

different. Developed by Zurb and implemented by big names like Mozilla, eBay, Microsoft, and more,

Foundation is meant for industrial and company-level website development.

10. Svelte
One more front-end framework but relatively a recent one has made it on our list. The framework made a

difference because unlike React or Vue, Svelte worked into a compiled step instead of putting it in the browser.

It is best used to write the code to update the DOM or document object model and align it with the state of

the application model.

You might also like