FSD 2
FSD 2
Example:
```javascript
let count = 10;
if (true) {
let count = 20; // This is a different variable than the one outside the block
console.log(count); // 20
}
console.log(count); // 10
```
- `const`: The `const` keyword is used to declare constants in JavaScript. Constants
must be initialized with a value and cannot be reassigned or redeclared. However, for
objects and arrays declared with `const`, their properties or elements can be modified.
Example:
```javascript
const PI = 3.14159;
// PI = 3.14; // Error: Assignment to constant variable
const colors = ['red', 'green', 'blue'];
colors.push('yellow'); // Allowed, as we're modifying the array contents
Spread Operator (`...`) in ES6
The spread operator (`...`) in ES6 is used to expand iterable objects (like arrays or
strings) into individual elements. It allows us to unpack elements from an array or object
and use them in places where multiple elements or key-value pairs are expected.
In ES6 (ECMAScript 2015), the syntax for defining functions was enhanced with the
introduction of arrow functions (`=>`). Here's a comparison between ES6 and
TypeScript syntax for functions:
In TypeScript, we can add type annotations to function parameters and return types,
enhancing the clarity and maintainability of the code.
The spread operator (`...`) in ES6 is used to expand iterable objects like arrays into
individual elements. It can also be used for object spreading to clone or merge objects.
In TypeScript, arrow functions can have type annotations for parameters and return
types, providing additional type safety and clarity.
Template literals in ES6 are a way to create strings that allow embedded expressions
and multiline strings. They are enclosed by backticks (` `) instead of single or double
quotes.
Destructuring assignment in ES6 allows you to unpack values from arrays or objects
into distinct variables.
// Object destructuring
const person = { firstName: 'John', lastName: 'Doe' };
const { firstName, lastName } = person;
console.log(firstName, lastName); // Output: John Doe
```
Creating a Class in ES6
greet() {
return `Hello, ${this.firstName} ${this.lastName}!`;
}
}
Inheritance in ES6
Inheritance in ES6 is achieved using the `extends` keyword to create subclasses (child
classes) that inherit from a superclass (parent class).
speak() {
return `${this.name} makes a noise`;
}
}
Modules in TypeScript are used to organize code into reusable components and
facilitate better code structure and maintainability. TypeScript supports both
CommonJS (`require`/`exports`) and ES6 (`import`/`export`) module formats.
Type narrowing in TypeScript refers to refining the type of a variable within a conditional
block based on type predicates or guards.
TypeScript Decorator
@logClass
class MyClass {
// Class implementation
}
```
Generics in TypeScript
Generics in TypeScript allow you to create reusable components that can work with a
variety of data types. They enable you to define functions, classes, or interfaces with
placeholders for types that are specified when the component is used.
Interfaces in TypeScript
Interfaces in TypeScript define the structure of objects and specify the types of their
properties and methods.
Type guards in TypeScript are used to narrow down the type of a variable within a
conditional block based on runtime checks.
TypeScript Data Types
I hope this helps clarify these TypeScript and ES6 concepts. If you have further
questions or need more examples, feel free to ask!
Unit 3
Certainly! Let's address each of these questions related to AngularJS:
The `ng-app` directive in AngularJS is used to define the root element (or the "root
scope") of an AngularJS application within an HTML document. It marks the beginning of
the AngularJS application and specifies which part of the HTML document should be
managed by AngularJS.
Example:
```html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS App</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyController">
<!-- AngularJS content goes here -->
</div>
</body>
</html>
```
In this example, `ng-app="myApp"` specifies that the `myApp` module is the root of
the AngularJS application.
In AngularJS, the scope refers to the context in which data is accessible to the AngularJS
application. Scopes are hierarchical and prototypically inherited, forming a tree-like
structure that mirrors the DOM structure of the application.
Define AngularJS and Its Key Features
In AngularJS, the `$scope` is an object that binds the "controller" and the "view" in the
MVC architecture. It acts as a data bridge between the controller and the view, allowing
data to be shared and manipulated.
The `$rootScope` is the top-level scope created for an AngularJS application. It is the
parent scope for all other scopes in the application and is used to store global data or
methods that need to be accessible across different parts of the application.
Example:
```javascript
app.controller('MyController', function($scope, $rootScope) {
$scope.name = 'John';
$rootScope.company = 'XYZ Corp';
});
```
In this example, `$scope.name` is accessible within the controller's scope, while
`$rootScope.company` is accessible globally across the entire AngularJS application.
I hope this clarifies these concepts in AngularJS. If you have further questions or need
more information, feel free to ask!
Let's address each of these questions related to AngularJS:
2. Dependency Injection (DI): AngularJS has a built-in dependency injection system that
promotes modularity and reusability of code. It allows components to be easily tested
and decoupled, leading to more maintainable applications.
Directives in AngularJS
Directives in AngularJS are special HTML attributes that modify the behavior or
appearance of DOM elements. They extend the functionality of HTML by allowing you to
create custom, reusable components and behaviors.
Example:
```html
<div ng-controller="MyController">
<input type="text" ng-model="name">
<p>Hello, {{ name }}!</p>
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
If you have more questions or need further clarification, feel free to ask!
Let's address each of these topics related to AngularJS:
<my-component></my-component>
<script>
angular.module('myApp', [])
.component('myComponent', {
template: '<h1>Hello, {{ $ctrl.name }}!</h1>',
controller: function() {
this.name = 'John';
}
});
</script>
</body>
</html>
```
In this example, we define a custom component named `myComponent` using the
`.component()` method. The component consists of a template (`<h1>Hello, {{
$ctrl.name }}!</h1>`) and a controller that sets the `name` property.
<script>
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.greeting = 'Hello, AngularJS!';
});
</script>
</body>
</html>
```
In this example, we define an AngularJS controller named `MyController` using the
`.controller()` method. The controller sets the `greeting` property on the scope, which
is displayed in the view using interpolation (`{{ greeting }}`).
<div ng-controller="MyController">
<p>{{ message }}</p>
</div>
<script>
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.message = 'Welcome to AngularJS Modules!';
});
</script>
</body>
</html>
```
In this example, we define an AngularJS module named `myApp` using the `.module()`
method. We then create a controller within the module to set the `message` property
on the scope.
AngularJS pipes (or filters) are used to format data displayed to the user. They transform
the data in the template before displaying it.
<script>
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.price = 100;
$scope.currentDate = new Date();
$scope.user = { name: 'John', age: 30 };
});
</script>
</body>
</html>
```
In this example:
- `currency`: Formats the `price` variable as a currency value.
- `date:'fullDate'`: Formats the `currentDate` variable as a full date string.
- `json`: Formats the `user` variable as a JSON string.
AngularJS routing allows you to build Single Page Applications (SPAs) by routing
different URLs to different views without reloading the entire page.
<a href="/home">Home</a>
<a href="/about">About</a>
<div ng-view></div>
<script>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: '
about.html',
controller: 'AboutController'
})
.otherwise({ redirectTo: '/home' });
})
.controller('HomeController', function($scope) {
$scope.message = 'Welcome to the Home Page!';
})
.controller('AboutController', function($scope) {
$scope.message = 'About Us';
});
</script>
</body>
</html>
```
In this example, we use `ngRoute` module to configure routing. Different URLs
(`/home` and `/about`) are mapped to corresponding templates (`home.html` and
`about.html`) and controllers (`HomeController` and `AboutController`). The `ng-
view` directive displays the template based on the current route.
Define Node.js
REPL stands for Read Eval Print Loop. The REPL terminal in Node.js is an interactive
environment that allows you to enter JavaScript code and immediately see the results. It
reads input from the user (JavaScript code), evaluates the input, prints the result, and
then loops back to wait for more input. The Node.js REPL terminal is useful for quick
experimentation and testing of JavaScript code snippets.
To start the Node.js REPL terminal, simply open your terminal or command prompt and
type `node`. You will see the `>` prompt indicating that you can start entering
JavaScript commands.
Syntax:
```javascript
setTimeout(callback, delay, arg1, arg2, ...);
```
Example:
```javascript
// Using setTimeout to execute a function after 2000 milliseconds (2 seconds)
setTimeout(() => {
console.log('2 seconds have passed.');
}, 2000);
```
In this example, the `console.log()` statement inside the callback function will be
executed after a delay of 2000 milliseconds (2 seconds).
I hope this clarifies these concepts related to Node.js. If you have further questions or
need more information, feel free to ask!
Let's address each of these questions related to Node.js:
In Node.js, a web server is a server-side program that listens for incoming HTTP
requests from clients (e.g., web browsers) and returns HTTP responses. Node.js can be
used to create web servers using the built-in `http` module.
Module in Node.js
REPL stands for Read Eval Print Loop. The REPL terminal in Node.js is an interactive
environment that allows you to enter JavaScript code, evaluate it, and see the result
immediately.
Four Common REPL Commands:
1. `.help`: Displays a list of available commands and their descriptions.
2. `.break`: Exit from multiline expressions.
3. `.clear`: Clear the current context.
4. `.exit` (or press `Ctrl + C` twice): Exit the REPL terminal.
To start the Node.js REPL terminal, simply open your terminal or command prompt and
type `node`. You will see the `>` prompt indicating that you can start entering
JavaScript commands interactively.
I hope this helps clarify these concepts about Node.js. If you have further questions or
need more information, feel free to ask!
Let's explore each of these topics related to Node.js:
Example of Blocking:
```javascript
const fs = require('fs');
Example of Non-blocking:
```javascript
const fs = require('fs');
The HTTP module in Node.js allows you to create HTTP servers and make HTTP
requests.
FS Module in Node.js
The FS (File System) module in Node.js provides file system-related functionality for
reading and writing files.
Example of FS Module:
```javascript
const fs = require('fs');
- Asynchronous Approach:
```javascript
const fs = require('fs');
The URL module in Node.js provides utilities for URL resolution and parsing.
// main.js
const math = require('./math.js');
console.log(math.add(2, 3)); // Output: 5
```
fetchData((data) => {
console.log(data); // Output: Hello, Node.js!
});
```
Promises in Node.js
Example of Promises:
```javascript
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = 'Hello, Node.js!';
resolve(data);
}, 2000);
});
}
fetchData()
.then((data) => {
console.log(data); // Output: Hello, Node.js!
})
.catch((err) => {
console.error(err);
});
```
readStream.on('end', () => {
console.log('End of file.');
});
Express.js Overview
Express.js is a popular web application framework for Node.js. It provides a robust set
of features for building web applications and APIs with Node.js. Express.js simplifies the
process of handling HTTP requests, routing, middleware integration, and more.
1. Install Express.js: First, install Express.js using npm if it's not already installed.
```bash
npm install express
```
2. Create an Express Application: Create a new JavaScript file (e.g., `app.js`) and
import Express.
```javascript
const express = require('express');
const app = express();
const port = 3000; // Port number for the server
// Define a route
app.get('/', (req, res) => {
res.send('Hello World!');
});
3. Run the Application: Execute the following command to start the Express server.
```bash
node app.js
```
Routing in Express.js refers to defining endpoints (URLs) and handling different HTTP
methods on those endpoints.
Example of Routing in Express.js:
```javascript
const express = require('express');
const app = express();
Express.js Middleware
Middleware in Express.js are functions that have access to the request and response
objects. They can modify these objects, execute additional code, terminate the request-
response cycle, or call the next middleware in the stack.
// Custom middleware
app.use((req, res, next) => {
console.log('Request received at:', new Date());
next(); // Call the next middleware
});
// Route handling
app.get('/', (req, res) => {
res.send('Hello World!');
});
To handle an HTML GET request in Express.js, you can define a route that responds with
HTML content.
These examples demonstrate basic concepts and usage of Express.js for building web
applications and APIs. If you have further questions or need more clarification, feel free
to ask!
Let's cover these topics related to Express.js and MongoDB:
1. Routing: Express.js provides a robust routing system that allows you to define
endpoints for handling different HTTP methods and URL patterns.
2. Middleware: Express.js has a powerful middleware system that enables adding
custom functionalities to the request-response cycle, such as logging, authentication,
error handling, etc.
3. Template Engines: Express.js supports various template engines (e.g., EJS, Pug) for
generating dynamic HTML content on the server.
4. Error Handling: Express.js simplifies error handling by providing middleware functions
specifically designed for error management and propagation.
To handle an HTML GET request in Express.js and respond with HTML content, you can
define a route that sends an HTML response using the `res.send()` method.
Example of Handling HTML GET Request:
```javascript
const express = require('express');
const app = express();
In Express.js, you can define routes using the `app.get()` and `app.post()` methods to
handle `GET` and `POST` HTTP methods, respectively.
To connect to a MongoDB database using Node.js, you can use the `mongodb`
package along with `mongoose` (a MongoDB object modeling tool).
// Connect to MongoDB
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true });
To create a login page using HTML and Express.js, follow these steps:
```html
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="/login" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
```
```javascript
// app.js (Express.js server)
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
```html
<!-- calculator.html -->
<!DOCTYPE html>
<html lang="en" ng-app="CalculatorApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Calculator</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="CalculatorController">
<h2>AngularJS Calculator</h2>
<input type="number" ng-model="operand1">
<input type="number" ng-model="operand2">
<button ng-click="add()">+</button>
<button ng-click="subtract()">-</button>
<button ng-click="multiply()"></button>
<button ng-click="divide()">/</button>
<p>Result: {{ result }}</p>
<script>
angular.module('CalculatorApp', [])
.controller('CalculatorController', function($scope) {
$scope.add = function() {
$scope.result = $scope.operand1 + $scope.operand2;
};
$scope.subtract = function() {
$scope.result = $scope.operand1 - $scope.operand2;
};
$scope.multiply = function() {
$scope.result = $scope.operand1 $scope.operand2;
};
$scope.divide = function() {
$scope.result = $scope.operand1 / $scope.operand2;
};
});
</script>
</body>
</html>
```
This example demonstrates how to create a basic AngularJS calculator application that
can perform arithmetic operations based on user input.