How to use custom Javascript code inside a plugin?

Look into wp_register_script() and wp_enqueue_script(). You may be able to get by with only the latter.

Pay special attention for your case of wanting it before the closing </body> that you can specify in_footer as a parameter.

wp_enqueue_script(  $handle, //(string) name of script
                    $src="", // uri to script
                    $deps = array(), //handles of other scripts this script is dependent on
                    $ver="1.0", version number of script 
                    $in_footer = true //if script should be in footer
                   )

You can hook the above via the wp_enqueue_scripts hook

function enqueue_your_scripts() {

    wp_enqueue_script( 'script-name', plugin_dir_url( __FILE__ )  . '/js/example.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_your_scripts' );

In the above, plugin_dir_url( __FILE__ ) is returning the plugin directory the file is in, and we’re assuming a subdirectory of /js/ and a file named example.js