The justification for building the 1st nuclear weapons was that Germany and Japan were also trying to make them. A lot of people were hoping that it would prove impossible. Evidence gathered after the war showed that the Germans had taken the wrong track and, as a result, were several years behind the Allies at the end of the war. Japan was on the right track but did not give it any priority, and would not have had the resource base to enrich the necessary uranium in time. Both missed the potential for a plutonium based bomb.
As for using nuclear weapons against Japan, projections were for 1 million to 4 million Allied casualties from the invasion of Japan proper, and 10 million to near extermination for the Japanese if they remained as fanatical as they had to that date. Allied planners had a duty to explore all possible alternatives for avoiding that, and it was difficult to justify not using the nuclear weapons at that time. The decision to deploy chemical weapons as part of the invasion plan had already been made.
The impact of the nuclear weapons used on Hiroshima and Nagasaki gave the Japanese a politically acceptable excuse to surrender. Yes, there are some scholars who claim that the Japanese would have surrendered even without the use of the nuclear weapons, but there is a even larger number (including many Japanese ones) who claim they were not ready to do so, so there is no way to be sure even in retrospect.
The power, and secondary effects, of the nuclear attacks also shocked the world in a way which would otherwise not have been possible, or anticipated, and probably was the reason further nuclear exchanges and WWIII were averted, becoming the Cold War instead. This was, of course, unanticipated and serendipitous, though fairly obvious in retrospect.