Array & Function

JavaScript Arrays

Array

In JavaScript, arrays consist only of values

  • Array literal

    var a = [1,2,3]

  • Array constructor function

    var b = new Array(1,2,3)

Array Iteration

  • for

    var a = [1,2,3]
    
    for (var i=0 ; i <a.length; i++){
        console.log(i, a[i])
    }

  • for .. of

    : Outputs element values one by one

    for (var elem of a){
        console.log(elem)
    }

  • forEach

    : Takes a function itself as an argument

    a.forEach( function(elem, idx) {
        console.log(idx, elem)
    })

  • for .. in

    • Not only accesses array elements but properties can also be output

      • Since arrays in JavaScript are also objects, property settings are possible, but they become properties of the Object, not the list

    var a = [1,2,3]
    
    a.name = 'myarr'
    
    for (var i in a){
        console.log(i, a[i])
    }
    
    //0 1
    //1 2
    //2 3
    //name myarr   => iterates through properties as well
    • Be careful when using the for ... in form!

      • for ...in iterates through all properties of the Object itself

Array methods

  • sort

    • If there is no comparison function (argument), it sorts based on strings

      • If you don't want that, pass a comparison function as an argument

    • If there is a comparison function, it sorts based on the return value being less than 0

  • String-related

    • join

      • array.join('haha')

  • toString

  • Array merging

    • concat

      : Merges two arrays

  • Element insertion/deletion

    • push

    • pop

    • unshift

      • Insert at the left end

    • shift

      • Remove from the left end

  • Index search

    • indexOf

  • Array manipulation

    • splice(start[, deleteCount[, item1[, item2[, ...]]]])

      • Modifies the original array itself

      • Can also modify/delete elements

  • Array slicing

    • slice

      : Returns the result

JavaScript Functions

Function Declaration

1. Function Declaration Statement

2. Function Expression

3. Immediately Invoked Function Expression (IIFE)

4. Arrow Function (ES6)

Function Arguments

  • In JavaScript, there are no restrictions on passing parameters to functions

  • The arguments object contains all information about the parameters passed

    • If no arguments are passed, it shows undefined

      • undefined

        : The value JavaScript assigns when initializing a variable

Last updated