0% found this document useful (0 votes)
29 views14 pages

Meanstack Mid Questions

Node.js is a JavaScript runtime environment that allows JavaScript to be run on the server side. It allows JavaScript code to directly interact with files, databases, streams, and other system-level resources. A web server can be created in Node.js using the built-in HTTP module which allows Node.js to transfer data over HTTP. The HTTP module can create an HTTP server that listens to server ports and gives responses back to clients.
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)
29 views14 pages

Meanstack Mid Questions

Node.js is a JavaScript runtime environment that allows JavaScript to be run on the server side. It allows JavaScript code to directly interact with files, databases, streams, and other system-level resources. A web server can be created in Node.js using the built-in HTTP module which allows Node.js to transfer data over HTTP. The HTTP module can create an HTTP server that listens to server ports and gives responses back to clients.
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/ 14

Explain about types of functions in Java Script?

➔ A function is a set of instructions


➔ It can be used repeatedly in a program
➔ It increases modularity
➔ In JavaScript ,functions are object that can be declared, assigned and
passed as parameters to other function
➔ JavaScript functions are enabling developers to write code that is more
organized , efficient , and easier to debug
➔ Ther are several types of JavaScript functions, each with its own purpose
and usage
1) Named parameter less functions
2) Named parameterized function
3) Function expressions
4) Anonymous functions
5) Named functions expressions
6) Immediately invoked function expression(IIFEs)
7) Arrow function
8) Generate function
9) Async function

1) Named parameter less functions:-


➔ Named function are functions declarations that include a name
➔ They are also sometimes referred to as traditional function or function
declarations
➔ Named function are typically used when the same code needs to be
executed multiple times through out a program
➔ They should always be declared before they are used
Example:
Function MyWorld()
{
Console.log(‘sai shankar and harika’); }
MyWorld();
2) Named parameterized function:-
➔ The JavaScript functions which takes parameters
➔ More control and more efficient

Example:

Function Add(a,b)

Console.log(a+b);

Add(10,20);

3) Function expression:-

➔ The function keyword can be used to define a function inside an


expression.
➔ You can also define functions using the function declaration

Example:

const getRectArea = function (width, height) {

return width * height;

};

console.log(getRectArea(3, 4));

4) Anonymous function:-

➔ Anonymous function are function expressions that do not have a


name associated with them
➔ They are also sometimes referred as lambda function expressions
➔ Anonymous function are typically used when the same code needs
to be executed only once or twice throughout a program
➔ They can be assigned to variables or passed as parameters to
other function
Example:

Let jimmy = function()

Console.log(“hello jimmy”);

5) Named functions expressions:-

➔ Using the function keyword followed by a name that can be used as


a callback to that function is known as using a named function in
JavaScript.
➔ Named functions are regular functions that have a name or identifier.
➔ Both their use in expressions and their declaration in statements are
options.
➔ The name of the function is stored in the body, which is useful.

Example:

var fibo = function fibonacci(number) {


if (number <= 1) return 1;
return fibonacci(number - 1) + fibonacci(number - 2);
};
console.log(fibo(5));

6) IIFEs:-
➔ An immediately invoked function expression (IIFEs)
➔ It is a function expressions that expression that is
defined an execute immediately after its creation
➔ It is wrapped in parentheses to make it an
expression and followed by an additional set of
parentheses to invoke it
➔ To create closures
➔ IIFEs is used to create private and public variable
and methods
Example:
<script>
(function(dt){
document.write(dt.to locate time string());
})(newdate());
</script>

7) Arrow function:-
➔ They are a short hand syntax for anonymous function
that was introduced in ECMAScript (ES-6)
➔ They are also sometimes referred as fat arrow
function or lambda short hand
➔ Arrow function are typically used when writing
concise code and when same code needs to be execute
only once or twice throughout a program
➔ They can be assigned to variables or passed as
parameters to other function
Example:
Let helloworld = () =>{
Console.log(“hello world”);
}
Alert (helloworld);

8) Generator function:-
➔ Generator or generator function is the new concept
introduced in ES-6
➔ Generator function are a special kind of function
that can be paused and resumed during execution
➔ It provie=des you a new way of eorking eith itrators
and functions
➔ They are defined using the function * keyword
➔ Generator don’t provide random access
Example:
<script>
Function * greet(name)
{
Yield “good morning”;
yield “hello how are you”;
}
Const msg = greet(“sree leela”)
Console.log(msg.next().value);
Console.log(msg.next().value);
</script>
9) Async function:-
➔ The keyword async before a function makes the function return a
promise
Example:
function myFunction() {
return Promise.resolve("Hello");
}

Explain about file operations with examples in Node.js?

➔ The Node.js file system module allows you to work with


the file system on your computer.To include the File
System module, use the require() method

var fs = require('fs');

➔ Common use for the File System module:

• Read files
• Create files
• Update files
• Delete files
• Rename files

• Read Files
• The fs.readFile() method is used to read files on your
computer.
• Assume we have the following HTML file (located in the
same folder as Node.js)
• Example:
<html>
<body>
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-
Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
</body>
</html>

Create Files
The File System module has methods for creating new files:

• fs.appendFile()
• fs.open()
• fs.writeFile()

The fs.appendFile() method appends specified content to a


file. If the file does not exist, the file will be created

Example:

var fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello
content!', function (err) {
if (err) throw err;
console.log('Saved!');
});

Update Files
The File System module has methods for updating files:

• fs.appendFile()
• fs.writeFile()

The fs.appendFile() method appends the specified content at


the end of the specified file

Example:

var fs = require('fs');

fs.appendFile('mynewfile1.txt', ' This is my


text.', function (err) {
if (err) throw err;
console.log('Updated!');
});

Delete Files
To delete a file with the File System module, use
the fs.unlink() method.

The fs.unlink() method deletes the specified file

Example:

var fs = require('fs');

fs.unlink('mynewfile2.txt', function (err) {


if (err) throw err;
console.log('File deleted!');
});

Rename Files
To rename a file with the File System module, use
the fs.rename() method.

The fs.rename() method renames the specified file

Example:

var fs = require('fs');

fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function


(err) {
if (err) throw err;
console.log('File Renamed!');
});
Write about Rest Operator, Spread operator
and Destructuring Objects?
Destructuring object:-
➔ JavaScript object Destructuring is a mechanism for
extracting values from an object property and
assigning them to a variable
➔ The destructuring is also possible foe JavaScript
arrays
➔ By default the object key name becomes the variables
that holds the respective value
➔ So no extra code is required to create another
variable for value assignment
➔ Object destructuring assigns the properties of an
object to variable with the same name by default

Example:
Consider this example, an object that represents a note with
an id, title, and date
const note = {
id: 1,
title: 'My first note',
date: '01/01/1970',
}

Spread operator:-
➔ A JavaScript object is a collection of key value
pairs
➔ It is an non primitive data type that can contain
various data types
➔ The spread operator could not be used with object
when it was first introduced in ES6
➔ The spread operator was eventully extended to object
in ES2018
➔ We can use the spread operator (…) to unpack elements
of an array
➔ Cloning and merging the array is simple through the
spread operator

Example:
// Create an Array
const tools = ['hammer', 'screwdriver']
const otherTools = ['wrench', 'saw']

// Concatenate tools and otherTools together


const allTools = tools.concat(otherTools)

// Unpack the tools Array into the allTools Array


const allTools = [...tools, ...otherTools]

console.log(allTools)

Rest operator:-

➔ The syntax appears the same as spread (...) but has the
opposite effect. Instead of unpacking an array or object into
individual values, the rest syntax will create an array of an
indefinite number of arguments.
➔ the rest parameter is mostly used with destructuring
syntax to consolidate the remaining properties in a new
object
Example:
const user = {
'name': 'Alex',
'address': '15th Park Avenue',
'age': 43
}
const {age, ...rest} = user;
console.log(age, rest);
what is node.js and Create a web server in
Node.js?
node.js:

➔ Node.js is an open-source server environment. Node.js uses


JavaScript on the server. The task of a web server is to open a file on
the server and return the content to the client.
➔ Node.js has a built-in module called HTTP, which allows Node.js to
transfer data over the Hyper Text Transfer Protocol (HTTP).
➔ The HTTP module can create an HTTP server that listens to server
ports and gives a response back to the client.

Web server:
const http=require("http");
const server=http.createServer((req,res)=>{
res.write("welcome to node js");
res.end();
})
server.listen("5500");

Explain about Asynchronous Programming? Write


in detail about callback, Promises, Async and
Await with examples?

Asynchronous programming:-
➔ asynchronous programming provides opportunities for a
program to continue running other code while waiting for a
long-running task to complete.
➔ Also known as nonblocking code
➔ The feature that enables asynchronous programming in these
languages is referred to as a callback function.
➔ It defines the relationship between two or more objects that
interact with each other within the same environment or system,
but at different time phases or time instant, and also does not
affect each other such as offline learning.
➔ We can also understand it with a simple example of an email, as in
this, people respond as per their convenience; hence it is an
asynchronous event.

➔ In asynchronous communication, both sender and receiver have


their internal clock; hence no synchronization is required.

➔ The data is sent from one end to another in the form of a byte of
characters.

➔ Callback, Promise, and async/await are all different ways to


handle asynchronous operations in JavaScript.

Callback:-

➔ A callback is a function that is passed as an argument to another


function and is executed after the first function completes its
operation.
➔ Callbacks are commonly used in JavaScript for handling
asynchronous operations, such as making an HTTP request.

Example:

function getData(callback) {

setTimeout(() => {

const data = 'Some data';

callback(data);

}, 1000);

getData((data) => {

console.log(data); });
Promises:-

➔ A promise is an object that represents the eventual completion (or


failure) of an asynchronous operation and its resulting value.
➔ Promises provide a simpler way to handle asynchronous operations
compared to callbacks by allowing you to chain multiple operations
together and handle errors in a more elegant way.

Example:

function getData() {

return new Promise((resolve, reject) => {

setTimeout(() => {

const data = 'Some data';

resolve(data);

}, 1000);

});

getData()

.then((data) => {

console.log(data);

})

.catch((error) => {

console.log(error);

});
Async/Await:

➔ Async/await is a more recent addition to JavaScript that provides a


way to write asynchronous code that looks and behaves like
synchronous code.

➔ It uses the async keyword to declare a function that returns a


promise, and the await keyword to wait for a promise to
resolve before continuing with the execution.

Example:

async function getData() {

return new Promise((resolve, reject) => {

setTimeout(() => {

const data = 'Some data';

resolve(data);

}, 1000);

});

async function main() {

const data = await getData();

console.log(data);

main();

You might also like