Magento 2:- How to call a js file on homepage?

there are two way to do it.

1.first you add it from admin panel. content->page -> edit page in design tab Layout Update XML

    <head><script src="js/myfile.js"/></head>
  1. if your js is based on some js library.

app/design/frontend/yourspacename/yourtheme/Magento_Cms/layout/cms_inde_index.xml

 <head><script src="js/myfile.js"/></head>

You can call your js only on home page by adding cms_index_index.xml file into your layout directory and your module directory structure should be

app/code/YOUR_NAMESPACE/YOUR_MODULENAME/view/frontend/layout/

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head><link src="js/myfile.js"/></head> 
</page>

If you want to include a javascript file from your theme into a cms page or block, you can use the built in x-magento-init system. This will remove the need to use xml or placing anything in the head of the page.

Inside of the cms block or page, place in these lines:

<script type="text/x-magento-init">
{
    "*": {
         "Magento_Theme/js/custom-file": {}
    }
}
</script>

This is unique to Magento 2 and is a way of initializing Javascript by Magento and not the browser. Alan Storm goes into depth on this issue here. But the basic idea is you have Magento trigger off the execution of Javascript.

You pass in the DOM node you want to target (in this case we are targeting the whole page with *). You then pass in the path to the file you want to include. For us, we are passing in Magento_Theme/js/custom-file which will resolve to:

app/design/frontend/{Namespace}/{theme}/Magento_Theme/web/js/custom-file.js

Note that you are using the Magento shorthand here, where the path ditches the .js file ext and then web dir, this can trip you up sometimes.

Inside the custom file you need to use require JS in the file to prevent conflicts. There are a few different ways to do this, but this works for me:

define([
    'jquery'
], function ($) {
    return function () {
        // Your code here
    }
});