Imagine in this way! Theme defines MAIN STRUCTURE for whole site! Theme is something like structure for a Post, a Page or a custom post type, custom page,..! So far you know theme is really HTML code! In the end of Wordpress excute, it returns HTML code to browser, and browser display for you! That HTML is build based on theme file (index.php, header.php, footer.php, single.php)
Plugins use hook& filter to modify theme BEFORE we output to browser!
Example:
If you want to add social buttons to end of post! You can change single.php and add code to put some social button right below the_content()!
But you can make a plugin to use Wordpress's filter& hook to change HTML of post, to append you social buttons!
You can use hook to add javascript, do some logic code, then render HTML based on that result, then append or replace with something via Wordpress's hook& filter!
But what happen if you put plugin code in theme file? Assume you put some functions to render content into functions.php of theme! Then call those functions manually somewhere on your theme! Or even better, you can use hook& filter to auto change content without manually call in theme!
So as long as wordpress can include your code in someway, and run it! As long as your code run it, it can do anything for you via using hook& filter! Some simple plugins can quite easy to put into a theme file! But some big plugins are too bloat to put into theme file!
Then later, you decide to remove that function, you go to theme file and remove the code? Sound stupid, right? So we have plugin, it's a way to auto modify the running process of Wordpress to change content, to change database,...
Moreover, some hooks are runned before call theme so you can't put theme in theme file!
Conclusions:
As long as you code is included by wordpress, wordpress runs it then return result! You can put that code in theme files, wordpress will call it for you! But if you package it as a plugin, you can easy install/deactive/remove without changing any theme files! Additionaly, you also keep your theme simple/clean!
So when you need to changing something, put it as a plugin if possible! Don't put it in theme files!