Understanding Vue.js Composition API

Vue 3 introduced the Composition API — a modern, function-based approach to building components. If you’ve been using the Options API (data, methods, computed, etc.), this might feel like a big shift. But the Composition API gives you more flexibility, reusability, and scalability.

In this post, we’ll explore what it is, how it works, why it matters, and we’ll finish with a real-world API fetching example.

🧩 What is the Composition API?

The Composition API is a collection of functions (like ref, reactive, watch, computed) that you use inside a setup() function (or <script setup>). Instead of organizing code into option blocks, you compose logic directly.

👉 In short:
It lets you group related logic together in one place, making your components more readable and reusable.


🔑 Core Features

Here are the most important building blocks:

  • ref() → create reactive primitive values (like numbers, strings, booleans).
  • reactive() → create reactive objects or arrays.
  • computed() → define derived values based on reactive state.
  • watch() → run side effects when values change.
  • Lifecycle hooks (onMounted, onUnmounted, etc.) → usable inside setup().
  • Composables → reusable functions built with Composition API logic.

⚖️ Options API vs Composition API

Options API (Vue 2 style)

<script>
export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}
</script>


Composition API (Vue 3 style)

<script setup>
import { ref } from 'vue'

const count = ref(0)
const increment = () => count.value++
</script>

<template>
  <p>{{ count }}</p>
  <button @click="increment">+</button>
</template>

✨ Notice the difference:

  • With Options API, logic is split across data and methods.
  • With Composition API, everything (state + methods) is grouped together.

🚀 Why Use Composition API?

  1. Better logic organization → Group related logic in one place.
  2. Reusability → Extract shared code into composables (useAuth, useFetch, etc.).
  3. TypeScript-friendly → Works smoothly with static typing.
  4. Scalable → Easier to manage large and complex components.

🌍 Real-World Example: Fetching API Data

Let’s say we want to fetch user data from an API.

Step 1: Create a composable useFetch.js

// composables/useFetch.js
import { ref, onMounted } from 'vue'

export function useFetch(url) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(true)

  onMounted(async () => {
    try {
      const res = await fetch(url)
      data.value = await res.json()
    } catch (err) {
      error.value = err
    } finally {
      loading.value = false
    }
  })

  return { data, error, loading }
}


Step 2: Use it inside a component

<script setup>
import { useFetch } from '@/composables/useFetch'

const { data, error, loading } = useFetch('https://jsonplaceholder.typicode.com/users')
</script>

<template>
  <div>
    <p v-if="loading">Loading...</p>
    <p v-if="error">Error: {{ error.message }}</p>
    <ul v-if="data">
      <li v-for="user in data" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

✨ What happened?

  • The composable useFetch handles logic for fetching.
  • The component only takes care of rendering.
  • Now, you can reuse useFetch anywhere in your app.

🎯 Final Thoughts

The Composition API makes Vue components cleaner, reusable, and scalable. It might look different at first, but once you start grouping related logic together, you’ll see how powerful it is compared to the Options API.

If you’re building modern Vue 3 apps, learning the Composition API is a must.


🔄 Vue.js: Composition API vs Mixins vs Composables

When working with Vue, developers often ask:

  • What’s the difference between the Composition API and Composables?
  • Do Mixins still matter in Vue 3?
  • When should I use one over the other?

Let’s break it down with clear explanations and examples.

🧩 Mixins (Vue 2 era)

🔑 What are Mixins?

Mixins are objects that contain reusable logic (data, methods, lifecycle hooks) which can be merged into components.

⚡ Example: Counter with a mixin

// mixins/counterMixin.js
export const counterMixin = {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}

<script>
import { counterMixin } from '@/mixins/counterMixin'

export default {
  mixins: [counterMixin]
}
</script>

<template>
  <p>{{ count }}</p>
  <button @click="increment">+</button>
</template>

✅ Pros

  • Easy to reuse logic.
  • Simple syntax.

❌ Cons

  • Name conflicts → two mixins or component methods can override each other.
  • Hard to track where logic comes from in large apps.
  • Doesn’t scale well.

👉 That’s why Vue 3 encourages Composition API + Composables instead.


⚙️ Composition API

🔑 What is it?

The Composition API is a set of functions (ref, reactive, watch, computed, lifecycle hooks) that let you write components in a function-based style.

⚡ Example: Counter with Composition API

<script setup>
import { ref } from 'vue'

const count = ref(0)
const increment = () => count.value++
</script>

<template>
  <p>{{ count }}</p>
  <button @click="increment">+</button>
</template>

👉 Unlike Mixins, all logic lives inside the component — no magic merging.

✅ Pros

  • Explicit and predictable.
  • Works great with TypeScript.
  • Organizes related logic together instead of scattering across options.

🔄 Composables

🔑 What are Composables?

Composables are just functions that use the Composition API to encapsulate and reuse logic.

They’re often named with a use prefix (useAuth, useCounter, useFetch).

⚡ Example: Reusable counter composable

// composables/useCounter.js
import { ref } from 'vue'

export function useCounter() {
  const count = ref(0)
  const increment = () => count.value++
  return { count, increment }
}

Usage in a component:

<script setup>
import { useCounter } from '@/composables/useCounter'

const { count, increment } = useCounter()
</script>

<template>
  <p>{{ count }}</p>
  <button @click="increment">+</button>
</template>

✅ Pros

  • Clear and explicit (unlike Mixins).
  • Reusable across multiple components.
  • Easy to test (plain functions).
  • Scales beautifully in large apps.

🆚 Side-by-Side Comparison

FeatureMixins 🧩Composition API ⚙️Composables 🔄
Introduced inVue 2Vue 3Vue 3
ReusabilityYes, but limitedMostly inside componentsYes, very flexible
Code OrganizationScattered across mixinsGrouped inside setup()Encapsulated in functions
ConflictsPossible (naming issues)NoneNone
TestabilityHarderGoodExcellent
TypeScript SupportPoorStrongStrong
Recommended in Vue 3?❌ Not preferred✅ Yes✅ Yes

🎯 Final Thoughts

  • Mixins were useful in Vue 2, but they can cause naming conflicts and make code hard to trace.
  • Composition API solves these issues by letting you organize logic in setup() with functions like ref, reactive, watch.
  • Composables build on the Composition API — they’re just functions that encapsulate and reuse logic across components.

👉 In Vue 3, the recommended pattern is:

  • Use Composition API inside components.
  • Extract reusable logic into Composables.
  • Avoid Mixins unless maintaining legacy Vue 2 code.

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 6 – this, call, apply, bind, Arrow Functions and Closures

This is one of the most important JavaScript lessons for us as a Ruby/Rails developer.

After this lesson, we should be able to read code like:

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

and understand exactly what this means.

We’ll also understand why:

const greet = user.greet;

can behave differently from:

user.greet();

Then we’ll connect that to:

useEffect(() => {
...
});

and eventually to closures, which are fundamental to React and Node.js.


1. What is this?

The easiest starting point is:

this is a special value available inside a function.

But unlike Ruby’s self, its value is usually determined by how a regular function is called.

Consider:

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

Output:

John

Why?

Because we called:

user.greet();

The object before the . is the receiver.

So:

user.greet()
↓
this = user

Therefore:

this.name

is effectively:

user.name

2. Think about the call site

This is the most useful mental model:

user.greet();

Look at the left side of the dot:

user . greet()
^^^^
receiver

For a normal method call, that receiver becomes this.

Example:

const person = {
name: "Alice",
sayName() {
console.log(this.name);
}
};
person.sayName();

Here:

this → person

Output:

Alice

3. But this is not permanently attached to the function

This is where JavaScript differs from the simple mental model we may have from Ruby.

Take:

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

Now:

user.greet();

gives:

John

But:

const greet = user.greet;
greet();

is a different call.

We did:

const greet = user.greet;

So greet now refers to the function.

But we’re no longer calling it as:

user.greet()

We’re calling:

greet()

There is no receiver.

So the this behavior is different.


4. The three things we should distinguish

When we see a function, distinguish:

user.greet
user.greet()
const fn = user.greet;
fn();

They mean different things.

user.greet

Get the function.

user.greet()

Call the function with user as the method receiver.

fn()

Call the function independently.

This distinction is extremely important in JavaScript.


5. this in a regular function

Consider:

function showThis() {
console.log(this);
}

What this is depends on how we invoke the function.

That’s the core idea:

regular function
↓
how was it called?
↓
determines `this`

There are several invocation patterns, and we’ll learn the important ones.


6. Method call

The easiest:

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

Here:

this = user

7. Explicitly set this

JavaScript gives us:

call()
apply()
bind()

These let us control what this refers to.

This is a very common int. topic.


8. call

Suppose:

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

We have an object:

const user = {
name: "John"
};

We can explicitly say:

greet.call(user);

Now:

this = user

Therefore:

John

So:

greet.call(user);

means approximately:

Call greet now, and make this equal to user.


9. call with arguments

Suppose:

function greet(message) {
console.log(`${message}, ${this.name}`);
}

Then:

const user = {
name: "John"
};

Call:

greet.call(user, "Hello");

Output:

Hello, John

The structure is:

function.call(thisArg, arg1, arg2, ...)

For example:

greet.call(user, "Hello");

means:

this = user
message = "Hello"

10. apply

apply is similar to call.

greet.apply(user, ["Hello"]);

Output:

Hello, John

The difference is mainly how arguments are supplied.

call

greet.call(user, "Hello", "How are you?");

apply

greet.apply(user, ["Hello", "How are you?"]);

So:

call → arguments individually
apply → arguments as an array

Historically apply was particularly useful when we already had an array of arguments. With modern JavaScript, spread syntax has reduced some of those use cases.


11. bind

bind is different.

const boundGreet = greet.bind(user);

This does not immediately call greet.

Instead it creates a new function.

Think:

greet.bind(user)
↓
new function
↓
this permanently set to user

Then:

boundGreet("Hello");

Output:

Hello, John

So:

call → call now
apply → call now
bind → create another function

That’s the key distinction.


12. call vs apply vs bind

Memorize this table:

MethodExecutes immediately?Arguments
callYesIndividual
applyYesArray
bindNoReturns new function

Example:

fn.call(obj, 1, 2);
fn.apply(obj, [1, 2]);
const newFn = fn.bind(obj);
newFn(1, 2);

13. A practical example

Suppose:

const user1 = {
name: "John"
};
const user2 = {
name: "Jane"
};
function greet(message) {
console.log(`${message}, ${this.name}`);
}

Now:

greet.call(user1, "Hello");

Output:

Hello, John

And:

greet.call(user2, "Hello");

Output:

Hello, Jane

Same function.

Different this.

This demonstrates why this in regular functions is associated with the invocation.


14. Arrow functions change the rules

Now comes a critical concept.

Arrow functions do not get their own this.

They use this from the surrounding lexical scope.

Example:

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

We might think:

user.greet()
↓
this = user

But that’s not how an arrow function works.

An arrow function does not create its own this.

It captures this from the surrounding scope.


15. Why this matters

Compare:

Regular function

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

Here:

this = user

Arrow function

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

Here this does not become user.

This is why object methods generally should not be written as arrow functions when they need dynamic this.


16. The classic callback problem

Now we get to a very common JavaScript issue.

Suppose:

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

We might expect:

John

But the inner regular function has its own this behavior.

The setTimeout callback isn’t being called as:

user.someMethod()

So it doesn’t automatically inherit the outer method’s this.


17. Arrow functions solve this nicely

Now:

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

Now the arrow function:

() => {
console.log(this.name);
}

doesn’t create a new this.

It captures the this from greet().

So:

user.greet()
↓
this = user
↓
arrow callback
↓
uses surrounding this
↓
this = user

Output:

John

This is one of the biggest reasons arrow functions are so useful.


18. Arrow functions and React

We’ll often see:

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

Here the arrow function is primarily being used as a callback.

React will call the arrow function later when the event occurs.

Similarly:

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

The callback passed to useEffect is an arrow function.

Again, remember:

() => {
...
}

is just a function.

React receives that function and decides when to invoke it.


19. Now: closures

This is perhaps even more important than this.

A closure happens when a function remembers variables from its surrounding lexical scope.

Consider:

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

Call:

const counter = createCounter();

Now:

counter(); // 1
counter(); // 2
counter(); // 3

The amazing part is:

createCounter() has already finished executing.

Yet the returned function can still access:

count

Why?

Because the function closed over the variable.


20. Visualize the closure

When we execute:

const counter = createCounter();

think:

createCounter()
|
| creates
v
count = 0
|
| returns function
v
counter ────────→ function
|
└── remembers count

Then:

counter();

the function can still access the remembered count.

After:

counter();

the value becomes:

count = 1

Next:

counter();

the function still has access to the same variable:

count = 2

21. Closure does NOT mean copying the value

This is an important detail.

Some beginners imagine:

count = 0

gets copied into the function.

That’s not the best mental model.

Instead, the function retains access to the lexical environment containing count.

Therefore:

counter();
counter();
counter();

all operate on the same captured variable.


22. Why closures are useful

Closures allow us to keep private state.

Example:

function createBankAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
balance += amount;
},
getBalance() {
return balance;
}
};
}

Now:

const account = createBankAccount(1000);
account.deposit(500);
console.log(account.getBalance());

Result:

1500

But:

account.balance

doesn’t exist as a public property.

The state is captured by the closure.

This is conceptually similar to encapsulation.


23. Closures and callbacks

Callbacks frequently create closures.

Example:

Output:

Hello John

The returned callback remembers:

name = "John"

even after greetUser() finished.

So:

outer function
↓
creates variable
↓
creates callback
↓
callback remembers variable

That’s a closure.


24. Closures in loops

Here’s a classic int. example:

for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}

Many people expect:

0
1
2

but with var, all callbacks refer to the same function-scoped i, which has reached 3 when the callbacks run.

So we get:

3
3
3

This is a classic closure + asynchronous execution int. question.

Now change var to let:

for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}

Now the callbacks see the per-iteration i values:

0
1
2

This connects directly to our Lesson 2 discussion of let and block/iteration scoping.


25. Closure + React

Closures are everywhere in React.

For example:

function User({ user }) {
const handleClick = () => {
console.log(user.name);
};
return (
<button onClick={handleClick}>
Click
</button>
);
}

The function:

handleClick

uses:

user

from its surrounding scope.

So it forms a closure over user.

This is normal JavaScript behavior, not React-specific magic.


26. Closure + useEffect

Consider:

function UserComponent({ userId }) {
useEffect(() => {
console.log(userId);
}, [userId]);
return null;
}

The callback passed to useEffect accesses:

userId

from the surrounding function scope.

That’s a closure.

This is why closures and React hooks are closely related.

Later, when we study the dependency array deeply, this will become very important.


27. Closure + Node.js

Closures are equally useful in Node.

For example:

function createLogger(prefix) {
return message => {
console.log(`[${prefix}] ${message}`);
};
}
const errorLogger = createLogger("ERROR");
const infoLogger = createLogger("INFO");
errorLogger("Database failed");
infoLogger("Server started");

Output:

[ERROR] Database failed
[INFO] Server started

Each returned function remembers its own prefix.

So closures are not merely “React stuff.”

They’re a fundamental JavaScript feature.


28. this vs closure

These are different concepts.

this

Answers:

What object/context does this regular function call use as this?

Closure

Answers:

What variables from surrounding lexical scopes can this function still access?

For example:

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

The arrow callback has access to:

this
message

but for different reasons:

this → inherited from surrounding context
message → closure over surrounding lexical variable

This distinction is worth remembering.


29. Ruby comparison

Ruby has:

self

JavaScript has:

this

But don’t assume:

Ruby self == JavaScript this

They have important differences.

Ruby self is much more naturally tied to the current execution context/object.

JavaScript this for a regular function is heavily dependent on how the function is called.

And JavaScript arrow functions don’t create their own this.

That distinction is especially important when moving from Rails backend code to React/Node.


30. A very useful mental model

For regular functions, ask:

How was this function called?

For arrow functions, ask:

What is the surrounding `this`?

For closures, ask:

Which variables from outer scopes does this function use?

These three questions will solve a huge number of JavaScript puzzles.


🎯 Interview questions

Try these without running them.

Q1

What is this here?

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

Q2

What’s the problem here?

const greet = user.greet;
greet();

Q3

What’s the difference between:

greet.call(user);

and:

const fn = greet.bind(user);

Q4

What is the difference between call and apply?

Q5

What is a closure?

Q6

Why does this work?

function createCounter() {
let count = 0;
return () => ++count;
}
const counter = createCounter();
counter(); // ?
counter(); // ?

Q7

Why does var produce the classic loop problem?

for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}

🧪 Live coding practice

Problem 1 – this

Predict the output:

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

Problem 2 – call

Write:

function introduce(role) {
console.log(`${this.name} is a ${role}`);
}

Then use call so that:

const user = {
name: "Abhilash"
};

produces:

Abhilash is a Senior Software Engineer

Problem 3 – bind

Given:

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

Create:

const boundGreet = ...

so that:

boundGreet("Hello");

produces:

Hello, John

Problem 4 – Closure

Implement:

const counter = createCounter();
counter(); // 1
counter(); // 2
counter(); // 3

The count variable should not be directly accessible from outside.


Problem 5 – Closure with argument

Create:

const double = multiplier(2);
double(5); // 10
double(10); // 20

The function multiplier(2) should return another function.

This is an excellent exercise for understanding closures.


Problem 6 – Callback + closure

Implement:

function createGreeter(name) {
return function() {
console.log(`Hello ${name}`);
};
}

Then:

const greetJohn = createGreeter("John");
const greetJane = createGreeter("Jane");
greetJohn();
greetJane();

Expected:

Hello John
Hello Jane

Be able to explain why each returned function remembers a different name.


Final mental model

We now have four layers:

FUNCTION
↓
Function can be passed around as a value
CALLBACK
↓
A function passed to another function
THIS
↓
For regular functions, determined by how the function is called
CLOSURE
↓
A function retains access to variables from its lexical scope

And the most important distinctions:

user.greet
↓
function reference
user.greet()
↓
function call
↓
this = user
greet.call(user)
↓
call now with explicit this
greet.apply(user, args)
↓
call now with explicit this + array arguments
greet.bind(user)
↓
return a new function with bound this

For arrow functions:

arrow function
↓
doesn't create its own `this`
↓
captures surrounding `this`

For closures:

outer scope
↓
function created inside it
↓
inner function remembers outer variables

The connection to React

We can now look at:

function User({ user }) {
const handleClick = () => {
console.log(user.name);
};
return (
<button onClick={handleClick}>
Click
</button>
);
}

and identify:

{ user } → object destructuring
handleClick → function
() => → arrow function
onClick={handleClick}→ function reference
user.name → closure over user

That’s the exact JavaScript foundation we want before going further into React.

Next lesson: JavaScript asynchronous programming – synchronous execution, call stack, event loop, Web/Node APIs, callback queue, microtask queue, Promises, and why async/await works. This will be especially important for us because it connects JavaScript directly to Node.js.

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.

Lesson 6: https://railsdrop.com/2024/12/09/javascript-es6-bootcamp-lesson-6-this-call-apply-bind-arrow-functions-and-closures/

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..

Remove and reset jQuery token input drop down values through ajax

If you have a requirement for reloading the token input drop down values, you can remove the token input by

$(".token-input-list-facebook").remove();

and add token input to the selector by

$("#demo-input-local").tokenInput([
                {id: 7, name: "Ruby"},
                {id: 41, name: "C"},
                {id: 43, name: "C++"},
                {id: 47, name: "Java"}
            ], {
      propertyToSearch: "name",
      theme: "facebook",
      preventDuplicates: true});

Twitter bootstrap typeahead difficult to add custom entries

 

If you are not familiar with twitter bootstrap typeahead please take a look at http://twitter.github.com/bootstrap/javascript.html#typeahead

While I am using twitter bootstrap, I found it is difficult to add the custom entries.

1 .When we add a entry and clicking on Enter the typeahead is taking the first list item as the value of the test box.

I solved this by Editing the typeahead javascript source code, refer my code from

https://github.com/abhilashak/Ajax-Typeahead