JavaScript Syllabus - Unit III (Detailed)
1. Arrays - References and Reference Parameters
- In JavaScript, arrays are objects stored by reference.
- When assigning an array to another variable, both variables point to the same array.
Example:
let arr1 = [1, 2, 3];
let arr2 = arr1;
arr2.push(4);
console.log(arr1); // [1,2,3,4]
- Reference Parameters:
Functions receive a reference to the original array, so modifications inside functions affect the original.
Example:
function modifyArray(a) {
a[0] = 99;
}
let nums = [1,2,3];
modifyArray(nums);
console.log(nums); // [99,2,3]
2. Passing Arrays to Functions
- Syntax: function process(arr) { /* ... */ }
- You can iterate, push/pop, sort, etc.
- Example - Summing elements:
function sumArray(a) {
return a.reduce((acc, val) => acc + val, 0);
}
console.log(sumArray([1,2,3,4])); // 10
- Example - Finding max value:
function maxInArray(a) {
return Math.max(...a);
}
console.log(maxInArray([5,3,9])); // 9
3. Multidimensional Arrays
- Arrays containing arrays as elements.
- Syntax: let matrix = [[1,2], [3,4], [5,6]];
- Access with multiple indices: matrix[1][0] // 3
- Iterating multi-dimensional arrays:
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}
- Example - Sum of diagonal elements:
function diagSum(mat) {
let sum = 0;
for (let i = 0; i < mat.length; i++) {
sum += mat[i][i];
}
return sum;
}
4. Objects of JavaScript
- Objects are collections of key-value pairs.
- Syntax: let obj = { key1: value1, key2: value2 };
- Access: obj.key1 or obj['key1']
5. Window Object
- The global object in browser JavaScript context.
- Properties & Methods:
- window.alert(), window.prompt(), window.confirm()
- window.location: URL information and navigation.
- window.document: access to DOM.
- window.innerWidth, window.innerHeight: viewport size.
- window.setTimeout(), window.setInterval().
- Example:
console.log(window.location.href);
6. Document Object
- Represents the DOM of the loaded page.
- Accessing elements:
document.getElementById(id)
document.getElementsByClassName(class)
document.querySelector(selector)
- Manipulating DOM:
element.innerHTML, element.textContent, element.style
- Creating elements:
let p = document.createElement('p');
p.textContent = 'Hello';
document.body.appendChild(p);
- Events & Handlers:
element.addEventListener('click', handler);
window.onload = function() { /* ... */ };
Practice Exercises:
1. Write a function that takes a 2D array and returns its transpose.
2. Implement a function that rotates a matrix by 90 degrees.
3. Given an array, write a function to remove duplicate elements (modify by reference).
4. Use window.prompt() to get a list of numbers, then display sorted list using DOM.
5. Create a simple to-do list app using document.createElement() and event listeners.
----------------------------------------
Study all examples, practice by hand, and understand reference behavior.
Good luck scoring full marks!