NEW
Font size
WorksheetsJavaScript / Node.js Logic (Async, Scopes, Types)
Total questions: 50
Worksheet time: 25mins
What’s the output? console.log('A'); setTimeout(()=>console.log('B'), 0); Promise.resolve().then(()=>console.log('C')); console.log('D');
A. A B C D
B. A D B C
C. A C D B
D. A D C B
What prints? var x = 10; (function(){ console.log(x); var x = 20; console.log(x); })();
A. 10, 20
B. undefined, 20
C. ReferenceError, 20
D. 10, undefined
What is [1,2,3].map(parseInt)?
[1, 2, 3]
[1, NaN, NaN]
[NaN, NaN, NaN]
Throws
What prints?
const obj = {a:1}; const arr=[obj];
obj.a=2; console.log(arr[0].a);
1
2
undefined
Error
typeof null equals:
"null"
"object"
"undefined"
What’s true about requiring the same Node module twice?
Loads twice, new instance each
Uses a shared cached instance
Loads fresh each event loop tick
Only works once per process
Execution order? console.log('start'); process.nextTick(()=>console.log('tick')); Promise.resolve().then(()=>console.log('promise')); setTimeout(()=>console.log('timeout'),0); console.log('end');
A. start, end, promise, tick, timeout
B. start, end, tick, promise, timeout
C. start, tick, end, promise, timeout
D. start, promise, end, tick, timeout
What is typeof NaN?
"nan"
"number"
"undefined"
"object"
Which is idempotent per HTTP spec?
POST
PATCH
PUT
CONNECT
Which expression is true?
[] == []
{ } == { }
[] == ![]
null == 0
What prints? for (var i=1;i<=3;i++){ setTimeout(()=>console.log(i),0); }
A. 1 2 3
B. 3 3 3
C. 0 1 2
D. 1 1 1
12. Debounce vs Throttle:
Debounce triggers at a fixed rate; throttle after idle
Debounce waits for silence; throttle limits calls per interval
Both do the same
Debounce calls immediately and never again
Two calls in one handler: const [count,setCount]=useState(0); setCount(count+1); setCount(count+1);
+0
+1
+2
Undefined behavior
Using functional updates twice: setCount(c=>c+1); setCount(c=>c+1);
+0
+1
+2
+3
useEffect(fn, []) runs:
Before first render
After first paint only
Every render
Only on unmount
Effect cleanup runs:
After render completes
Before next effect run and on unmount
Only on errors
Never automatically
useMemo vs useCallback:
Both memoize values
useMemo → value, useCallback → function
useCallback → value, useMemo → function
Neither memoizes
Why are keys required in list items?
For styling
For SEO
To keep stable identity/state across reorders
To force re-renders
Controlled input means:
DOM manages value
Value is derived from React state
Input is read-only
Uses refs
In Next.js (pages router), server-side data fetch occurs in:
getStaticProps at runtime per request
getServerSideProps per request
useEffect
getInitialProps only in API routes
Best way to protect a JWT in a browser app?
LocalStorage
SessionStorage
HTTP-only, secure cookie
Inline in HTML
In Next.js, which is best for static marketing pages that rarely change?
getServerSideProps
Client fetch in useEffect
getStaticProps (SSG)
API route proxy on every hit
Correct order to validate JWT in Express:
Route → Controller → Auth middleware
Auth middleware → Route handler
Controller → DB → Auth
Error handler → Auth → Route
For invalid/expired credentials, return:
400
401
403
409
For authenticated user lacking permission, return:
400
401
403
422
CORS preflight uses:
GET
OPTIONS
HEAD
TRACE
Best place to rate-limit an Express API:
After route handler
Global middleware early in pipeline
In database layer
On client
Validation error for well-formed JSON but semantically invalid fields:
200
400
422
500
Ensure unique emails across users efficiently:
Check in code before insert
Create a unique index on email
Store in array
Use $group on every insert
Which stage aggregates per restaurant daily orders?
$project
$matchthen$group
$lookupthen$project
$unwindthen$skip
Which improves pipeline performance most often?
$group early
$match as early as possible
$sort early
$project at end
Embedding vs referencing: when to reference?
Small, bounded subdocs read with parent
Highly relational data reused across collections
Data never reused
Always embed
Atomicity in MongoDB:
Multi-document ops are atomic by default
Single-document writes are atomic
Reads are atomic, writes not
Nothing is atomic
Upsert with defaults during create:
updateOne(query, {$set:doc}, {upsert:true})
findOneAndUpdate(query, {$setOnInsert:doc}, {upsert:true})
insert(doc) then update
$merge
Enforce uniqueness of franchiseEmail per ownerId:
Unique index on franchiseEmail
Compound unique index on {ownerId, franchiseEmail}
TTL index
Text index
Populate in Mongoose is used to:
Denormalize documents
Join referenced docs by replacing ObjectIds with documents
Create indexes
Hash passwords
Principle of least privilege in IAM means:
Attach AdministratorAccess to be safe
Grant only permissions required to perform tasks
Use inline policies everywhere
Prefer root user for automation
S3 pre-signed URLs let you:
Create buckets
Upload/download objects temporarily without exposing AWS keys
Launch EC2 instances
Add bucket policies
EC2 security group inbound rule controls:
Outgoing traffic from instance
Incoming traffic to instance
S3 access only
IAM permissions
Safest way to store API secrets for a Node app on EC2:
Hard-code in repo
User-data script echo to file
AWS Systems Manager Parameter Store / Secrets Manager
Env vars in .env committed to Git
Zero-downtime upgrade for a web API:
SSH and restart process
Stop instance then start
Use Load Balancer with two targets and rolling deploy
Kill process and PM2 will revive
Best fit for static portfolio hosting + global CDN:
S3 static website + CloudFront
EC2 only
RDS + EC2
Lambda only
git revert
Both rewrite history
revert creates a new commit undoing changes; reset --hard moves HEAD and discards history
Both are safe on shared branches
reset --hard is safer for shared branches
Purpose of package-lock.json:
Speeds webpack
Pins exact dependency versions for repeatable installs
Lists scripts
Stores env vars
With ^1.2.3, NPM can install:
1.2.x only
1.x.x (≥1.2.3 <2.0.0)
any version
1.2.3 only
Postman is primarily used to:
Host APIs
Design UIs
Test and document APIs
Manage Git
Best status for successful POST creating a resource:
200
201
202
204
ETags help with:
Authentication
Cache validation / conditional requests
Encryption
CORS
Safest server-side password handling:
Store plaintext
Hash with bcrypt + salt
Base64 encode
MD5 without salt
You need to speed up frequent GET /restaurants (rarely changing). Best first move:
Add cache-control/ETag and a CDN/edge cache in front
Switch to WebSockets
Replace Express with bare Node
Move to another regi
