L

Javascript Lecture Notes

Array Methods

  • JavaScript provides several built-in array methods for performing common operations.
  • These methods include forEach, map, filter, some, every, and reduce.

forEach

  • The forEach method iterates over each element in an array and executes a provided function once for each element.
  • Syntax:
    arr.forEach(function(element) {
    console.log(element);
    });
  • Example:
    javascript let arr = [1, 2, 3, 4, 5]; arr.forEach(function(el) { console.log(el); });
  • The forEach method does not create a new array; it simply executes the provided function for each element in the existing array.

Map

  • The map method creates a new array with the results of calling a provided function on every element in the calling array.
  • The map method transforms each element of the original array.
  • The new array will have the same size as the original array.
  • Syntax:
    let newArr = arr.map(function(element) {
    return element * 2;
    });
  • Example:
    javascript let num = [1, 2, 3, 4]; let double = num.map(function(el) { return el * 2; }); console.log(double); // Output: [2, 4, 6, 8]
  • If the return statement is missing in the map callback, it will return an array of undefined values.
    • Example:
      javascript let num = [1, 2, 3, 4]; let double = num.map((el) => {}); console.log(double) // Output: [undefined, undefined, undefined, undefined]

Filter

  • The filter method creates a new array with all elements that pass the test implemented by the provided function.
  • The callback function should return true to include the element in the new array or false to exclude it.
  • Syntax:
    let newArr = arr.filter(function(element) {
    return element > 2;
    });
  • Example:
    javascript let nums = [2, 4, 1, 5, 6, 2, 7, 8, 9]; let even = nums.filter((num) => (num % 2 == 0)); console.log(even); // Output: [2, 4, 6, 2, 8]

Every

  • The every method tests whether all elements in the array pass the test implemented by the provided function. It returns true if all elements pass the test; otherwise, it returns false.
  • Syntax:
    arr.every(function(element) {
    return element > 2;
    });
  • Examples:
    • [2, 4].every(el => el % 2 == 0) returns true because all elements are even.
    • [1, 2, 3, 4].every(el => el % 2 == 0) returns false because not all elements are even.
    • [2, 4, 6].every((el) => el % 2 == 0) returns true
    • [2, 4, 6, 8].every ((el) => el % 2 == 0) returns true
    • [2, 4, 6, 8, 1].every ((el) => el % 2 == 0) returns false

Some

  • The some method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if at least one element passes the test; otherwise, it returns false.
  • Syntax:
    arr.some(function(element) {
    return element > 2;
    });
  • Examples:
    • [1, 2, 3, 4].some(el => el % 2 == 0) returns true because some elements are even.
    • [1, 3].some(el => el % 2 == 0) returns false because no elements are even.

Reduce

  • The reduce method executes a reducer function (provided) on each element of the array, resulting in a single output value.
  • The reducer function takes two arguments: an accumulator and the current element.
  • Syntax:
    arr.reduce(function(accumulator, element) {
    return accumulator + element;
    });
  • Example:
    javascript let nums = [1, 2, 3, 4]; let finalVal = nums.reduce((res, el) => res + el); console.log(finalVal); // Output: 10
  • The reduce method can be used to find the maximum value in an array.
    javascript let nums = [2, 3, 4, 5, 3, 4, 7, 8, 1, 2]; let result = nums.reduce((max, el) => { if(el > max) { return el; } else { return max; } }); console.log(result); // Output: 8

Practice Questions and Solutions

  • Check if all numbers in an array are multiples of 10 or not using every.

    let nums = [10, 20, 30, 40];
    let ans = nums.every((el) => el % 10 == 0);
    console.log(ans); // Output: true
    
    let nums = [10, 20, 30, 40, 5];
    let ans = nums.every ((el) => el % 10 == 0);
    console.log(ans); // Output: false
    
  • Create a function to find the minimum number in an array using reduce.

    function getMin(nums) {
        let min = nums.reduce((min, el) => {
            if (min < el) {
                return min;
            } else {
                return el;
            }
        });
        return min;
    }
    
    let nums = [10, 20, 30, 40, 5];
    console.log(getMin(nums)); // Output: 5
    

Default Parameters

  • A default parameter is a value given to a function parameter if the user does not supply a value.

  • Syntax:
    javascript function func(a, b = 2) { // do something }

  • Example:

    function sum(a, b = 3) {
        return a + b;
    }
    
    console.log(sum(2));   // Output: 5
    console.log(sum(1, 4)); // Output: 5
    
  • If a parameter with a default value is followed by a parameter without a default value, the function may not work as expected because JavaScript assigns arguments from left to right.
    javascript function sum(a = 2, b) { return a + b; } console.log(sum(1, 3)); // Output: 4 console.log(sum(1)); // Output: NaN (because b is undefined)

Spread

  • The spread syntax expands an iterable (e.g., an array or a string) into multiple values.
  • It is denoted by three dots (...).
  • Example: Spreading an array into Math.min()
    javascript let arr = [1, 2, 3, 4, 5]; console.log(Math.min(...arr)); // Output: 1
  • Spreading a string:
    javascript console.log(...".apnacollege"); // Output: a p n a c o l l e g e
  • Spread can be used to create a shallow copy of an array:
    javascript let arr = [1, 2, 3, 4, 5]; let newArr = [...arr]; newArr.push(6); console.log(arr); // Output: [1, 2, 3, 4, 5] console.log(newArr); // Output: [1, 2, 3, 4, 5, 6]
  • Spread can be used to combine multiple arrays:
    javascript let odd = [1, 3, 5, 7, 9]; let even = [2, 4, 6, 8, 10]; let nums = [...odd, ...even]; console.log(nums); // Output: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
  • Spread with Object Literals
    javascript let data = { email: "ironman@gmail.com", password: "abcd", }; let dataCopy = { ...data, id: 123, country: "India" }; console.log(dataCopy); // Output: {email: 'ironman@gmail.com', password: 'abcd', id: 123, country: 'India'}
  • Spread syntax can be used to convert an array into an object, where array indices become keys.
    javascript let arr = [1, 2, 3, 4, 5]; let obj1 = { ...arr }; console.log(obj1); // Output: {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
  • Spread syntax can be used to convert a string to an object, where string indices become keys and characters become values.
    javascript let obj2 = { ..."hello" }; console.log(obj2); // Output: {0: 'h', 1: 'e', 2: 'l', 3: 'l', 4: 'o'}

Rest

  • The rest parameter allows a function to accept an indefinite number of arguments as an array.

  • Syntax:
    javascript function sum(...args) { // args is an array }

  • Example:

    function sum(...args) {
        let total = 0;
        for (let i = 0; i < args.length; i++) {
            total += args[i];
        }
        return total;
    }
    
    console.log(sum(1, 2, 3, 4)); // Output: 10
    
  • Using reduce with rest parameters
    javascript function sum(...args) { return args.reduce((sum, el) => sum + el); } console.log(sum(1, 2, 3, 4)); // Output: 10

  • Rest parameter to find mix
    javascript function min(...args) { return args.reduce((min, el) => { if (min < el) { return min; } else { return el; } }); } console.log(min(1, 2, 3, 4)); // Output: 1 console.log(min(12, 445, 123, -20)); // Output: -20

  • Rest parameters can be combined with regular parameters.
    javascript function min(msg, ...args) { console.log(msg); return args.reduce((min, el) => { if (min < el) { return min; } else { return el; } }); } console.log(min("hello", 12, 445, 123, -20)); // Output: // hello // -20

Destructuring

  • Destructuring is a JavaScript expression that allows you to extract values from arrays or objects and assign them to variables in a concise way.

Array Destructuring

  • Example:
    javascript let names = ["tony", "bruce", "steve", "peter"]; let [winner, runnerup] = names; console.log(winner, runnerup); // Output: "tony" "bruce"
  • Using Rest with Array Destructuring:
    javascript let names = ["tony", "bruce", "peter", "steve", "abc", "xyz", "pyq"]; let [winner, runnerup, ...others] = names; console.log(winner); // Output: "tony" console.log(runnerup); // Output: "bruce" console.log(others); // Output: ["peter", "steve", "abc", "xyz", "pyq"]

Object Destructuring

  • Example:

    const student = {
        name: "karan",
        class: 9,
        age: 14,
        subjects: ["hindi", "english", "math", "science", "social studies"],
        username: "karan@123",
        password: "abcd",
    };
    
    let { username, password } = student;
    console.log(username); // Output: "karan@123"
    console.log(password); // Output: "abcd"
    
  • Renaming Variables During Destructuring
    javascript let { username: user, password: secret } = student; console.log(user); // Output: "karan@123" console.log(secret); // Output: "abcd"

  • Setting Default Values
    javascript let { username: user, password: secret, city = "Mumbai" } = student; console.log(city); // Output: "Mumbai" if city is not defined in student

  • If the object has a property, it will override the default value.
    javascript const student = { name: "karan", age: 14, class: 9, subjects: ["hindi", "english", "math", "science"], username: "karan@123", password: "abcd", city: "Pune", }; let { username: user, password: secret, city: place = "Mumbai" } = student; console.log(place); // Output: "Pune"

Practice Questions Solutions

  • Square and sum the array elements using the arrow function and then find the average of the array.

    let nums = [1, 2, 3, 4, 5];
    const square = nums.map((num) => num * num);
    console.log(square); // Output: [1, 4, 9, 16, 25]
    
    let sum = square.reduce((acc, cur) => acc + cur, 0);
    let avg = sum / nums.length;
    console.log(avg);   // Output: 11
    
  • Create a new array using the map function whose each element is equal to the original element plus 5.
    javascript let numbers = [2, 4, 6, 8, -2, -4]; console.log(numbers.map((number) => number + 5)); // Output: [7, 9, 11, 13, 3, 1]

  • Create a new array whose elements are in uppercase of words present in the original array.
    javascript let strings = ["adam", "bob", "catlyn", "donald", "eve"]; console.log(strings.map((string) => string.toUpperCase())); // Output: ["ADAM", "BOB", "CATLYN", "DONALD", "EVE"]

  • Write a function called doubleAndReturnArgs which accepts an array and a variable number of arguments. The function should return a new array with the original array values and all of the additional arguments doubled.

    const doubleAndReturnArgs = (arr, ...args) => [
        ...arr,
        ...args.map((v) => v * 2),
    ];
    
    console.log(doubleAndReturnArgs([1, 2, 3], 4, 4)); // Output: [1, 2, 3, 8, 8]
    console.log(doubleAndReturnArgs([2], 10, 4));    // Output: [2, 20, 8]
    
  • Write a function called mergeObjects that accepts two objects and returns a new object which contains all the keys and values of the first object and second object.
    javascript const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 }); console.log(mergeObjects({ a: 1, b: 2 }, { c: 3, d: 4 })); // Output: {a: 1, b: 2, c: 3, d: 4}