JavaScript frequently used functions

This is a handy reference for frequently used JavaScript functions;

Shorten the console log

Instead of writing console.log() again and again in code, we can bind it;

//tired of typeing console.log. shorten it
    const log = console.log.bind(document);
    log("does it works?");
    log("yes");

Merge two arrays into one

If you want to merge two arrays of any size into a single array you can use the concate JavaScript function.

//merge two arrays
    const array1 = ["one", "two", "three"]
    const array2 = ["four", "five", "six"]

    const merged = array1.concat(array2)
    console.log(merged)
    //Output:
    //(6) ['one', 'two', 'three', 'four', 'five', 'six']

Merge two objects into one

If you working with objects you can merge them together with this simple trick.

//merge two objects into one
    const user = {
        name: "Shahzad",
        gender: "Male"
    };
    const artcile = {
        title: "Born on the Fourth of July",
        publishDate: "12/14/2021"
    };
    const summary = {...user, ...artcile}
    console.log(summary)
    //Output:
    /*
    gender: "Male"
    name: "Shahzad"
    publishDate: "12/14/2021"
    title: "Born on the Fourth of July"
    */

Shorten an array

There exist an easy way for web developers to shorten an array. You need to use the length method and pass a number that is smaller than the actual array size.

//shorten an array
    const big_array = ["one", "two", "three", "four", "five", "six"]
    big_array.length = 3
    console.log(big_array)
    //Output:
    //(3) ['one', 'two', 'three']

Shuffle an array

Sometimes you want to randomize the values within an array. To achieve this you can use the Array.sort function with a random compareFunction.

//shuffle an array
    const array = ["one", "two", "three", "four", "five", "six"]
    array.sort( function(){ return Math.random() - 0.5})
    console.log('shuffling array')
    console.log(array)

Use isNum to verify a number

With this function, you can check whether a value or variable is a number (int, float, etc) or not.

//use isNum to verify Number
    function isNum(n) {return !isNaN(parseFloat(n)) && isFinite(n);}

    console.log(isNum(4125))        //true
    console.log(isNum(50))          //true
    console.log(isNum("jQuery"))    //false

Use isStr to verify a string

With this function, you can check whether a value or variable is in string format or not.

//use isStr to verify string
    const isStr = value => typeof value === 'string';

    console.log(isStr("jQuery"))    //true
    console.log(isStr(4125))        //false
    console.log(isStr(true))        //false

Use isNull

Often it is useful to check if a result or data is null.

//use isNull
    const isNull = value => value == null || value === undefined;

    console.log(isNull(null))   //true
    console.log(isNull())       //true
    console.log(isNull(123))    //false
    console.log(isNull("s"))    //false

Calculate the performance of a function

If you want to check how long a function runs you can use this approach in your program.

//Calculate the performance of a function
    const start = performance.now();
    //business program
    const end = performance.now();
    const total = start - end
    console.log("function takes " + total + " milisecond");

Remove duplicates from an array

We often encounter an array with duplicated data in it and use a loop to remove those duplicates. This function can remove duplicates in an easy way without using a loop.

//Remove duplicates from an array
    const duplicate_array = array => [...new Set(array)]
    console.log(duplicate_array([
        "One", "Two", "Three", "Two", "Four",
        "One", "Two", "Three", "Two", "Five",
        "Three", "One", "Four", "Two", "Five"]))

    //Output:
    //(5) ['One', 'Two', 'Three', 'Four', 'Five']

Use logical AND/OR for conditions

Instead of using an if-condition, you can use a logical AND/OR. This can be used within a function for executing commands.

//Use logical AND/OR for conditions
    const input = 2
    input == 4 && console.log("it is 4")
    input == 4 || console.log("it is not 4")

    //can also be used for assigning values
    function defaultTo4(arg) {
        arg = arg || 4; //arg will have 4 as a default value if not set
        console.log(arg)
    }
    let arg1 = 2
    let arg2 = null
    defaultTo4(arg1)    //2
    defaultTo4(arg2)    //4

Ternary operator

The ternary operator is just cool. You can avoid bad-looking nested conditional if..elseif..elseif with ternary operators.

//Ternary operator
    function temperature(temp){
        return (temp > 39 || temp < 35.5) ? 'Stay home'
        : (temp < 37.5 && temp > 36.5) ? 'Go out and play'
        : (temp <= 39 && temp >= 35.5) ? 'Take some rest'
        : ''
    }

    console.log(temperature(38))    //take some rest
    console.log(temperature(36))    //take some rest
    console.log(temperature(39.1))  //Stay home
    console.log(temperature(35.1))  //Stay home
    console.log(temperature(37))    //Go out and plan

Resources

https://docs.microsoft.com/en-us/javascript/

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect