Browser Storage Mechanisms Explained (with Vue.js Examples)

Modern web applications often need to store data on the client side – whether it’s user preferences, form progress, or temporary UI state.
Browsers provide built-in storage mechanisms that help developers do exactly that, without hitting the backend every time.

In this post, we’ll cover:

  • What browser storage is
  • localStorage vs sessionStorage
  • Basic JavaScript examples
  • Vue.js usage patterns
  • When to use (and not use) each
  • Why developers rely on browser storage
  • Comparison with React and Angular

๐ŸŒ What Is Browser Storage?

Browser storage allows web applications to store keyโ€“value data directly in the userโ€™s browser.

Key characteristics:

  • Data is stored client-side
  • Data is stored as strings
  • Accessible via JavaScript
  • Faster than server round-trips

The most common browser storage mechanisms are:

  • localStorage
  • sessionStorage

(Both are part of the Web Storage API)


๐Ÿ“ฆ localStorage

What is localStorage?

localStorage stores data persistently in the browser.

  • Survives page reloads
  • Survives browser restarts
  • Shared across all tabs of the same origin
  • Cleared only manually or via code

Basic JavaScript Example

// Save data
localStorage.setItem('theme', 'dark')
// Read data
const theme = localStorage.getItem('theme')
// Remove data
localStorage.removeItem('theme')

Vue.js Example

export default {
data() {
return {
theme: localStorage.getItem('theme') || 'light'
}
},
watch: {
theme(newValue) {
localStorage.setItem('theme', newValue)
}
}
}

When to Use localStorage

  • User preferences (theme, language)
  • Remembered UI settings
  • Non-sensitive data that should persist
  • Cross-tab shared state

When NOT to Use localStorage

  • Authentication tokens (use httpOnly cookies)
  • Sensitive personal data
  • Temporary flows (signup, checkout steps)

โณ sessionStorage

What is sessionStorage?

sessionStorage stores data only for the lifetime of a browser tab.

  • Cleared when the tab is closed
  • Not shared across tabs
  • Survives page refresh
  • Scoped per tab/window

Basic JavaScript Example

// Save data
sessionStorage.setItem('step', '2')
// Read data
const step = sessionStorage.getItem('step')
// Remove data
sessionStorage.removeItem('step')

Vue.js Example (Signup Flow)

export default {
data() {
return {
postalCode: sessionStorage.getItem('postalCode') || ''
}
},
methods: {
savePostalCode() {
sessionStorage.setItem('postalCode', this.postalCode)
}
}
}

When to Use sessionStorage

  • Multi-step forms
  • Signup / onboarding flows
  • Temporary UI state
  • One-time user journeys

When NOT to Use sessionStorage

  • Long-term preferences
  • Data needed across tabs
  • Anything that must survive browser close

โš–๏ธ localStorage vs sessionStorage

FeaturelocalStoragesessionStorage
LifetimePersistentUntil tab closes
ScopeAll tabsSingle tab
Shared across tabsโœ… YesโŒ No
Survives reloadโœ… Yesโœ… Yes
Use casePreferencesTemporary flows
Storage size~5โ€“10MB~5MB

๐Ÿค” Why Web Developers Use Browser Storage

Developers use browser storage because it:

  • Improves performance
  • Reduces API calls
  • Remembers user intent
  • Simplifies UI state management
  • Works instantly (no async fetch)

Browser storage is often used as a support layer, not a replacement for backend storage.


โš ๏ธ Security Considerations

Important points to remember:

  • โŒ Data is NOT encrypted
  • โŒ Accessible via JavaScript
  • โŒ Vulnerable to XSS attacks

Never store:

  • Passwords
  • JWTs
  • Payment data
  • Sensitive personal information

โš›๏ธ Comparison with React and Angular

Browser storage usage is framework-agnostic.

Vue.js

sessionStorage.setItem('key', value)

React

useEffect(() => {
localStorage.setItem('key', value)
}, [value])

Angular

localStorage.setItem('key', value)

All frameworks rely on the same Web Storage API
The difference lies in state management patterns, not storage itself.


Best Practices

  • Store only strings (use JSON.stringify)
  • Always handle null values
  • Clean up storage after flows
  • Wrap storage logic in utilities or composables
  • Never trust browser-stored data blindly

Final Thoughts

  • localStorage โ†’ persistent, shared, preference-based
  • sessionStorage โ†’ temporary, per-tab, flow-based
  • Vue, React, and Angular all use the same browser API
  • Use browser storage wisely โ€” as a helper, not a database

Used correctly, browser storage can make your frontend faster, smarter, and more user-friendly.


Happy web development!

The Evolution of Asset ๐Ÿ“‘ Management in Web and Ruby on Rails

Understanding Middleware in Rails

When a client request comes into a Rails application, it doesn’t always go directly to the MVC (Model-View-Controller) layer. Instead, it might first pass through middleware, which handles tasks such as authentication, logging, and static asset management.

Rails uses middleware like ActionDispatch::Static to efficiently serve static assets before they even reach the main application.

ActionDispatch::Static Documentation

“This middleware serves static files from disk, if available. If no file is found, it hands off to the main app.”

Where Are Static Files Stored?

Rails stores static assets in the public/ directory, and ActionDispatch::Static ensures these are served efficiently without hitting the Rails stack.

Core Components of Ruby on Rails – A reminder

To understand asset management evolution, let’s quickly revisit Rails’ core components:

  • ActiveRecord: Object-relational mapping (ORM) system for database interactions.
  • Action Pack: Handles the controller and view layers.
  • Active Support: A collection of utility classes and standard library extensions.
  • Action Mailer: A framework for designing email services.

The Role of Browsers in Asset Management

Web browsers cache static assets to improve performance. The caching strategy varies based on asset types:

  • Images: Rarely change, so they are aggressively cached.
  • JavaScript and CSS files: Frequently updated, requiring cache-busting mechanisms.

The Era of Sprockets

Historically, Rails used Sprockets as its default asset pipeline. Sprockets provided:

  • Conversion of CoffeeScript to JavaScript and SCSS to CSS.
  • Minification and bundling of assets into fewer files.
  • Digest-based caching to ensure updated assets were fetched when changed.

The Rise of JavaScript & The Shift Towards Webpack

The release of ES6 (2015-2016) was a turning point for JavaScript, fueling the rise of Single Page Applications (SPAs). This marked a shift from traditional asset management:

  • Sprockets was effective but became complex and difficult to configure for modern JS frameworks.
  • Projects started including package.json at the root, indicating JavaScript dependency management.
  • Webpack emerged as the go-to tool for handling JavaScript, offering features like tree-shaking, hot module replacement, and modern JavaScript syntax support.

The Landscape in 2024: A More Simplified Approach

Recent advancements in web technology have drastically simplified asset management:

  1. ES6 Native Support in All Major Browsers
    • No need for transpilation of modern JavaScript.
  2. CSS Advancements
    • Features like variables and nesting eliminate the need for preprocessors like SASS.
  3. HTTP/2 and Multiplexing
    • Enables parallel loading of multiple assets over a single connection, reducing dependency on bundling strategies.

Enter Propshaft: The Modern Asset Pipeline

Propshaft is the new asset management solution introduced in Rails, replacing Sprockets for simpler and faster asset handling. Key benefits include:

  • Digest-based file stamping for effective cache busting.
  • Direct and predictable mapping of assets without complex processing.
  • Better integration with HTTP/2 for efficient asset delivery.

Rails 8 Precompile Uses Propshaft

What is Precompile? A Reminder

Precompilation hashes all file names and places them in the public/ folder, making them accessible to the public.

Propshaft improves upon this by creating a manifest file that maps the original filename as a key and the hashed filename as a value. This significantly enhances the developer experience in Rails.

Propshaft ultimately moves asset management in Rails to the next level, making it more efficient and streamlined.

The Future of Asset Management in Rails

With advancements like native ES6 support and CSS improvements, Rails continues evolving to embrace simpler, more efficient asset management strategies. Propshaft, combined with modern browser capabilities, makes asset handling seamless and more performance-oriented.

As the web progresses, we can expect further simplifications in asset pipelines, making Rails applications faster and easier to maintain.

Stay tuned for more innovations in the Rails ecosystem!

Happy Rails Coding! ๐Ÿš€

JavaScript / ES6+ Bootcamp – Lesson 5 – JavaScript Objects, Destructuring, Spread and this

This lesson connects several things you’ve already seen:

const [users, setUsers] = useState([]);

and:

const { name, age } = user;

and React props such as:

<User name="John" age={30} />

The goal is to understand how JavaScript objects work and how we extract, copy, and pass their data around.


1. JavaScript objects

An object is a collection of properties:

const user = {
id: 1,
name: "John",
age: 30,
active: true
};

Think of it as:

user
|
+-- id โ†’ 1
+-- name โ†’ "John"
+-- age โ†’ 30
+-- active โ†’ true

Access properties:

user.name; // "John"
user.age; // 30
user.active; // true

You can also use bracket notation:

user["name"];

These are equivalent when the property name is known.


2. Dot notation vs bracket notation

This works:

const user = {
name: "John"
};
console.log(user.name);

But bracket notation becomes particularly useful when the property name is stored in a variable:

const property = "name";
console.log(user[property]);

Result:

John

This would not work the same way:

user.property;

because that looks for a property literally called "property".


3. Objects can contain functions

For example:

const user = {
name: "John",
greet() {
console.log("Hello");
}
};

Call it:

user.greet();

The function is a property of the object.

When a function belongs to an object like this, we commonly call it a method.


4. Objects can contain anything

An object can contain:

const user = {
id: 1,
name: "John",
active: true,
roles: ["admin", "editor"],
address: {
city: "Kochi",
country: "India"
},
greet() {
console.log("Hello");
}
};

So you can have:

object
โ”œโ”€โ”€ primitive
โ”œโ”€โ”€ array
โ”œโ”€โ”€ object
โ””โ”€โ”€ function

This is why JavaScript objects are extremely flexible.


5. Object destructuring

Now the first very important ES6 feature.

Suppose:

const user = {
id: 1,
name: "John",
age: 30
};

You could write:

const name = user.name;
const age = user.age;

But destructuring allows:

const { name, age } = user;

This means:

const name = user.name;
const age = user.age;

Conceptually, yes.

So:

const { name, age } = user;

means:

Take the `name` property from user
โ†“
put it into variable `name`
Take the `age` property from user
โ†“
put it into variable `age`

6. Array destructuring vs object destructuring

This is one of the most important distinctions from the previous lessons.

Array

const numbers = [10, 20];
const [a, b] = numbers;

Destructuring is based on position:

numbers[0] โ†’ a
numbers[1] โ†’ b

Object

const user = {
name: "John",
age: 30
};
const { name, age } = user;

Destructuring is based on property name:

user.name โ†’ name
user.age โ†’ age

So:

Array destructuring โ†’ position
Object destructuring โ†’ property name

This distinction should become automatic.


7. Rename while destructuring

Suppose:

const user = {
name: "John",
age: 30
};

You don’t have to name your variable name.

You can do:

const { name: userName, age: userAge } = user;

Now:

userName; // "John"
userAge; // 30

Read this as:

name property โ†’ variable userName
age property โ†’ variable userAge

This syntax looks strange initially, but you’ll see it in real React and Node code.


8. Default values in destructuring

Suppose:

const user = {
name: "John"
};

You can write:

const { name, age = 30 } = user;

Now:

name; // "John"
age; // 30

The default is used only when the property is undefined.


9. Nested destructuring

Given:

const user = {
name: "John",
address: {
city: "Kochi",
country: "India"
}
};

You can do:

const {
name,
address: { city, country }
} = user;

Now:

name; // "John"
city; // "Kochi"
country; // "India"

This is useful, but don’t overuse deep destructuring. Very complex destructuring can become harder to read than ordinary property access.


10. Function parameters can be destructured

This is very common in React.

Instead of:

function User(props) {
return <h2>{props.name}</h2>;
}

you can write:

function User({ name }) {
return <h2>{name}</h2>;
}

The second form says:

The function receives an object, and I want its name property.

Suppose React effectively gives:

{
name: "John",
age: 30
}

Then:

function User({ name }) {

extracts:

name = "John";

This is one of the reasons you see React code full of { ... } around function parameters.


11. useState vs props: two different destructuring styles

Now compare these:

const [users, setUsers] = useState([]);

and:

function User({ name, age }) {
}

The first is array destructuring:

position 0 โ†’ users
position 1 โ†’ setUsers

The second is object destructuring:

name property โ†’ name
age property  โ†’ age

This is a very important React distinction.


12. Spread syntax with objects

Let’s revisit spread:

const user = {
name: "John",
age: 30
};
const copy = {
...user
};

Now:

copy

contains:

{
name: "John",
age: 30
}

The spread operator copies the object’s own enumerable properties into a new object.

At a beginner level, think:

“Take the properties from this object and put them into a new object.”


13. Updating an object using spread

Suppose:

const user = {
name: "John",
age: 30
};

We want:

same user
but age = 31

Write:

const updatedUser = {
...user,
age: 31
};

Result:

{
name: "John",
age: 31
}

Why does age: 31 win?

Object properties appearing later overwrite earlier properties with the same key.

So conceptually:

...user
โ†“
name: John
age: 30
age: 31
โ†“
overwrite age

14. This is common in React state updates

Suppose:

const [user, setUser] = useState({
name: "John",
age: 30
});

To change just the age:

setUser({
...user,
age: 31
});

We don’t do:

user.age = 31;

for normal React state updates.

Instead, we create a new object.

Conceptually:

old object
โ†“
{ name: "John", age: 30 }
...copy...
new object
โ†“
{ name: "John", age: 31 }

This gives React a new object reference.

We’ll later connect this directly to the question you raised previously about why React cares about new references.


15. Spread with arrays

Given:

const users = ["John", "Jane"];

Append without modifying the original:

const newUsers = [...users, "Mike"];

Result:

["John", "Jane", "Mike"]

Prepend:

const newUsers = ["Mike", ...users];

Result:

["Mike", "John", "Jane"]

Merge:

const first = [1, 2];
const second = [3, 4];
const combined = [...first, ...second];

Result:

[1, 2, 3, 4]

16. Spread is shallow

This is an important interview topic.

Consider:

const user = {
name: "John",
address: {
city: "Kochi"
}
};
const copy = {
...user
};

copy is a new object.

But:

copy.address === user.address

is:

true

Why?

Because spread creates a shallow copy.

The outer object is new, but nested objects are still shared.

Visualize:

user โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚
copy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ†“
address
{ city: "Kochi" }

Both objects point to the same nested address object.

This becomes extremely important when we talk about immutable state.


17. Deep copy is a different problem

Don’t assume:

const copy = { ...user };

means:

“Everything inside user has been recursively copied.”

It hasn’t.

For modern applications there are several strategies for deep cloning, but don’t jump to one automatically. Often you don’t actually need a deep clone.

For React state, it’s usually better to create new references only along the part of the structure you’re changing.

For example:

const updatedUser = {
...user,
address: {
...user.address,
city: "Bengaluru"
}
};

Now both the outer object and changed nested object are new references.


18. Object shorthand

ES6 gives us convenient syntax here:

const name = "John";
const age = 30;
const user = {
name,
age
};

Instead of:

const user = {
name: name,
age: age
};

JavaScript understands that:

name

means:

name: name

when used in an object literal.

You’ll see this everywhere.


19. Computed property names

You can dynamically create a property name:

const field = "name";
const user = {
[field]: "John"
};

Result:

{
name: "John"
}

Another example:

const field = "email";
const value = "john@example.com";
const user = {
[field]: value
};

Result:

{
email: "john@example.com"
}

This is useful when dynamically building objects.


20. this – the important part

Now we reach one of JavaScript’s most confusing concepts for Ruby developers:

this

Consider:

const user = {
name: "John",
greet() {
console.log(this.name);
}
};
user.greet();

Output:

John

Here:

this

refers to the object used to call the method:

user.greet();

So conceptually:

user.greet()
โ†“
this = user

Therefore:

this.name

is:

user.name

21. A critical difference from Ruby

In Ruby, you may mentally think:

“self is the current object.”

JavaScript’s this is more nuanced.

One of the most useful rules:

For a normal function call, this is determined by how the function is called, not simply where the function was defined.

That means:

user.greet();

and:

const greet = user.greet;
greet();

can have different this behavior.

This is one of the reasons JavaScript’s this can be tricky.


22. Arrow functions and this

Arrow functions behave differently.

They do not create their own this.

Consider:

const user = {
name: "John",
greet: () => {
console.log(this.name);
}
};
user.greet();

Do not assume:

this = user

just because the function appears inside the object.

That is not how arrow functions work.

This is one of the reasons you should not blindly replace every regular function with an arrow function.

We’ll spend an entire lesson on this, call, apply, bind, and arrow-function behavior.


23. Object references

Now an important JavaScript behavior.

const user1 = {
name: "John"
};
const user2 = user1;

We did not create a new object.

Both variables refer to the same object:

user1 โ”€โ”€โ”€โ”€โ”€โ”
โ†“
{ name: "John" }
โ†‘
user2 โ”€โ”€โ”€โ”€โ”€โ”˜

Therefore:

user2.name = "Jane";
console.log(user1.name);

prints:

Jane

This is because objects are reference values.


24. Compare primitive values

Now compare:

let a = 10;
let b = a;
b = 20;
console.log(a);

Result:

10

For the primitive number:

a โ†’ 10
b โ†’ 10
then:
b โ†’ 20

Changing b doesn’t alter a.

With objects:

user1 โ”€โ”€โ”
โ†“
object
โ†‘
user2 โ”€โ”€โ”˜

Both references point to the same object.

This distinction will become crucial when we discuss:

  • React state
  • equality
  • immutability
  • shallow comparison
  • useMemo
  • useCallback

25. === with objects

This gives us another important interview question.

const user1 = { name: "John" };
const user2 = { name: "John" };
console.log(user1 === user2);

Result:

false

Why?

Because these are two different objects.

Even though their contents are identical:

user1 โ†’ Object A
user2 โ†’ Object B

They have different references.

But:

const user1 = { name: "John" };
const user2 = user1;
user1 === user2;

returns:

true

because both reference the same object.


26. This explains something important in React

Later you’ll see code like:

setUsers(users);

versus:

setUsers([...users]);

The first gives React the same array reference.

The second creates a new array:

users โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ old array
[...users] โ”€โ”€โ†’ new array

This distinction becomes important because React can use reference identity when determining whether state/props values changed.

We’ll go deep into this when we revisit React state and rendering.


27. Complete React example

Let’s put today’s concepts together.

function User({ user }) {
const { name, age } = user;
return (
<div>
<h2>{name}</h2>
<p>{age}</p>
</div>
);
}

Here we have:

Object parameter

{ user }

Object destructuring

const { name, age } = user;

Function

function User(...) {
}

And React passes an object as the argument.


28. Another React example

Suppose:

const [user, setUser] = useState({
name: "John",
age: 30,
city: "Kochi"
});

Update only the city:

setUser({
...user,
city: "Bengaluru"
});

This combines:

object
+
spread
+
new object reference
+
state update

And now you can see why learning JavaScript first is useful.


๐Ÿง  The five concepts to remember

At the end of this lesson, these should be clear:

1. Object destructuring

const { name, age } = user;

Means:

const name = user.name;
const age = user.age;

2. Array destructuring

const [first, second] = numbers;

Means:

const first = numbers[0];
const second = numbers[1];

3. Spread

const copy = { ...user };

Creates a new shallow object.

4. References

const b = a;

with objects means both variables refer to the same object.

5. this

For a normal method call:

user.greet();

this inside the method refers to the receiver of that call – user.

Arrow functions have different this behavior.


๐ŸŽฏ Int. questions

Try answering these before reading further.

Q1

What’s the difference?

const [a, b] = [10, 20];

and:

const { a, b } = { a: 10, b: 20 };

Q2

What does this produce?

const user = {
name: "John",
age: 30
};
const { name: userName } = user;

Q3

What is the difference between:

const user2 = user1;

and:

const user2 = { ...user1 };

Q4

What happens here?

const user1 = { name: "John" };
const user2 = { name: "John" };
console.log(user1 === user2);

Q5

What does this do?

const user = {
name: "John",
age: 30
};
const updated = {
...user,
age: 31
};

Q6

Why can this be dangerous to assume?

const copy = { ...user };

when user contains nested objects?


๐Ÿงช Live coding practice

Problem 1 – Destructure

Given:

const user = {
id: 10,
name: "John",
age: 30
};

Extract:

id
name
age

using object destructuring.


Problem 2 – Rename

Extract name into a variable called:

userName

Problem 3 – Update immutably

Given:

const user = {
name: "John",
age: 30
};

Create a new object where:

name = "Jane"

without modifying user.


Problem 4 – Add a property

Given:

const user = {
name: "John"
};

Create:

{
name: "John",
active: true
}

using spread.


Problem 5 – Nested object

Given:

const user = {
name: "John",
address: {
city: "Kochi",
country: "India"
}
};

Create a new object where only:

city = "Bengaluru"

changes.

Don’t mutate the original nested address.


Problem 6 – Reference test

Predict:

const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count);

Then compare:

const a = { count: 1 };
const b = { ...a };
b.count = 2;
console.log(a.count);

Explain why the outputs differ.


๐Ÿ”— How this connects to your React learning

You now have almost all the JavaScript pieces needed to understand this:

const [users, setUsers] = useState([]);

and:

function User({ name, age }) {

and:

setUser({
...user,
age: 31
});

They are no longer “React syntax”. They are combinations of ordinary JavaScript:

useState(...) โ†’ function call
[users, setUsers] โ†’ array destructuring
{ name, age } โ†’ object destructuring
...user โ†’ spread
user => ... โ†’ function / callback

That’s exactly the mental model we want.

Next lesson

Lesson 6 – this, call, apply, bind, arrow functions, and closures.

This is the first lesson where JavaScript will behave noticeably differently from Ruby, and it is especially important for understanding React event handlers and Node.js code.

JavaScript / ES6+ Bootcamp Lesson 4 – Arrays, map, filter, find, reduce, Spread and Rest

This lesson is extremely important for React.

A large amount of React code looks like this:

users.map(...)
users.filter(...)
users.find(...)
items.reduce(...)

Once you understand what these methods are doing with callbacks, React code becomes much easier to read.

The goal today is not to memorize methods. It is to understand the pattern:

array
  โ†“
array method
  โ†“
callback
  โ†“
new result

1. JavaScript arrays

Start with:

const numbers = [10, 20, 30, 40];

An array has:

index: 0 1 2 3
value: 10 20 30 40

Access:

numbers[0]; // 10
numbers[2]; // 30

Length:

numbers.length; // 4

Unlike some languages, JavaScript arrays can contain different types:

const values = [10, "John", true, null];

But in normal application code, arrays usually contain consistent types:

const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
];

2. forEach – execute something for every item

Let’s start with the simplest callback method.

const numbers = [1, 2, 3];
numbers.forEach(number => {
console.log(number);
});

Output:

1
2
3

Conceptually:

1 โ†’ callback(1)
2 โ†’ callback(2)
3 โ†’ callback(3)

The important point:

forEach is mainly for performing an action for each item.

For example:

users.forEach(user => {
  console.log(user.name);
});

It does not create a transformed array for you.


3. map – transform every item

This is one of the most important methods for React.

const numbers = [1, 2, 3];

const doubled = numbers.map(number => number * 2);

Result:

[2, 4, 6]

Think:

input
[1, 2, 3]
callback
number => number * 2
output
[2, 4, 6]

The key idea:

map takes every element, runs your callback, and builds a new array from the returned values.


4. What does map actually do?

Conceptually, this:

const doubled = numbers.map(number => number * 2);

behaves roughly like:

const doubled = [];

doubled.push(1 * 2);
doubled.push(2 * 2);
doubled.push(3 * 2);

Result:

[2, 4, 6]

The real implementation is more sophisticated, but this is the right mental model.


5. map with objects

This is where React developers use it constantly.

const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Mike" }
];

Extract names:

const names = users.map(user => user.name);

Result:

["John", "Jane", "Mike"]

The callback:

user => user.name

is called once for each object.


6. map can transform objects

Suppose we want to create a different structure:

const users = [
{ id: 1, name: "John", age: 30 },
{ id: 2, name: "Jane", age: 25 }
];
const result = users.map(user => ({
id: user.id,
displayName: user.name
}));

Result:

[
{ id: 1, displayName: "John" },
{ id: 2, displayName: "Jane" }
]

Notice the parentheses:

user => ({
id: user.id,
displayName: user.name
})

We need them because the arrow function is implicitly returning an object.


7. filter – keep matching elements

Now:

const numbers = [1, 2, 3, 4, 5];
const result = numbers.filter(number => number > 2);

Result:

[3, 4, 5]

Unlike map, the callback for filter answers:

Should this item be included?

The callback must produce something truthy or falsy.

Conceptually:

1 โ†’ false โ†’ remove
2 โ†’ false โ†’ remove
3 โ†’ true  โ†’ keep
4 โ†’ true  โ†’ keep
5 โ†’ true  โ†’ keep

8. filter with users

const users = [
{ id: 1, name: "John", active: true },
{ id: 2, name: "Jane", active: false },
{ id: 3, name: "Mike", active: true }
];
const activeUsers = users.filter(user => user.active);

Result:

[
{ id: 1, name: "John", active: true },
{ id: 3, name: "Mike", active: true }
]

Very common React pattern:

activeUsers.map(user => (
<div key={user.id}>
{user.name}
</div>
))

This combines two concepts:

filter
โ†“
choose data
map
โ†“
transform/render data

9. find – find one item

find looks for the first matching item.

const numbers = [10, 20, 30, 40];
const result = numbers.find(number => number > 20);

Result:

30

Notice something important:

map โ†’ returns an array
filter โ†’ returns an array
find โ†’ returns one item

10. find with objects

const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
];
const user = users.find(user => user.id === 2);

Result:

{ id: 2, name: "Jane" }

If nothing matches:

const user = users.find(user => user.id === 99);
console.log(user);

Result:

undefined

This is important when handling lookup failures.


11. some

Another useful method:

const numbers = [1, 2, 3, 4];
numbers.some(number => number > 3);

Result:

true

It asks:

Does at least one item satisfy this condition?

For example:

const hasAdmin = users.some(user => user.role === "admin");

12. every

every asks:

Do all items satisfy the condition?

const numbers = [2, 4, 6];
numbers.every(number => number % 2 === 0);

Result:

true

13. reduce – the most important one to understand carefully

reduce often looks scary:

const result = numbers.reduce((total, number) => {
return total + number;
}, 0);

Don’t memorize this.

Understand what it is doing.

Given:

const numbers = [10, 20, 30];

we want:

10 + 20 + 30

reduce maintains an accumulated value.

Think:

initial accumulator
โ†“
0
0 + 10 = 10
10 + 20 = 30
30 + 30 = 60

Final result:

60

14. Understand the two arguments to reduce

This:

numbers.reduce((total, number) => {
return total + number;
}, 0);

contains:

total
โ†“
accumulator
number
โ†“
current element
0
โ†“
initial value

So:

(total, number) => total + number

means:

Take the accumulated result and the current item, then produce the next accumulated result.


15. reduce step by step

Given:

const numbers = [10, 20, 30];
const total = numbers.reduce(
(sum, number) => sum + number,
0
);

Execution:

First iteration

sum = 0
number = 10
0 + 10 = 10

Accumulator becomes:

10

Second iteration

sum = 10
number = 20
10 + 20 = 30

Third iteration

sum = 30
number = 30
30 + 30 = 60

Final:

60

16. reduce can create objects

This is where reduce becomes powerful.

Suppose:

const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Mike" }
];

We want:

{
1: "John",
2: "Jane",
3: "Mike"
}

We can do:

const result = users.reduce((acc, user) => {
acc[user.id] = user.name;
return acc;
}, {});

Result:

{
1: "John",
2: "Jane",
3: "Mike"
}

Don’t worry if reduce still feels less intuitive. That’s normal.

We’ll practice it.


17. map vs filter vs find vs reduce

Keep this table in your head:

MethodPurposeReturns
forEachPerform actionundefined
mapTransform every itemNew array
filterKeep matching itemsNew array
findFind first matchOne item / undefined
someAny match?Boolean
everyAll match?Boolean
reduceAccumulate/build resultAnything

This is much more useful than memorizing code examples.


18. Chain array methods

You can combine methods.

const users = [
{ name: "John", active: true },
{ name: "Jane", active: false },
{ name: "Mike", active: true }
];
const names = users
.filter(user => user.active)
.map(user => user.name);

Step 1:

filter(user => user.active)

produces:

[
{ name: "John", active: true },
{ name: "Mike", active: true }
]

Then:

map(user => user.name)

produces:

["John", "Mike"]

This style is extremely common in React.


19. Spread syntax

Now let’s move to another extremely important ES6 feature.

Suppose:

const numbers = [1, 2, 3];

We can copy its elements into a new array:

const newNumbers = [...numbers];

Result:

[1, 2, 3]

The ... here is called spread syntax.

Think:

...numbers
โ†“
take elements out
โ†“
1, 2, 3

20. Add an item with spread

const users = ["John", "Jane"];
const newUsers = [...users, "Mike"];

Result:

["John", "Jane", "Mike"]

This is extremely important in React.

Instead of mutating:

users.push("Mike");

you often create a new array:

setUsers([...users, "Mike"]);

Why?

Because React state updates rely heavily on creating new references rather than mutating existing state.

Check for detial: https://railsdrop.com/react-state-change-causes-react-to-render-reconcile-but-the-important-part-is-how-does-react-know-that-the-state-actually-changed/

21. Spread with objects

Given:

const user = {
name: "John",
age: 30
};

Create a new object:

const updatedUser = {
...user,
age: 31
};

Result:

{
name: "John",
age: 31
}

The later age: 31 overrides the previous value.

Think:

...user
โ†“
name: John
age: 30
age: 31
โ†“
overwrite age

22. Spread is heavily used in React

For example:

setUser({
...user,
name: "Jane"
});

Suppose:

user = {
id: 1,
name: "John",
age: 30
};

The result becomes:

{
id: 1,
name: "Jane",
age: 30
}

We didn’t modify the original object.

We created a new object.


23. Rest syntax

Here’s where JavaScript can get confusing.

The same ... syntax can also mean rest.

Compare:

Spread

const numbers = [1, 2, 3];
const copy = [...numbers];

We’re taking values out.

Rest

function sum(...numbers) {
console.log(numbers);
}

Now we’re collecting values into an array.

sum(10, 20, 30);

Inside the function:

numbers = [10, 20, 30]

So:

spread โ†’ expand
rest โ†’ collect

Same ..., different context.


24. Rest parameters

Example:

function sum(...numbers) {
return numbers.reduce((total, number) => {
return total + number;
}, 0);
}

Now:

sum(10, 20, 30);

Inside:

numbers
// [10, 20, 30]

Result:

60

This is a beautiful example because it combines:

rest
+
reduce
+
callback

25. Destructuring + rest

You can also use rest during destructuring.

const numbers = [10, 20, 30, 40];
const [first, ...rest] = numbers;

Now:

first;
// 10

and:

rest;
// [20, 30, 40]

This means:

first โ†’ first item
rest โ†’ everything remaining

26. Object destructuring + rest

Very common in React:

const user = {
id: 1,
name: "John",
age: 30
};
const { id, ...details } = user;

Now:

id
// 1

and:

details
// { name: "John", age: 30 }

You will see patterns like this in React props.


27. A React-style example

Consider:

function User({ id, ...userDetails }) {
return (
<div>
<h2>{userDetails.name}</h2>
<p>{userDetails.email}</p>
</div>
);
}

The props object might be:

{
id: 10,
name: "John",
email: "john@example.com"
}

After:

const { id, ...userDetails } = props;

you get:

id = 10;
userDetails = {
name: "John",
email: "john@example.com"
};

This syntax becomes much easier once destructuring and rest are clear.


28. A complete example

Let’s combine everything.

const users = [
{ id: 1, name: "John", active: true, age: 30 },
{ id: 2, name: "Jane", active: false, age: 25 },
{ id: 3, name: "Mike", active: true, age: 35 }
];

Find active users

const activeUsers = users.filter(user => user.active);

Get their names

const names = activeUsers.map(user => user.name);

Get total age

const totalAge = activeUsers.reduce(
(sum, user) => sum + user.age,
0
);

Result:

activeUsers
// John, Mike
names
// ["John", "Mike"]
totalAge
// 65

The whole pipeline:

users
โ”‚
โ”œโ”€โ”€ filter โ”€โ”€โ†’ active users
โ”‚
โ”œโ”€โ”€ map โ”€โ”€โ”€โ”€โ”€โ†’ names
โ”‚
โ””โ”€โ”€ reduce โ”€โ”€โ†’ total age

๐Ÿ’Ž Ruby comparison

These should look familiar:

Ruby:

users.select { |user| user[:active] }

JavaScript:

users.filter(user => user.active);

Ruby:

users.map { |user| user[:name] }

JavaScript:

users.map(user => user.name);

Ruby:

users.find { |user| user[:id] == 2 }

JavaScript:

users.find(user => user.id === 2);

Ruby:

users.reduce(0) { |sum, user| sum + user[:age] }

JavaScript:

users.reduce((sum, user) => sum + user.age, 0);

The collection-processing concepts are familiar. The biggest thing to master is JavaScript’s function syntax and callback model.


โš ๏ธ One important distinction: map does NOT modify the original array

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
console.log(numbers);
console.log(doubled);

Output:

[1, 2, 3]
[2, 4, 6]

The original remains unchanged.

Similarly:

const filtered = numbers.filter(n => n > 1);

creates another array.

This is one reason these methods fit well with React’s preference for immutable state updates.


๐ŸŽฏ Int. questions

Try answering these yourself.

Q1

What’s the difference between:

forEach()
map()
filter()
find()
reduce()

Q2

What does this return?

[1, 2, 3, 4].map(n => n * 2);

Q3

What does this return?

[1, 2, 3, 4].filter(n => n % 2 === 0);

Q4

What does this return?

[10, 20, 30].find(n => n > 15);

Q5

What is the final value?

[10, 20, 30].reduce(
(sum, n) => sum + n,
0
);

Q6

What is the difference between spread and rest?

const copy = [...numbers];

versus:

function test(...numbers) {}

๐Ÿงช Live coding practice

Try solving these without using a loop first.

Problem 1 – Double numbers

doubleNumbers([1, 2, 3, 4]);
// [2, 4, 6, 8]

Use map.


Problem 2 – Active users

getActiveUsers(users);

Return only users where:

user.active === true

Use filter.


Problem 3 – Find user

findUser(users, 2);

Return the user whose id is 2.

Use find.


Problem 4 – Total

sum([10, 20, 30, 40]);
// 100

Use reduce.


Problem 5 – Method chaining

Given:

const users = [
{ name: "John", active: true },
{ name: "Jane", active: false },
{ name: "Mike", active: true },
{ name: "Sarah", active: false }
];

Produce:

["John", "Mike"]

using:

filter + map

Problem 6 – Spread

Given:

const users = ["John", "Jane"];

Create:

["John", "Jane", "Mike"]

without using push.


Problem 7 – Rest

Write:

sum(10, 20, 30, 40);

and make it return:

100

using a rest parameter.


Mental model for today

Remember these seven statements:

forEach โ†’ do something for every item

map    โ†’ transform every item

filter โ†’ keep matching items

find   โ†’ get the first matching item

some   โ†’ does at least one match?

every  โ†’ do all match?

reduce โ†’ accumulate/build one result

And:

spread โ†’ expand values
rest โ†’ collect values

The most important connection from today’s lesson is:

Array method
โ†“
takes a callback
โ†“
callback runs for each relevant item
โ†“
method produces a result

For example:

users
.filter(user => user.active)
.map(user => user.name);

You should now be able to read that almost as English:

“Take users, keep the active ones, then transform each remaining user into their name.”

Next lesson: Objects, destructuring, spread, this, and JavaScript’s object model. This will connect directly to React props and explain why const { name } = user and const [users, setUsers] = useState([]) look similar but work differently.

Next lesson: https://railsdrop.com/2024/12/07/javascript-es6-bootcamp-lesson-5-javascript-objects-destructuring-spread-and-this/

JavaScript / ES6+ Bootcamp Lesson 3 – JavaScript Functions, Arrow Functions and Callbacks

This lesson is probably the most important JavaScript lesson before React.

You already know the basic idea of functions from Ruby. The big shift is:

In JavaScript, a function is also a value.

Once that clicks, callbacks, map, filter, React event handlers, useEffect, promises, and Node.js APIs become much easier to understand.

1. Normal function

The traditional syntax is:

function add(a, b) {
return a + b;
}

Call it:

const result = add(10, 20);
console.log(result); // 30

Execution:

add(10, 20)
โ†“
a = 10
b = 20
โ†“
a + b
โ†“
30

Very similar to Ruby:

def add(a, b)
a + b
end

2. A function is a value

This is the important part.

function add(a, b) {
return a + b;
}

You can do:

const operation = add;

Now:

operation(10, 20); // 30

Notice that we wrote:

const operation = add;

not:

const operation = add();

These are completely different.

add

Means:

Give me the function itself.

add()

Means:

Execute the function now and give me its return value.

Example:

function add() {
return 30;
}
const a = add;
const b = add();
console.log(a); // function
console.log(b); // 30

This distinction is extremely important for React.


3. Function expression

A function can also be assigned to a variable:

const add = function(a, b) {
return a + b;
};

Now:

add(10, 20);

This is called a function expression.

Compare:

function add(a, b) {
return a + b;
}

with:

const add = function(a, b) {
return a + b;
};

Both create functions, but they are written differently.


4. Arrow functions

Modern JavaScript heavily uses arrow functions.

const add = (a, b) => {
return a + b;
};

Shorter:

const add = (a, b) => a + b;

These are roughly equivalent for simple use cases:

function add(a, b) {
return a + b;
}
const add = (a, b) => a + b;

But later we’ll learn an important difference involving this.


5. Arrow function syntax

Let’s break down:

const add = (a, b) => a + b;
const add
   โ†“
variable

(a, b)
   โ†“
parameters

=>
   โ†“
arrow function

a + b
   โ†“
implicit return

Because there are no { }, JavaScript automatically returns the expression.

So:

const add = (a, b) => a + b;

means:

const add = (a, b) => {
return a + b;
};

6. Parentheses rules

With multiple parameters:

const add = (a, b) => a + b;

With one parameter, parentheses can be omitted:

const square = n => n * n;

Equivalent:

const square = (n) => n * n;

With no parameters:

const greet = () => "Hello";

So you’ll commonly see:

() => ...
x => ...
(x, y) => ...

7. Explicit vs implicit return

This is important.

Explicit return

const add = (a, b) => {
return a + b;
};

Implicit return

const add = (a, b) => a + b;

But this:

const add = (a, b) => {
a + b;
};

returns:

undefined

Why?

Because once you use { }, you have a function body. JavaScript requires an explicit:

return

if you want to return a value.


8. Returning an object from an arrow function

This is a common syntax trap.

You might write:

const createUser = () => {
name: "John"
};

That does not return the object you expect.

Use parentheses:

const createUser = () => ({
name: "John"
});

Now:

createUser();
// { name: "John" }

Explanation:

This is one of the most confusing parts of JavaScript arrow functions. The key is that {} has two different meanings depending on context.

1. Your first example

const createUser = () => {
name: "John"
};

You might read this as:

“Return an object containing name: "John".”

But JavaScript does not interpret it that way.

Because the arrow function has:

() => {
...
}

the {} is interpreted as a function block, not an object literal.

So JavaScript sees:

const createUser = () => {
name: "John";
};

as roughly:

const createUser = () => {
// function body
name: "John"; // labeled statement
// no return
};

Therefore:

console.log(createUser());

prints:

undefined

2. What is name: "John" then?

Inside a normal JavaScript block, this:

name: "John";

is interpreted as a label.

For example, JavaScript supports:

start:
for (let i = 0; i < 5; i++) {
console.log(i);
}

So in your code:

name: "John";

name is treated as a label, not an object property.

3. So why do parentheses fix it?

Now:

const createUser = () => ({
name: "John"
});

The important part is:

({
name: "John"
})

The parentheses tell JavaScript:

“Treat what’s inside these parentheses as an expression.”

Inside an expression, { name: "John" } is understood as an object literal.

So the arrow function becomes:

const createUser = () => ({
name: "John"
});

This is an implicit return.

It is basically equivalent to:

const createUser = () => {
return {
name: "John"
};
};

So:

console.log(createUser());

gives:

{ name: "John" }

4. Why can’t JavaScript just figure it out?

Therefore, JavaScript gives you two distinct forms.

Block body
const createUser = () => {
return {
name: "John"
};
};
Expression body
const createUser = () => ({
name: "John"
});

5. A useful way to remember it

Compare these:

() => {
name: "John";
}

versus:

() => ({
name: "John"
})

First:

=> { ... }
โ†‘
function block

Second:

=> ( ... )
โ†‘
expression
โ†“
object literal

One very common React example

This is why you often see:

const UserCard = () => (
<div>
<h1>John</h1>
</div>
);

The parentheses aren’t strictly required there, but they make it clear that JSX is the expression being implicitly returned.

And for objects:

const getUser = () => ({
name: "John",
age: 30
});

This is a very common JavaScript int. question because it tests whether you understand arrow functions, implicit returns, blocks and object literals.

You’ll see this frequently in React code.


9. Functions can receive functions

This is where callbacks begin.

Consider:

function execute(callback) {
callback();
}

We can call it:

execute(() => {
console.log("Hello");
});

Let’s slow this down.

The function:

() => {
console.log("Hello");
}

is passed as an argument to:

execute(...)

Inside execute:

function execute(callback) {
callback();
}

So:

execute(...)
|
| receives function
โ†“
callback
|
| callback()
โ†“
console.log("Hello")

That passed function is called a callback.


10. Why is it called a callback?

Because you’re essentially saying:

“Here is a function. Call it when you need to.”

Example:

function processUser(user, callback) {
console.log("Processing user:", user.name);
callback(user);
}

Usage:

processUser(
{ name: "John" },
(user) => {
console.log("Finished:", user.name);
}
);

The second argument is the callback.


11. Callbacks are NOT automatically asynchronous

This is very important.

Look at:

function execute(callback) {
console.log("A");
callback();
console.log("B");
}
execute(() => {
console.log("C");
});

Output:

A
C
B

Everything is synchronous.

A callback simply means:

a function passed to another function.

It does not mean asynchronous.


12. Asynchronous callback

Now:

setTimeout(() => {
  console.log("C");
}, 1000);

console.log("A");

Output:

A
C

after approximately one second.

Here the callback is asynchronous because setTimeout schedules it to run later.

This distinction is critical:

callback
โ‰ 
async

A callback may be:

synchronous
or
asynchronous

13. Higher-order functions

A function that:

  • accepts a function as an argument, or
  • returns a function

is commonly called a higher-order function.

Example:

function execute(callback) {
callback();
}

execute is a higher-order function because it accepts a function.

Another example:

function createGreeter() {
return function() {
console.log("Hello");
};
}

createGreeter is also a higher-order function because it returns a function.


14. This explains map

Now something you’ll see constantly in React:

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);

What is actually happening?

map receives a function:

n => n * 2

Conceptually:

numbers.map(callback)
โ†“
function(n) {
return n * 2;
}

For every element, map calls your callback.

Conceptually:

1 โ†’ callback(1) โ†’ 2
2 โ†’ callback(2) โ†’ 4
3 โ†’ callback(3) โ†’ 6

Result:

[2, 4, 6]

15. map with objects

This is extremely important for React.

const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
];
const names = users.map(user => user.name);

The callback:

user => user.name

runs for every user.

Result:

["John", "Jane"]

You can think:

users
โ†“
map(callback)
โ†“
John โ†’ "John"
Jane โ†’ "Jane"
โ†“
["John", "Jane"]

16. filter

filter also accepts a callback.

const numbers = [1, 2, 3, 4, 5];
const result = numbers.filter(n => n > 2);

The callback returns a boolean:

1 โ†’ false
2 โ†’ false
3 โ†’ true
4 โ†’ true
5 โ†’ true

Result:

[3, 4, 5]

The pattern is:

array.filter(callback)

17. find

const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
];
const user = users.find(user => user.id === 2);

The callback is:

user => user.id === 2

Result:

{ id: 2, name: "Jane" }

18. Why React uses callbacks everywhere

Consider:

<button onClick={() => console.log("Clicked")}>
Click me
</button>

You’re giving React a function:

() => console.log("Clicked")

You’re essentially saying:

“When the click happens, call this function.”

That is a callback.

Another example:

users.map(user => (
<div key={user.id}>
{user.name}
</div>
))

Again:

user => (...)

is a callback.

So when you see React code filled with arrow functions, don’t think:

“React magic.”

Think:

“JavaScript is passing functions around.”

That mental model is much more useful.


19. A very important React mistake

Compare:

<button onClick={handleClick}>

and:

<button onClick={handleClick()}>

These are not the same.

First

onClick={handleClick}

means:

Give React the function. React will call it when the event occurs.

Second

onClick={handleClick()}

means:

Call the function right now and give the result to React.

This is one of the most common beginner mistakes.

Again:

function reference
handleClick
โ†“
"Here is the function"
function call
handleClick()
โ†“
"Execute it now"

20. Function parameters are just variables

Look at:

function greet(name) {
console.log(name);
}

When you call:

greet("John");

JavaScript effectively does:

name = "John"

Similarly:

function execute(callback) {
callback();
}

When:

execute(myFunction);

conceptually:

callback = myFunction

Then:

callback();

calls it.

This is the key to understanding callbacks.


21. Callback with data

Callbacks can receive values too.

function getUser(callback) {
const user = {
id: 1,
name: "John"
};
callback(user);
}

Usage:

getUser(user => {
console.log(user.name);
});

Execution:

getUser()
โ†“
create user
โ†“
callback(user)
โ†“
user => console.log(user.name)

Output:

John

This pattern is foundational to asynchronous JavaScript.


๐Ÿ’Ž Ruby developer comparison

You already know something conceptually similar in Ruby:

[1, 2, 3].map { |n| n * 2 }

JavaScript:

[1, 2, 3].map(n => n * 2);

Ruby:

users.map { |user| user[:name] }

JavaScript:

users.map(user => user.name);

The syntax is different, but the underlying idea is similar:

collection
โ†“
iterate
โ†“
execute supplied function for each item
โ†“
produce result

But don’t equate Ruby blocks and JavaScript callbacks completely. JavaScript functions are first-class values in a particularly explicit way, and the language’s treatment of closures, this, arguments and async execution differs.


Int. questions

Try these before checking the answers.

Q1

What’s the difference?

handleClick

vs

handleClick()

Q2

What does this return?

const add = (a, b) => a + b;

Q3

Why does this return undefined?

const add = (a, b) => {
a + b;
};

Q4

What is a callback?

Q5

Are callbacks always asynchronous?

Q6

Why is map considered a higher-order-function use case?

Q7

What does this produce?

const numbers = [1, 2, 3];
const result = numbers.map(n => n * 10);

Mini exercise

Predict the output:

function calculate(a, b, callback) {
const result = a + b;
callback(result);
}
calculate(10, 20, result => {
console.log(result);
});

Then trace this one:

function execute(callback) {
console.log("A");
callback();
console.log("B");
}
execute(() => {
console.log("C");
});

Expected order:

?
?
?

And finally:

const users = [
{ id: 1, name: "John", active: true },
{ id: 2, name: "Jane", active: false },
{ id: 3, name: "Mike", active: true }
];
const activeUsers = users.filter(user => user.active);
const names = activeUsers.map(user => user.name);
console.log(names);

Try to mentally execute it as:

users
  โ†“
filter(callback)
  โ†“
active users
  โ†“
map(callback)
  โ†“
names

What you should take away

At this point, you should have these mental models:

function          โ†’ a value
function()        โ†’ call the function
callback           โ†’ function passed to another function
higher-order function  โ†’ accepts/returns functions
arrow function     โ†’ concise function syntax
map/filter/find    โ†’ receive callbacks

The next lesson should build directly on this:

Lesson 4 – Arrays, map, filter, find, reduce, spread and rest, with lots of React-style examples. That lesson will make expressions like users.map(...) feel natural rather than mysterious.

Lesson 4: https://railsdrop.com/2024/12/06/javascript-es6-bootcamp-lesson-4-arrays-map-filter-find-reduce-spread-and-rest/

JavaScript / ES6+ Bootcamp – Lesson 2

This lesson is important because JavaScript variable scope behaves differently enough from Ruby to cause bugs and int. confusion.

The four things to understand:

let
const
scope
hoisting

let, const, Scope and Hoisting

1. let vs const

Start with the simplest rule:

const name = "Abhilash";
let age = 40;

Use const when the variable should not be reassigned:

const name = "Abhilash";
// name = "John"; โŒ

Use let when reassignment is required:

let age = 40;
age = 41; // โœ…

Important: const does NOT make the value immutable

This is a very important JavaScript int. question.

const users = [];
users.push("John"); // โœ…

The array can be modified.

What cannot happen is:

users = ["Jane"]; // โŒ

Why?

Because const prevents reassignment of the variable, not mutation of the object.

Think:

const users
|
v
[ "John" ]

You cannot make users point somewhere else:

users โ”€โ”€โ”€โ”€โ”€Xโ”€โ”€โ”€โ”€> [ "Jane" ]

But you can modify the existing array:

users
|
v
["John", "Jane"]

The same applies to objects:

const user = {
name: "John"
};
user.name = "Jane"; // โœ…

But:

user = {}; // โŒ

Int. answer

const prevents reassignment, but it does not make objects or arrays immutable.


2. What is scope?

Scope simply means:

Where can this variable be accessed?

Example:

const name = "Abhilash";
function greet() {
console.log(name);
}
greet();

name is available inside greet() because functions can access variables from their outer scope.

But:

function greet() {
const message = "Hello";
}
console.log(message); // โŒ

message exists only inside the function.

Visualize:

Global Scope
โ”‚
โ”œโ”€โ”€ name
โ”‚
โ””โ”€โ”€ greet()
โ”‚
โ””โ”€โ”€ message

greet() can see name.

The outside cannot see message.


3. Block scope

This is where let and const become important.

A block is anything inside { }, such as:

if (...)
{
}

or:

for (...)
{
}

Example:

if (true) {
const message = "Hello";
console.log(message); // โœ…
}
console.log(message); // โŒ

message is block scoped.

Same with let:

if (true) {
let age = 40;
}
console.log(age); // โŒ

4. Why var is different

Historically JavaScript used:

var name = "John";

var does not have block scope.

Example:

if (true) {
var name = "John";
}
console.log(name); // John

That surprises many developers.

Compare:

if (true) {
let name = "John";
}
console.log(name); // โŒ

This is one major reason modern JavaScript prefers let and const.


5. Ruby comparison

You may initially think:

if true
name = "John"
end
puts name

Ruby’s local-variable behavior is different from JavaScript’s block scoping rules.

For JavaScript, remember:

const + let
โ†“
block scoped

and:

var
โ†“
function scoped

You don’t need to use var in modern code, but you must understand it when reading legacy JavaScript.


6. Nested scope

Scopes can be nested.

const country = "India";
function outer() {
const state = "Kerala";
function inner() {
const city = "Kochi";
console.log(country);
console.log(state);
console.log(city);
}
inner();
}

inner() can access:

country
state
city

because it can look outward through its scope chain.

But outer() cannot access city.

Visualize:

Global
โ”‚
โ”œโ”€โ”€ country
โ”‚
โ””โ”€โ”€ outer
โ”‚
โ”œโ”€โ”€ state
โ”‚
โ””โ”€โ”€ inner
โ”‚
โ””โ”€โ”€ city

JavaScript searches for variables from the current scope outward.

This is called the scope chain.


7. A very important example

Look carefully:

const name = "Abhilash";
function greet() {
const message = `Hello ${name}`;
console.log(message);
}
greet();

Inside greet():

name

is not declared locally.

JavaScript looks outward:

greet scope
โ†“
global scope
โ†“
find name

This behavior becomes extremely important when we learn closures.


8. What is hoisting?

Now we get to a classic int. topic.

JavaScript processes declarations before executing the code in the current scope.

This behavior is commonly called hoisting.

But don’t interpret it as JavaScript literally moving your code to the top. That’s a useful mental model, but the actual mechanics are more nuanced.

Start with a function declaration:

greet();
function greet() {
console.log("Hello");
}

This works.

Why?

Function declarations are available before their textual position.


9. var and hoisting

Consider:

console.log(name);
var name = "John";

You might expect an error.

Instead:

undefined

A useful mental model is:

var name;
console.log(name);
name = "John";

The declaration is available, but the assignment happens later.


10. let and const are different

Now:

console.log(name);
let name = "John";

This produces:

ReferenceError

And:

console.log(name);
const name = "John";

also produces:

ReferenceError

This is often explained using the Temporal Dead Zone (TDZ).


11. Temporal Dead Zone

For let and const, the variable exists in the scope before its declaration is executed, but you cannot access it before that point.

Example:

console.log(age); // โŒ
let age = 40;

The area between entering the scope and reaching the declaration is called the:

Temporal Dead Zone

You don’t need to memorize the implementation details yet. The int.-level mental model is:

var
โ†“
hoisted + initialized as undefined
let / const
โ†“
hoisted but inaccessible until declaration is reached

12. Function declarations vs function expressions

This becomes important when we get to callbacks.

This works:

greet();
function greet() {
console.log("Hello");
}

But this does not:

greet();
const greet = function() {
console.log("Hello");
};

And similarly:

greet();
const greet = () => {
console.log("Hello");
};

The second forms involve a const variable, so the TDZ applies.


13. A common int. trap

What does this print?

var x = 10;
if (true) {
var x = 20;
}
console.log(x);

Answer:

20

Because var is function scoped, not block scoped.

Now:

let x = 10;
if (true) {
let x = 20;
}
console.log(x);

Answer:

10

The inner x belongs to the block.

Visualize:

let x = 10
โ”‚
โ”œโ”€โ”€ if block
โ”‚ โ””โ”€โ”€ let x = 20
โ”‚
โ””โ”€โ”€ outside -> x is still 10

14. Shadowing

JavaScript allows an inner scope to define a variable with the same name.

const name = "Abhilash";
function test() {
const name = "John";
console.log(name);
}
test();
console.log(name);

Output:

John
Abhilash

The inner variable shadows the outer one.

This is perfectly valid, although unnecessary shadowing can make code harder to read.


15. Why this matters in React

Consider:

function UserList() {
const [users, setUsers] = useState([]);
if (users.length === 0) {
const message = "No users";
return <p>{message}</p>;
}
return (
<ul>
...
</ul>
);
}

message exists only inside that if block.

React code frequently contains nested blocks, callbacks and functions, so understanding scope prevents many bugs.


16. Scope + callbacks = important later

Consider:

function createCounter() {
let count = 0;
return function() {
count++;
console.log(count);
};
}

Don’t worry about understanding every detail yet.

The interesting question is:

How can the returned function still access count after createCounter() has finished?

That question leads directly to:

closures.

And closures are one of the most important JavaScript concepts for React and Node.js.


Qn) Is it necessary to put semi colon in Javascript?

No, putting a semicolon (or colon) at the end of a line is not mandatory in ES6 (ECMAScript 2015) or modern JavaScript.

JavaScript uses a feature called Automatic Semicolon Insertion (ASI). This means the JavaScript engine automatically inserts semicolons where it thinks they are needed to run your code correctly.

โš ๏ธ The Rare Exception

While you can safely omit semicolons 99% of the time, there are rare cases where leaving them out can break your code. This usually happens if a line starts with a bracket [ or parenthesis (.

Example of a bug without semicolons:

const user = "Alice"
['a', 'b'].forEach(letter => console.log(letter))

The JavaScript engine reads this as a single continuous line: const user = "Alice"['a', 'b'].forEach(...), which throws an error.

Best Practice

Because of ASI, choosing to use semicolons is largely a matter of personal or team preference:

  • With semicolons: Safer for beginners, prevents accidental ASI bugs, and follows traditional coding styles.
  • Without semicolons: Keeps code looking clean, modern, and reduces visual clutter.

Most development teams use a tool like Prettier or ESLint to automatically format the code and handle semicolons for them.

Int. questions

Try answering these without looking back.

Q1

What is the difference between:

const user = {};

and:

let user = {};

Q2

Why does this work?

const users = [];
users.push("John");

even though users is declared with const?

Q3

What is the output?

let x = 10;
if (true) {
let x = 20;
}
console.log(x);

Q4

What is the output?

var x = 10;
if (true) {
var x = 20;
}
console.log(x);

Q5

What happens here?

console.log(name);
let name = "John";

Q6

Why does this work?

greet();
function greet() {
console.log("Hello");
}

but this doesn’t?

greet();
const greet = () => {
console.log("Hello");
};

Mini exercise

Predict the output before running:

const name = "Abhilash";
function outer() {
const name = "John";
if (true) {
const name = "Jane";
console.log(name);
}
console.log(name);
}
outer();
console.log(name);

Expected mental trace:

global name
โ†“
outer name
โ†“
if-block name

Check the detailed Answer here: https://railsdrop.com/is-javascript-synchronous-or-asynchronous/

The most important thing from this lesson is to build the habit of asking:

Which scope does this variable belong to?

That question will help enormously when we reach closures, callbacks, useEffect, event handlers and async JavaScript.

Next lesson: Functions in depth – function declarations, expressions, arrow functions, parameters, return values, callbacks and higher-order functions.

Lesson 3: https://railsdrop.com/2024/12/04/javascript-es6-bootcamp-lesson-3-javascript-functions-arrow-functions-and-callbacks/

JavaScript / ES6+ Bootcamp – Lesson 1

The goal of this lesson is simple: understand what JavaScript is actually doing when you write basic code.

Coming from Ruby, you’ll notice that many concepts are similar, but JavaScript has some syntax and behavior that becomes important later in React and Node.js.

Variables, Values, Objects, Arrays, Functions and Return Values

1. Variables: let and const

In modern JavaScript, primarily use:

const name = "Abhilash";
let age = 40;

Think of them roughly like Ruby local variables:

name = "Abhilash"
age = 40

The difference is important:

const

The variable cannot be reassigned:

const name = "Abhilash";
name = "John"; // TypeError

let

The variable can be reassigned:

let age = 40;
age = 41;

What about var?

You’ll see:

var name = "Abhilash";

in older JavaScript code.

For modern JavaScript:

Use const by default.
Use let when reassignment is required.
Avoid var unless you're dealing with legacy code.

2. Everything starts with values

JavaScript variables hold values.

const name = "Abhilash";
const age = 40;
const active = true;

These values have types.

typeof name; // "string"
typeof age; // "number"
typeof active; // "boolean"

Some common types:

string
number
boolean
undefined
null
object
symbol
bigint

For now, focus on:

string
number
boolean
undefined
null
object

3. Arrays

An array stores multiple values.

const numbers = [10, 20, 30];

You can access them using an index:

numbers[0]; // 10
numbers[1]; // 20
numbers[2]; // 30

Just like Ruby:

numbers = [10, 20, 30]
numbers[0] # 10

JavaScript arrays are zero-indexed too.

Important

This:

const numbers = [10, 20, 30];

means numbers contains one array value.

It does not mean:

numbers = 10
20
30

Think:

numbers
|
v
[10, 20, 30]

4. Objects

JavaScript objects are heavily used in React and Node.

const user = {
id: 1,
name: "Abhilash",
active: true
};

You can access properties:

user.name; // "Abhilash"
user.id; // 1
user.active; // true

Ruby equivalent:

user = {
id: 1,
name: "Abhilash",
active: true
}
user[:name]

JavaScript also supports bracket notation:

user["name"];

This becomes useful when the property name is dynamic.


5. Arrays can contain objects

This is extremely common in React.

const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Mike" }
];

Visualize it:

users
|
v
[
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Mike" }
]

Then:

users[0].name;

returns:

"John"

This structure is everywhere in frontend applications.


6. Functions

A JavaScript function can be written like:

function add(a, b) {
return a + b;
}

Call it:

const result = add(10, 20);
console.log(result); // 30

Ruby equivalent:

def add(a, b)
a + b
end
result = add(10, 20)

So far, very familiar.


7. The important idea: functions are values

This is one of the biggest concepts you need for React and Node.

In JavaScript:

function add(a, b) {
return a + b;
}

The function itself is a value.

You can store it:

const operation = add;

Now:

operation(10, 20);

returns:

30

Visualize:

add
|
v
function
operation
|
+------> same function

This is why JavaScript can pass functions around so easily.


8. Functions can return anything

A function can return a number:

function getAge() {
return 40;
}

A string:

function getName() {
return "Abhilash";
}

An object:

function getUser() {
return {
id: 1,
name: "John"
};
}

An array:

function getUsers() {
return [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
];
}

And importantly, a function can return another function:

function createGreeter() {
return function() {
console.log("Hello");
};
}

We’ll use this concept later when learning closures.


9. This explains useState

Now let’s return to the example that confused you:

const [users, setUsers] = useState([]);

Ignore React for a moment.

Imagine an ordinary function:

function useState(initialValue) {
return [
initialValue,
function setValue(value) {
console.log(value);
}
];
}

Now call:

const result = useState([]);

What does result contain?

Conceptually:

[
[],
setValueFunction
]

So:

const users = result[0];
const setUsers = result[1];

Now combine the two operations with destructuring:

const [users, setUsers] = result;

Therefore:

const [users, setUsers] = useState([]);

means:

1. Pass [] into useState
2. useState returns [value, function]
3. destructure that returned array
4. users gets element 0
5. setUsers gets element 1

This is a critical mental model.


10. Array destructuring

Let’s isolate the JavaScript feature.

const numbers = [10, 20];
const [a, b] = numbers;

Equivalent to:

const a = numbers[0];
const b = numbers[1];

You can even ignore values:

const [first, , third] = [10, 20, 30];
console.log(first); // 10
console.log(third); // 30

11. Object destructuring

There is another extremely common form:

const user = {
name: "John",
age: 30
};
const { name, age } = user;

Equivalent to:

const name = user.name;
const age = user.age;

So remember:

Array -> []
Object -> {}

Therefore:

const [a, b] = array;
const { name, age } = object;

This distinction is extremely important in React.


12. Arrow functions

Modern JavaScript frequently uses:

const add = (a, b) => {
return a + b;
};

Short form:

const add = (a, b) => a + b;

Equivalent roughly to:

function add(a, b) {
return a + b;
}

React code uses arrow functions constantly:

users.map(user => user.name);

Don’t worry about map yet. Just notice:

user => user.name

is a function.


13. Why callbacks matter

Consider:

function execute(callback) {
callback();
}

Then:

execute(() => {
console.log("Hello");
});

What’s happening?

execute()
|
| receives a function
v
callback
|
v
callback()
|
v
console.log("Hello")

The function is being passed as a value.

This is the foundation of callbacks.

We’ll go much deeper into this in a later lesson.


Ruby developer mental model

For now, keep these mappings in your head:

JavaScriptRuby
const x = 10x = 10
[]Array
{}Hash-like object
functiondef / Proc/Lambda concepts
returnreturn
obj.nameobj[:name] for Hash
array[0]array[0]
function as valueProc/lambda/block-like concept
arrow functionlambda-ish syntax, but not identical

The last row is deliberately approximate. JavaScript functions, arrow functions, Ruby blocks, Procs and lambdas are not interchangeable concepts. We’ll cover the differences properly.


๐ŸŽฏ Lesson 1 int. questions

Try answering these without looking back.

Question 1

What does this return?

const numbers = [10, 20, 30];
numbers[1];

Question 2

What is the difference between:

const user = {
name: "John"
};

and:

const users = [
{ name: "John" }
];

Question 3

What does this do?

const [a, b] = [10, 20];

Question 4

What does this return?

function getUser() {
return {
id: 1,
name: "John"
};
}

Question 5

What is stored in operation?

function add(a, b) {
return a + b;
}
const operation = add;

Small exercise

Without running it, predict the output:

function getUser() {
return [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
];
}
const users = getUser();
const [firstUser, secondUser] = users;
console.log(firstUser.name);
console.log(secondUser.name);

Then try this variation:

const [firstUser] = getUser();
console.log(firstUser.name);

The key skill I’m looking for is not memorizing syntax. It’s being able to mentally trace:

function call
โ†“
return value
โ†“
array/object
โ†“
destructuring
โ†“
variables

Once that becomes natural, a lot of React code will stop looking mysterious.

Next lesson: let, const, scope, hoisting, and why JavaScript behaves differently from Ruby around variable scope.

Happy Learning! to be continued..