Harshil Chovatiya - Day 7 and 8: Arrays, Functions - Advanced Concepts in JavaScript
Day 7: Arrays and Lists in JavaScript
Overview:
Arrays are used to store collections of data in JavaScript. They are versatile and can hold various data types, including numbers, strings, and objects.
In-Depth:
Creating Arrays:
You can create arrays using square brackets []
and populate them with values.
var numbers = [1, 2, 3, 4, 5];
var fruits = ["apple", "banana", "cherry"];
Accessing Array Elements:
Array elements are accessed by their index (starting at 0).
var firstNumber = numbers[0]; // Access the first element
var secondFruit = fruits[1]; // Access the second element
Modifying Arrays:
You can add, remove, and modify elements in an array.
fruits.push("orange"); // Add an element to the end
fruits.pop(); // Remove the last element
fruits[1] = "grape"; // Modify an element
Array Length:
You can find the length of an array using the length
property.
var numCount = numbers.length; // Length of the 'numbers' array
Iterating Over Arrays:
Loops are often used to iterate over array elements.
for (var i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
Multidimensional Arrays:
Arrays can also hold other arrays, creating multidimensional structures.
var matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
Day 8: Functions - Advanced Concepts in JavaScript
Overview:
Building upon the basics of functions, this day covers more advanced concepts and techniques.
In-Depth:
Function Scope:
Variables declared inside a function are typically scoped to that function and are not accessible outside of it.
function greet() {
var message = "Hello";
console.log(message);
}
greet();
console.log(message); // Error: 'message' is not defined
Function Closures:
Functions can "close over" and retain access to their containing scope even after the outer function has finished executing.
function makeCounter() {
var count = 0;
return function() {
return ++count;
};
}
var counter = makeCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
Function Arguments:
Functions can accept a variable number of arguments using the `arguments` object or the rest parameter syntax.
function calculateSum() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
console.log(calculateSum(1, 2, 3)); // Output: 6
Function Recursion:
A function can call itself, which is known as recursion.
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(5)); // Output: 120
Function Hoisting:
Function declarations are hoisted to the top of their containing scope, allowing you to call a function before it's defined.
sayHello(); // Works
function sayHello() {
console.log("Hello");
}
Comments
Post a Comment