Week 4
Week 4
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
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
javascript
Copy code
var name = "John";
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
javascript
Copy code
let name = "Alice";
javascript
Copy code
let number = 42;
let temperature = 36.6;
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
javascript
Copy code
let y = null;
javascript
Copy code
let person = {
name: "John",
age: 30
};
4. Interaction
Alert
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
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
javascript
Copy code
let isAdult = true;
let hasPermission = false;
let canEnter = isAdult && hasPermission; // false
6. Control Flow
Conditional Statements
javascript
Copy code
if (x > 10) {
console.log("x is greater than 10");
}
javascript
Copy code
if (x > 10) {
console.log("x is greater than 10");
} else {
console.log("x is 10 or less");
}
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
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
javascript
Copy code
for (let i = 0; i < 5; i++) {
console.log(i);
}
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
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"));
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;
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
Copy code
{
"name": "John",
"age": 30,
"city": "New York"
}
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 }
While JSON and JavaScript objects look similar, there are key differences:
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.
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"};
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.
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;
Example
person.name = function ()
{
return this.firstName + " " + this.lastName;
};
HELLO WORLD!
Example
person.name = function ()
{
return (this.firstName + " " + this.lastName).toUpperCase();
};
Objects of the same type are created by calling the constructor function with the new keyword:
Note
this is not a variable. It is a keyword. You cannot change the value of this.
Example
myFather.nationality = "English";
The property will be added to myFather. Not to myMother. (Not to any other person objects).
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).
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.
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.
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:
Example
let x1 = ""; // new primitive string
let x2 = 0; // new primitive number
let x3 = false; // new primitive boolean
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 Properties
Properties are the values associated with a JavaScript object.
objectName.property // person.age
or
objectName["property"] // person["age"]
or
Example 1
person.firstname + " is " + person.age + " years old.";
Example 2
person["firstname"] + " is " + person["age"] + " years old.";
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.
Example
const person = {
fname:" John",
lname:" Doe",
age: 25
};
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.
Example
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language;
}
};
Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang;
}
};
Example 1
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
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();
}
};
Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang.toUpperCase();
}
};
A Counter Example
// Define object
const obj = {counter : 0};
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, Array objects, and Person objects inherit from Object.prototype.
Sometimes you want to add new properties (or methods) to an object constructor.
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:
Before Arrow:
hello = function() {
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:
Note: This works only if the function has only one statement.
In fact, if you have only one parameter, you can skip the parentheses as well:
Example
With a regular function this represents the object that calls the function:
// Regular Function:
hello = function() {
document.getElementById("demo").innerHTML += this;
}
Example
With an arrow function this represents the owner of the function:
// Arrow Function:
hello = () => {
document.getElementById("demo").innerHTML += this;
}
Remember these differences when you are working with functions. Sometimes the behavior of
regular functions is what you want, if not, use arrow functions.
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.
Variable Substitutions
Template literals allow variables in strings:
Example
let firstName = "John";
let lastName = "Doe";
Expression Substitution
Template literals allow expressions in strings:
Example
let price = 10;
let VAT = 0.25;
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.
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];
Example
Assign the first and second items from numbers to variables and put the rest in an array:
Example
Combine these two objects:
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
}
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:
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
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.
Example
'use strict'
let wp = new WeakMap();
let obj = {};
console.log(wp.set(obj,"Welcome to javaTpoint"));
console.log(wp.has(obj));
Output
Example
'use strict'
var colors = new Map([
['1', 'Red'],
['2', 'Green'],
['3', 'Yellow'],
['4', 'Violet']
]);
console.log(" ")
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']
]);
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 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
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
0
Set.prototype.delete(value)
This method is used to remove the corresponding passed value from the set object.
Example
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
[ '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
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
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');
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
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.
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
• 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");
}
• 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
• 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
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
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
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
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-
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,
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