How come Facebook is able to show me ads for something I was searching on Google?

How come Facebook is able to show me ads for something I was searching on Google?. I’m also curious about this question. And got a great answer.

So, when you log into Facebook, you would be shown an ad from Apple. It does not matter that you were logged out of Facebook when you visited Apple’s website. The ad will be shown based on your browsing habits outside of Facebook. In a sense, Facebook might not even know that you visited Apple’s website, as the ads are created using your data (using tracking cookies) complied by the advertisers. In addition, you might see the same ad on other websites, too (not just on Facebook), as the same advertisers engage with different ad exchanges.