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/

Get base url in javascript

If you are constructing your URL like this;

message += '<br><a href=/Project/GetFileData?documentId=' + response.Data.vm.DocumentId + '>' + response.Data.vm.FileName + '</a>';

You will get results like this;

https://www.foo.com/Project/GetFileData?1234

This will not work on a web site that has following URL;

https://www.foo.com/demo/Project/GetFileData?1234

To fix this problem in ASP.NET Core, use this;

var url = '@Url.Content("~");
message += '<br><a href=' + url + '/Project/GetFileData?documentId=' + response.Data.vm.DocumentId + '>' + response.Data.vm.FileName + '</a>';

Other useful function to find URL are;

var url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );

Return a Json Object from another function call

When we try to capture a value from called method we get undefined. The reason is that data hasn’t been fetched yet. Fetch takes some time to make the call and send back the result, and it’s asynchronous, Here is an example;

function getApi() {
  var obj;

  fetch("https://foo.apicode.com/posts/1")
    .then((res) => res.json())
    .then((data) => (obj = data));

  return obj;
}

let x = getApi();
console.log(x);

When we console.log the value, getApi() didn’t finish yet, therefore didn’t set the obj

The fetch method is asynchronous, so obj is undefined because the code is going to the next instruction without waiting the fetch. We can simply use async/await method that is a great way to make asynchronous calls because await will wait for the result before going to the next instruction.

async function getApi() {

      const response = await fetch("https://foo.apicode.com/posts/1")
        
      const obj = await response.json()
      
      return obj;
    }

(async() => {
   let x = await getApi();
   console.log(x);
})()

Resources

https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function

Simplest way to test Node.js is working

I am assuming that Node.Js is installed on your machine. Use any editor and write this JavaScript;

var http = require('http');
var url = require('url');

http.createServer(function (req, res) {
    console.log("Request: " + req.method + " to " + req.url);

    res.writeHead(200, "OK");
    res.write("<h1>Hello</h1>Node.js is working");
    res.end();
}).listen(80);
console.log("Ready on port 80");

Save it as NodeTest.js.

Open a command prompt and run this;

node NodeTest.js

You should see this;

JavaScript Object Patterns

All object properties in JavaScript are public. There is no explicit way to indicate that a property shouldn’t be accessed from outside. Sometime we don’t want the data to be public. For example, when an object uses a value to determine some sort of state, modify that data without the objects’ knowledge throws the state management process.

One way to avoid this is by using naming conventions. For example, it’s quite common to prefix properties with an underscore (such as _name) when they are not intended to be public. However, there are other ways of hiding data that don’t rely on conventions.

The Module Pattern

There are many different ways to create and compose objects in JavaScript. While JavaScript does not include the formal concept of private properties, we can create data or functions that are accessible only from within an object. For singleton objects, we can use the module pattern to hide data from the outside world. we can use an immediately invoked function expression (IIFE) to define local variables and functions that are accessible only by the newly created object. Privileged methods are methods on the object that have access to private data. We can also create constructors that have private data by either defining variables in the constructor function or by using an IIFE to create private data that is shared among all instances.

var yourObject = (function() {

      // private data variables

      return {
          // public methods and properties
      };
}());

Here we are defining custom type that are keeping their private properties. This is similar to module pattern inside the constructor to create instance-specific private data.

function Student(name) {
            this.name = name;
        }
        Student.prototype = (function () {
            //private variables inside this closure scope
            var age = 25;   
            var myGrades = [93, 95, 88, 0, 55, 91];

            function getAge() {
                return age;
            }
            function growOlder() {
                age++;
            }

            function getAverage() {
                var total = 0;
                for (var i = 0; i < myGrades.length; i++) {
                    total += myGrades[i];
                }
                return avg = (total / myGrades.length);
            }

            function getGradeStatus() {
                var failingGrades = myGrades.filter(function (item) {
                    return item < 70;
                });

                return 'You failed ' + failingGrades.length + ' times.';
            }

            //revaling
            return {
                getAverage: getAverage,
                getGradeStatus: getGradeStatus,
                getAge: getAge,
                growOlder: growOlder
            };

        })();
var student1 = new Student("shahzad");
var student2 = new Student("ali");
student1.name		//returns "shahzad"
student1.getAge();	//returns 25
student1.growOlder();	//increment age 
student1.getAge();	//returns 26
student1.getAverage();	//returns 70.33333333333333
student1.getGradeStatus();	//returns "You failed 2 times."
student2.name			//returns "ali"
student2.getAge();		//returns 26
student2.getAverage();		//returns 70.33333333333333
student2.getGradeStatus()	//returns "You failed 2 times."

If we want private data to be shared across all instances, we can use a hybrid approach that looks like the module pattern but uses a constructor;

var Student = (function() {
    //everyone shares the same age
    var age = 20;   
    function IStudent(name){
        this.name = name;
    }
    
    IStudent.prototype.getAge = function() {
        return age;
    };
    
    IStudent.prototype.growOlder = function() {
        age++;
    };
    
    return IStudent;
}());

var student1 = new Student("shahzad");
var student2 = new Student("ali");
console.log(student1.name);	//returns shahzad
console.log(student1.getAge());		//returns 20
console.log(student2.name);		//returns ali
console.log(student2.getAge());		//returns 20
student1.growOlder();			//increment age
console.log(student1.getAge());		//returns 21
console.log(student2.getAge());		//returns 21

The IStudent constructor is defined inside an IIFE. The variable age is defined outside the constructor but is used for two prototype methods. The IStudent constructor is then returned and becomes the Person constructor in the global scope. All instances of Person end up sharing the age variable, so chaing the value with one instance automatically affects the other instance.

The Mixins Pattern

Mixins are a powerful way to add functionality to objects while avoiding inheritance. A mixin copies properties from one object to another so that the receiving object gains functionality without inheriting from the supplying object. Unlike inheritance, mixins do not allow you to identify where the capabilities came from after the object is created. For this reason, mixins are best used with data properties or small pieces of functionality. Inheritance is still preferable when you want to obtain more functionality and know where that functionality came from.

Scope-safe constructors

Scope-safe constructors are constructors that we can call with or without new to create a new object instance. This pattern takes advantage of the fact that this is an instance of the custom type as soon as the constructor begins to execute, which lets us alter the constructor’s behavior depending on whether or not you used the new operator.

function Person(name) {
    this.name = name;
}
Person.prototype.sayName = function() {
    console.log(this.name);
};
var person1 = Person("shahzad");		//note: missing “new”
console.log(person1 instanceof Person);		//returns false
console.log(typeof person1);			//returns undefined
console.log(name);				//returns shahzad

The name is created as a global variable because the Person constructor is called without new. Since this code is running in nonrestrict mode so leaving out new would not throw an error. The fact that constructor begins with capital letter should be preceded by new. What if we want to allow this use case and have the function work without new. We can implement a pattern like this;

function Person(name) {
    if (this instanceof Person) {
        //called with "new"
    } else {
        //called without new
    }
}

Let’s re-write our constructor logic;

function Person(name) {
    if (this instanceof Person) {
        this.name = name;
    } else {
        return new Person(name);
    }
}
var person1 = Person("shahzad");
console.log(person1 instanceof Person);		//returns true
console.log(typeof person1);			//returns object
console.log(person1.name);			//returns shahzad

The constructor is called recursively via new if new keyword is not used to create a proper instance of the object. This way following are equivalent;

var person1 = new Person(“shahzad”);
var person2 = Person(“shahzad”);

console.log(person1 instanceof Person);		//returns true
console.log(person2 instanceof Person);		//returns true

Creating new objects without using the new operator is becoming more common. JavaScript itself has several reference types with scope-sfe constructors, such as Object, Array, RegExp, and Error.

Resources

https://www.theodinproject.com/paths/full-stack-javascript/courses/javascript/lessons/factory-functions-and-the-module-pattern