JavaScript Interview Question
1. Synchronous and Asynchronous in java Script ?
3. Callback function in javascript
4. What is promises in javascript ?
5. What is async await in javascript ?
6. Diffrence between let, var and const in javascript ?
7. What is Dom ?
8. Event loop in javascript ?
9. What is Clouser in javascript ?
10. Pure Function in javascript ?
11. What is Server Side Rendring and Client Side Rendring ?
12. What is async and defer in web development ?
Answer
1. Synchronous and Asynchronous in java Script ?
Synchronous : JavaScript language is synchronous by default. Synchronous means the code runs in a particular sequence of instructions given in the program. Each instruction waits for the previous instruction to complete its execution.
See the following code example of synchronous JavaScript .
<script>
console.log('First');
console.log('Second');
console.log('Third');
</script>
First
Second
Third
Asynchronous :
Asynchronous code execution allows to execution next instructions immediately and doesn't block the flow because of previous instructions.
just understand with bellow example
<script>
console.log("hello i am first line");
for (i = 1; i < 2000; i++) {
console.log("hello i am second line");
}
console.log("hello i am third line");
</script>
above code will block the flow of the execution, third line will display after second line will finished because of Synchronous Code.
Now See Asynchronous Code with callback function
<script>
console.log("hello i am first line");
setTimeout(() => {
for (i = 1; i < 2000; i++) {
console.log("hello i am second line");
}
}, 1000);
console.log("hello i am third line");
</script>
in above code does not block the flow of code execution because of Asynchronous programm .it will display first and third line without waiting the second line.
What is the Difference Between Synchronous vs Asynchronous JavaScript?
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top.
This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.
4. What is promises in javascript ?
promise is an object in javascript that returns a value which you hope to recieve in the future. but not now .this is mostly for asynchronous operation .
promise chaining:
example 1 :
<script>
// promise chaining
let p = new Promise((resolve, reject) => {
resolve(10);
})
p.then((data) => {
console.log(data) // 10
return data * 2;
}).then((data) => {
console.log(data)
// out will be 20 because previous then return data with multiply 2
return data * 3;
}).then(data => {
console.log(data);
// out will be 60 because previous value is 20 and multiply by 3 in prevoius then
})
</script>
here all then are bind in one P if we will do same thing in individual then you will got 10 ,10 ,10 check bellow example
<script>
// promise chaining
let p = new Promise((resolve, reject) => {
resolve(10);
})
p.then((data) => {
console.log(data) // 10
return data * 2;
})
p.then((data) => {
console.log(data) // 10
return data * 3;
})
p.then(data => {
console.log(data); //10
})
</script>
Promise.All method Example
<script>
// promise chaining
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("The first promise has resolved");
resolve(10);
}, 1*1000);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("The Second promise has resolved");
resolve(20);
}, 2*1000);
});
let p3 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("The third promise has resolved");
resolve(30);
}, 3*1000);
});
Promise.all([p1,p2,p3])
.then(result=>{
const total= result.reduce((p,c)=>p+c);
console.log(`Result: ${result}`);
console.log(`Total: ${total}`);
})
</script>
Output :
The first promise has resolved
The Second promise has resolved
The third promise has resolved
Result: 10,20,30
Total: 60
if any promise will be reject then .then method not will run .
Promise.race Example :
promise race => which promise will be first solve or reject then or catch will consume
<script>
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("The first promise has resolved");
resolve(10);
}, 2 * 1000);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("The Second promise has resolved");
resolve(20);
//reject(20);
}, 1 * 1000);
});
let p3 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("The third promise has resolved");
resolve(30);
}, 3 * 1000);
});
Promise.race([p1, p2, p3])
.then(result => { console.log(`Result: ${result}`); })
.catch(error => console.log("error" + error))
</script>
Output:
The Second promise has resolved
Result: 20
The first promise has resolved
The third promise has resolved
9. What is Closures in javascript ?
A closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.
Consider the following example code:
<script>
function callApi(method) {
return function (url) {
console.log("fetching data from " + url + " using " + method);
}
}
const URL = "hhtp://example.com/api"
// callApi("GET")(URL);
const api = callApi("GET");
api(URL);
</script>
above program is a exampe of closure .when programm will execute ,after finishing of outer function it will remove from call stack but variable will be there in side closure so that inner function can use this variable, this is closure.
Closure is useful in hiding implementation detail in JavaScript. In other words, it can be useful to create private variables or functions.we can understand this with a example so consider the the bellow code.
<script>
let count = 0;
function updateCount() {
count++;
}
updateCount();
updateCount();
// count = 5;
console.log(count);
</script>
in above example we make a counter function with name "updateCount" which increse a number,count is globle variable so we can increse a number by calling "updateCount" function multiple time. but there is problem if count variable is re-assigned by any value outside of function by mistake then we can not achive result properly.so that we will hide this variable with the help of closure.means we can not access count variable outside of function .
first we will try to put variable in local scope
<script>
function updateCount() {
let count = 0;
count++;
console.log(count);
}
updateCount();
updateCount();
</script>
but its not incresing the numner because when function is calling variable is resigning.
<script>
function counterWraper()
{
let count = 0;
return function () {
count++;
console.log(count);
}
}
updateCount = counterWraper()
updateCount();
updateCount();
</script>
above code we are using closure and making private variable so we can not eccess count variable out of function
example :
<script>
function CartCounter() {
let _count = 0;
function _updateCounter(val) {
_count += val
}
return {
increment() {
-_updateCounter(1)
},
decrement() {
_updateCounter(-1)
},
value() {
return _count
}
}
}
const cartCounter = CartCounter();
cartCounter.increment();
cartCounter.increment();
cartCounter.increment(); //output : 3
cartCounter.decrement(); //output : 2
console.log(cartCounter.value());
</script>
11. What is Server Side Rendring and Client Side Rendring ?
Server-side rendering (SSR) is the process of rendering web pages on the server and sending the fully-rendered HTML to the client. In this approach, the server generates the HTML, including any dynamic data, and sends it to the client as a complete page. The client then displays the page without any further processing.
One example of a popular SSR framework is Next.js. With Next.js, you can write React code and have it automatically rendered on the server, providing the benefits of SSR without having to manage the server yourself.
Server-side rendering (SSR) is a technique that renders a web page on the server rather than in the browser. When a website's JavaScript is rendered on the website's server, a fully rendered page is sent to the client and the client's JavaScript bundle engages and enables the Single Page Application framework to operate.
Server-side rendering is where your site’s content is rendered on the web server rather than the browser. This server prepares an HTML file with user-specific data and sends it to the user’s machine.
Client-side rendering (CSR) is the process of rendering web pages on the client using JavaScript. In this approach, the server sends the initial HTML file, but the client then uses JavaScript to dynamically update the page as needed. This allows for more interactive and responsive web pages, as the client can update specific parts of the page without needing to reload the entire page.
One example of a popular CSR framework is React. With React, you can write JavaScript code that updates the DOM as needed, providing a more interactive and dynamic web application.
Client-side rendering means that a website’s JavaScript is rendered in your browser, rather than on the website’s server. So now, instead of getting all the content from the HTML doc, only the required HTML with the JS files will be rendered. The rendering time for the first upload is a bit slow. However, the next page loads will be very fast as we don't have to wait for every page render. Moreover, there is no need to reload the entire UI after every call to the server. The client-side framework manages to update UI with changed data by re-rendering only that particular DOM element.
Also, a clear client-server separation scales better for larger engineering teams, as the client and server code can be developed and released independently. This is especially so at Grab when we have multiple client apps hitting the same API server.
In Client-Side Rendering (CSR) with React, the browser downloads a minimal HTML page and the JavaScript needed for the page. The JavaScript is then used to update the DOM and render the page. When the application is first loaded, the user may notice a slight delay before they can see the full page, this is because the page isn't fully rendered until all the JavaScript is downloaded, parsed, and executed.
After the page has been loaded for the first time, navigating to other pages on the same website is typically faster, as only necessary data needs to be fetched, and JavaScript can re-render parts of the page without requiring a full page refresh.
What Are The Differences Between Client-Side And Server-Side Rendering?
The main difference between these two rendering approaches is in the algorithms of their operation. CSR shows an empty page before loading, while SSR displays a fully-rendered HTML page on the first load.
This gives server-side rendering a speed advantage over client-side rendering, as the browser doesn’t need to process large JavaScript files. Content is often visible within a couple of milliseconds.
12. What is async and defer in web development ?
Async allows your script to run as soon as it's loaded, without blocking other elements on the page. Defer means your script will only execute after the page has finished loading
fetch data
Statement st;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:4306/mydata", "root", "sandip@123");
st = con.createStatement();
String query = "select * from student";
rs = st.executeQuery(query);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ViewRecord</title>");
out.println("</head>");
out.println("<body>");
out.println("<center>");
out.println("<table cellspacing='0' width ='500px' border='1'>");
out.println("<tr>");
out.println("<td> Name :</td>");
out.println("<td> Address :</td>");
out.println("<td> Update:</td>");
out.println("<td> Delete:</td>");
out.println("</tr>");
while (rs.next()) {
String name = rs.getString("name");
String address = rs.getString("address");
out.println("<tr>");
out.println("<td> " + name + " :</td>");
out.println("<td> " + address + " :</td>");
out.println("<td> <a href='Edit2?name=" + rs.getString("name") + "'>Edit</a> </td>");
out.println("<td> <a href='Delete?name=" + rs.getString("name") + "'>Delete</a> </td>");
out.println("</tr>");
}
out.println("</center>");
out.println("</body>");
out.println("</html>");
Last Updated on : 4th Nov 2024 17:35:55 PM
Latest Update
- JavaScript Interview Question MongoDb Command Curd Operation Node MonogoDb Express EJSC Practice Question Example Data Structure with CPPjava practice questionCurd operation with localstorage in javascriptComplete curd operation in react with json server and axios and router-domCPP Practice Question React Interview Question Java Pattern Program