Japan attacked Pearl Harbor because it wanted to have an empire in East Asia and it feared that the United States would prevent that from happening.
Japan had, at least since the Russo-Japanese War of 1905, thought of itself as a major power. It felt that it should have an empire like those of the other major powers. However, it was prevented from getting an empire because much of the area around Japan was already colonized by other countries.
Once World War II started in Europe, this changed to some degree. The Germans, who were allied with the Japanese, had defeated France and the Netherlands. This meant that Japan could hope to take French colonies in Indochina and Dutch colonies in Indonesia. The Germans were fighting the British, and the Japanese could also hope to take British colonies in the area. The main problem was that the US did not want that to happen.
For example, when Japan took French Indochina, the US stopped selling oil and scrap iron (we were Japan’s major source for these important commodities) to Japan. Japan calculated that it would run out of oil in about two years. Therefore, it needed to take the oilfields in Indonesia or else it would run out of oil and be at the mercy of any country that wanted to push it around.
Japan decided to go ahead and take an empire. But first it needed to make sure the US could not interfere. Therefore, it attacked Pearl Harbor to try to destroy the US fleet and make it impossible for the US to interfere.
A consensus had been reached from a series of imperial conferences that Japan would need to fight the US to obtain victory in Southeast Asia. To prevail in a protracted conflict, Japane needed high levels of raw materials and the only way to obtain the resources from Southeast Asia was to provoke the US into a war through a surprise attack. The attack on the US would give the Japanese the time they needed to attain the resources they required and to further expand its own industrial capability. It was thus necessary for the Japanese navy to first destroy the American Pacific fleet and challenge US naval supremacy since it was the only potent force that could halt the Japanese advance in the region. By destroying the battle fleets that were located at Pearl Harbour, Japan would be able to gain the time they needed to erect a giant barrier around Southeast Asia, which when guarded by the imperial navy, could keep the US at bay. A knockout blow at sea was also essential to gain the psychological ascendancy they needed to drag out the war so as to force the Americans out of it - they were sure that the Americans would not be invested into fighting a protracted conflict in a region that they would not familiar with.