Hello friends, In this post we will learn about consuming self created javascript file inside our lightning component. You can use this approach to combined commonly/repetitively used function inside a single javascript file and used in any lightning component. So let's get started,

Consume self created javascript file in lightning component

Here I provided two types of javascript file example in which you can use any file and consume in lightning component.

Example 1 :
 (function() {
    window._name = function(a,b){
        return 'Hi '+a+' '+b;
    };
  
    window._sum = function(a,b) {
        return (a+b);
    };
 })();
Example 2 :
 window._sum = (function() {    
    return {
        getSum: function(a,b) {
            return (a+b);
        }
    };	
 }());

 window._name = (function() {    
    return {
        getFullName: function(a,b) {
            return 'Hi '+a+' '+b;
        }
    };	
 }());
Step 1: Copy any of the above script code and paste it into notepad and save the file with .js extension.

Step 2: Load your java script file in salesforce static resource by navigating to Setup | Custom Code | Static Resources.


Step 3: Create a lightning component by using following markup.

ConsumeJSFile.cmp
 <aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <ltng:require aura:id="scr" scripts="{!$Resource.MyJSFile}"></ltng:require>
    <lightning:button label="Call JS Function" variant="brand" onclick="{!c.handleJSfunction}"/>
    <br/>
    <b><div id="divSum"></div></b>
    <b><div id="divName"></div></b>
 </aura:component>
ConsumeJSFileController.js (When using example 1 javascript file)
 ({
    handleJSfunction : function(component, event, helper) {
        var sum=_sum(4,3);
        var fullname=_name('Jim','Carrey');        
        document.getElementById('divSum').innerHTML="Sum of Number : "+sum;
        document.getElementById('divName').innerHTML="Full Name : "+fullname;
    }
 })
ConsumeJSFileController.js (When using example 2 javascript file)
 ({
    handleJSfunction : function(component, event, helper) {      
        var sum=_sum.getSum(4,3);
        var fullname=_name.getFullName('Jim','Carrey');
        document.getElementById('divSum').innerHTML="Sum of Number : "+sum;
        document.getElementById('divName').innerHTML="Full Name : "+fullname;
    }
 })
Output: Doesn't matter you are using example 1 file or example 2 file; Output will be the same for each file.


Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Happy Coding...:)
Thank you.