KEMBAR78
Node | PDF | Web Development | Software
0% found this document useful (0 votes)
11 views13 pages

Node

The document provides solutions to common programming problems in Node.js and JavaScript, including string manipulation, array operations, and basic algorithms like palindrome and anagram checks. It also outlines essential JavaScript and Node.js topics for interviews, such as asynchronous programming, REST APIs, and error handling. Additionally, it covers React concepts like lifecycle methods, hooks, and performance optimization strategies.

Uploaded by

jay2001p
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)
11 views13 pages

Node

The document provides solutions to common programming problems in Node.js and JavaScript, including string manipulation, array operations, and basic algorithms like palindrome and anagram checks. It also outlines essential JavaScript and Node.js topics for interviews, such as asynchronous programming, REST APIs, and error handling. Additionally, it covers React concepts like lifecycle methods, hooks, and performance optimization strategies.

Uploaded by

jay2001p
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/ 13

Node.

js
1) Shiftgram Problem
Ans:- let shiftgram=(name1,name2)=>{

if(name1.length!==name2.length){
return false;
}
const globlevalriable=name1+name1;
return globlevalriable.includes(name2);
}
shiftgram("abcd","cdab")

✅ Part 2: Must-Know JavaScript Topics for Node.js Interviews

These are core topics that often come up in interviews (especially for freshers/juniors):

🔹 1. String Questions

• Reverse a string
• function reve(name){
• let revee='';
• for(let i=name.length-1;i>=0;i--)
• {
• revee+=name[i]
• }
• return revee;
• }
• let r=(name)=> name.split('').reverse().join('');
• console.log(r("Hello"))
• console.log(reve("Paresh"))

3.Swap number without using third variable :

Ans:- let a=10;


let b=20;
a=a+b;
b=a-b;
a=a-b;
// [a,b]=[a,b]
console.log("a:"+a)
console.log("b:"+b)
• Palindrome check

Ans:- function plaindrom(str)


{
const reve=str.split('').reverse().join('');
if(str===reve)
{
return "It is";
}
else{
return "it not"
}
}
plaindrom("Paresh")

• Anagram check
• function anagram(str,str1)
• {
• if(str.length!==str1.length) return false;
• let new1=str.split('').sort().join()
• let new2=str1.split('').sort().join()
• if(new1===new2)
• {
• return "it is"
• }
• else{
• return "it is not"
• }

• }
• Shiftagram (what you shared)

🔹 2. Array Questions

• Reverse an array

Ans:- function reversear(arr){


let revarr=[];
for(let i=arr.length-1;i>=0;i--)
{
revarr.push(arr[i])
}
console.log(revarr)
}
let arr=[1,2,3,4]
reversear(arr)

• Remove duplicates

Ans:- function dup(arr)


{
const ch=[...new Set (arr)];
console.log(ch)
}
arr=[1,2,2,3,4,4]
dup(arr);

• Find max/min
• let arr=[1,7,8,9]
• console.log(Math.max(...arr))
• console.log(Math.min(...arr))
• Rotate array

Ans:-

• Flatten nested array


• Find common elements between two arrays
• Sum of all elements

Ans:- let arr = [1, 2, 3, 4, 5];

let sum = arr.reduce((acc, val) => acc + val, 0);

console.log("Sum:", sum); // 15

or

let arr = [1, 2, 3, 4, 5];

let sum = 0;
for (let i = 0; i < arr.length; i++) {

sum += arr[i];

console.log("Sum of array elements:", sum); // Output: 15

Example:

js
CopyEdit
// Remove duplicates
const arr = [1, 2, 2, 3, 4, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]

Part 3: Node.js Topics to Prepare

Here's a priority cheat sheet for you:

Topic What to Focus


require() vs import CommonJS vs ES modules
Node.js Core Modules fs, http, path, os, events
Asynchronous JS callbacks, promises, async/await
Event Loop explain with diagram or phases
Express.js Basics routes, middleware, req/res
REST APIs CRUD operations
package.json dependencies, scripts, versioning
npm vs npx tools and use cases
Middleware app.use, custom middleware
Error handling try/catch, .catch(), error middleware
Topic What to Focus
File System fs.readFile, fs.writeFile, etc.
Environment Variables .env, process.env
JSON Handling JSON.stringify() / JSON.parse()
MongoDB Basics connection, schema, model if Mongoose used

✅ Part 4: 3 Mock Questions to Practice

Q1: How is Node.js different from traditional server-side languages?

Answer: Node.js is single-threaded, event-driven, non-blocking, uses JavaScript on the server,


great for scalable apps.

Q2: What is the difference between == and === in JavaScript?

Answer: == compares values only. === compares values and types (strict equality).

Q3: Write a function in Node.js that reads a file and logs its contents.

js
CopyEdit
const fs = require('fs');

fs.readFile('myfile.txt', 'utf8', (err, data) => {


if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});

React
1. React Lifecycle Methods

Phases:

• Mounting (Component added to DOM):


o constructor()
o getDerivedStateFromProps()
o render()
o componentDidMount()

Example:
componentDidMount() {
console.log('Component mounted!');
}

• Updating (Component re-rendered):


o getDerivedStateFromProps()
o shouldComponentUpdate()
o render()
o getSnapshotBeforeUpdate()
o componentDidUpdate()
• Unmounting (Component removed):
o componentWillUnmount()
• Error Handling:
o componentDidCatch()
o getDerivedStateFromError()

2. Class vs Functional Components


Feature Class Component Functional Component

Lifecycle Yes (methods) Yes (using Hooks)

State this.setState() useState()

Hooks Not Supported Supported

Code Size More Code Less Code

Preferred Old Projects Modern Projects

3. useState & useEffect

useState:
const [count, setCount] = useState(0);

useEffect:
useEffect(() => {
console.log("Runs once after first render");
}, []);
4. Keys in Lists

• Helps React track items.


• Avoid using index as key if list is dynamic.

list.map(item => <li key={item.id}>{item.name}</li>)

5. Synthetic Events

• React handles events using its own system.


• Example:

<button onClick={handleClick}>Click</button>

6. Refs

Functional Component:
const inputRef = useRef();
<input ref={inputRef} />

• Use for direct DOM access, focus, scroll, etc.

7. Controlled vs Uncontrolled Components


Feature Controlled Uncontrolled

Managed by React state DOM

Re-render on change Yes No

Example

8. Props vs State
Feature Props State

Source Parent Internal

Mutable No Yes
Used For Data Passing Component Behavior

9. Higher Order Components (HOC)

• Function that returns a component.


• Example:

const withAuth = (Component) => (props) => isLoggedIn ? <Component


{...props}/> : <Login/>;

10. Error Boundaries


class ErrorBoundary extends React.Component {
componentDidCatch(error, info) {
// handle error
}
render() {
return this.props.children;
}
}

11. Prop Drilling

• Passing props down multiple levels.

Solution:

• Context API
• Redux / Zustand

12. Lifting State Up

• Move shared state to common parent.

13. React Router DOM


import { BrowserRouter, Route } from 'react-router-dom';

• Helps navigate without refreshing page.


14. PureComponent vs React.memo

• PureComponent: Class version


• React.memo: Functional version

export default React.memo(MyComponent);

15. Styling in React

• CSS Files: import './style.css'


• Inline Style: <div style={{ color: 'red' }}>Text</div>
• CSS Modules: import styles from './style.module.css'
• Libraries: Tailwind, MUI, Bootstrap

16. Data Fetching


useEffect(() => {
fetchData();
}, []);

• Libraries: Axios, React Query, RTK Query

17. Conditional Rendering


isLoggedIn ? <Logout /> : <Login />
show && <Component />

18. CSR vs SSR


Feature CSR SSR

Render Location Browser Server

SEO Friendly No Yes

Initial Load Fast HTML Fast Content

Library React Next.js

19. Lazy Loading


const LazyComponent = React.lazy(() => import('./HeavyComponent'));
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>

20. Custom Hooks


function useCounter() {
const [count, setCount] = useState(0);
return [count, () => setCount(count + 1)];
}

21. useMemo vs useCallback

useMemo:
const result = useMemo(() => heavyFunction(x), [x]);

useCallback:
const handleClick = useCallback(() => setCount(count + 1), [count]);

22. Challenges in React

• Prop drilling
• Complex state
• Re-rendering
• Large forms

Solutions:

• Redux / Zustand
• React.memo
• useCallback / useMemo
• Formik / React Hook Form

23. Performance Optimization

• React.memo, useMemo, useCallback


• Code splitting
• Virtualized lists
• Avoid re-render with proper keys
• Lazy image loading

You might also like