Part 2: JavaScript beginners to advance

 

Functions Arrays Objects Closures & Destructuring  The Complete Guide (2026)




Welcome to Part 2 of our JavaScript Basics series.  In Part 1 we covered Variables Data Types Operators Type Conversion Scope and Hoisting. This part goes further than a typical tutorial  beyond Functions Arrays and Objects you will also learn Destructuring the Spread/Rest operators Closures and the notoriously confusing this keyword. These are the concepts that separate beginners from developers who can actually build real applications.

Table of Contents

1. Understanding Functions

2. Types of Functions

3. Default and Rest Parameters

4. Understanding Closures

5. The this Keyword Explained

6. Understanding Arrays

7. Essential Array Methods

8. Understanding Objects

9. Object Methods and Nesting

10. Destructuring (Arrays and Objects)

11. The Spread Operator

12. Frequently Asked Questions

13. Practice Exercises

1. Understanding Functions

What is a Function?

A function is a reusable block of code built to perform a specific task so you donot have to repeat the same logic throughout your program function greet() 

console.log("Hello, welcome to our website!");

}

greet();       // Output: Hello, welcome to our website!

Why Functions Matter

Reusability: Write logic once call it anywhere.

Organization: Break large programs into small testable pieces.

Maintainability: Fixing a bug in one function fixes it everywhere its used. Parameters Arguments and Return Values function add Numbers(a, b) 

{

return a + b;

}

let sum = add Numbers(5, 10);

console.log(sum);  

Output= 15;

a and b are parameters (placeholders)  5 and 10 are the arguments (actual values passed in). The return keyword sends a value back and immediately stops the functions execution.

2. Types of Functions

Function Declaration function multiply

(a, b) {

return a * b;

}

Function declarations are hoisted  callable even before they appear in the file.

Function Expression

const divide = function (a, b) 

{

return a / b;

}

Stored in a variable not hoisted so it must be defined before its called.

Arrow Functions

  • const subtract = (a, b) => a - b;                                                                                        console.log(subtract(10, 4));                                                                                                      //Output= 6

  • const square = num => num * num; // single parameters  no parentheses needed

const calculate Area = (length, width) 

 {

const area = length * width;

return area;

}

Arrow functions are shorter and importantly do not have their own this binding  more on that shortly.

3. Default and Rest Parameters

Default Parameters

function order(item = "Pizza")

 {

console.log(`You ordered: ${item}`);

}

order(); // You ordered: Pizza

order("Burger"); // You ordered: Burger


Rest Parameters

The rest operator ( ... ) collects any number of arguments into a single array.

function sum All(...numbers) {

return numbers.reduce((total num) =>

total + num, 0);

}

console.log(sum All(1, 2, 3, 4)); // 10

This is incredibly useful when you do not know in advance how many arguments a function will receive.

4. Understanding Closures

A closure is a function that remembers the variables from its outer scope even after that outer function has finished running. This is one of the most powerful  and most asked-about in interviews concepts in JavaScript.

function createCounter() {

let count = 0;

return function () {

count++;

return count;

}

}

const counter = createCounter();

console.log(counter()); // 1

console.log(counter()); // 2

console.log(counter()); // 3


Here the inner function keeps access to count even though createCounter() has already finished executing. Closures are the foundation behind many real world patterns including private variables and data encapsulation in JavaScript.

5. The this Keyword Explained

this refers to the object that is currently executing the function but its value depends entirely on how the function is called.

const person = {

name: "Aman",

greet: function () {

console.log(`Hi  am ${this.name}`);

}

}

person.greet(); // Hi I am Aman  this refers to person

Important: Arrow functions do not have their own this  they inherit it from their surrounding scope which is why they behave differently inside objects:

const person2 = {

name: "Riya",

greet: () => {

console.log(`Hi, I'm ${this.name}`); //

'this' is NOT person2 here

}

}

Rule of thumb: 

Use regular functions for object methods and arrow functions for callbacks where you want to preserve the outer this .

6. Understanding Arrays

An array is an ordered collection used to store multiple values in a single variable.

const fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log(fruits[0]); // Apple

console.log(fruits.length); // 4

Arrays are zero indexed  the first element is at position 0 .

7. Essential Array Methods

Adding and Removing

let cart = ["Shoes", "Watch"];

cart.push("Bag"); // Add to end

cart.pop( ); // Remove from end

cart.unshift("Cap"); // Add to beginning

cart.shift( ); // Remove from beginning

Looping with for Each

[85, 90, 78].forEach(score =>console.log(`Score: ${score}`));

Transforming with map

const prices = [100, 200, 300];

const discounted = prices.map(price =>price * 0.9);

console.log(discounted); // [90, 180, 270]

Filtering with filter

const ages = [12, 18, 25, 15, 30];

const adults = ages.filter(age => age >=18);

console.log(adults); // [18, 25, 30]

Reducing with reduce

const total = [10, 20, 30].reduce((sum, current) => sum + current, 0); console.log(total); // 60

Searching Arrays

const users = [{ id: 1 }, { id: 2 }, { id: 3 }];

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

console.log(found); // { id: 2 }

Other Useful Methods

fruits.includes("Mango"); // true

fruits.indexOf("Banana"); // 1

fruits.join(", "); // "Apple,

Banana, Mango, Orange"

fruits.sort(); // Sorts alphabetically

fruits.reverse(); // Reverses order in place

8. Understanding Objects

Objects store data as key value pairs ideal for modeling real world entities.

const student = {

name: "Priya",

age: 21,

is Enrolled: true

};

console.log(student.name); // Dot notation

console.log(student["age"]); // Bracket notation

Bracket notation is essential when the property name is stored in a variable.

const key = "isEnrolled";

console.log(student[key]); // true

Adding, Updating, and Deleting Properties

student.grade = "A"; // Add

student.age = 22; // Update

delete student.grade; // Delete

9. Object Methods and Nesting

Methods Inside Objects

const car = {

brand: "Toyota",

startEngine: function () {

console.log("Engine started!");

}

}

car.startEngine(); // Engine started!

Nested Objects

const company = {

name: "TechCorp",

address: {

city: "Bangalore",

zip: "560001"

}

};

console.log(company.address.city); //

Bangalore

Looping Through Objects

const person = { name: "Karan", age: 30,

city: "Delhi" };

for (let key in person) {

console.log(`${key}: ${person[key]}`);

}

Arrays of Objects (Very Common Real World Pattern)

const users = [

{ name: "Aman", age: 25 },

{ name: "Sita", age: 30 }

]

users.forEach(user =>

console.log(`${user.name} is ${user.age}`));

 10. Destructuring (Arrays and Objects)

Destructuring lets you unpack values from arrays or properties from objects into individual variables cleaner and more readable than manual access.

Array Destructuring

const coordinates = [10, 20];

const [x, y] = coordinates;

console.log(x, y); // 10 20

Object Destructuring

const user = { name: "Neha", age: 27, city: "Pune" };

const { name, city } = user;

console.log(name, city); // Neha Pune

You can also rename variables during destructuring:

const { name: userName } = user;

console.log(userName); // Neha

This pattern is used extensively in modern JavaScript frameworks like React.

11. The Spread Operator

The spread operator ( ... ) expands arrays or objects into individual elements  the opposite concept of the rest parameter.

Spreading Arrays

const arr1 = [1, 2, 3];

const arr2 = [4, 5, 6];

const combined = [...arr1, ...arr2];

console.log(combined); // [1, 2, 3, 4, 5, 6]

Spreading Objects

const baseInfo = { name: "Aman", age: 28 };

const fullInfo = { ...baseInfo, city: "Delhi" };

console.log(fullInfo); // { name: "Aman", age: 28, city: "Delhi" }


Spread is especially useful for copying arrays/objects without mutating the original a common requirement in frameworks like React where immutability matters.


12. Frequently Asked Questions

Q: What the difference between a function declaration and a function expression?                                 Declarations are hoisted and can be called before they are defined in the file expressions are not.

Q: Why should I use arrow functions instead of regular functions?                                                  Arrow functions offer shorter syntax and do not bind their own this  which is helpful in callbacks  but for object methods regular functions are usually correct.

Q: Whats the real world use of closures?                                                                                                       Closures are used for data privacy (private counters caching memoization) and are the core mechanic behind how many JavaScript libraries manage internal state.

Q: Should I use map/filter/reduce or a regular for loop?                                                                           Both work but map  filter  and reduce are more readable and are the modern standard for transforming data.

13. Practice Exercises

1. Write a function that accepts any number of arguments using rest parameters and returns their average.

2. Create a closure-based counter that can increase or decrease its value.

3. Destructure a name and email from a user object in a single line.

4. Use the spread operator to merge two arrays without duplicates (hint: combine with Set ).

5. Build an array of 5 product objects and use filter + map together to get the names of products priced under 500.




Conclusion

This part covered a huge range of essential concepts Functions Arrays Objects Closures the this keyword Destructuring and the Spread/Rest operators. These patterns appear in nearly every real world JavaScript codebase and modern framework, so mastering them here will make everything else you learn dramatically easier.

Coming up in Part 3 

Loops DOM Manipulation Events Switch Statements Error Handling and an introduction to Promises and async/await  where you will learn to build fully interactive production ready web pages. Keep coding daily  these patterns become intuitive with consistent practice.


Post a Comment

ON

Previous Post Next Post