Alert boxes are used for displaying a Popup Alert Box with Warnings or Texts Like Hello [ by using alert("hello") ] in JavaScript.
JavaScript Alert Boxes are not always used to Show Texts like Hello in the Output screen. Its Also can used for showing some Important Informations.
For example, I have a form where user can fill Data about themselves and submit that information to me. But if user Left any Input Field Empty I can use JavaScript alert() Method to Tell my users to Fill the Empty field or Guide my users or show Errors.
To use Alert Method in JavaScript, we have to write alert() inside the JavaScript Script Tags. (If we are using JavaScript inside an HTML Web-Page).
After writing Alert method, we have to write our Data/Text/Warning, that we want to Display inside our Alert Box. [ like: alert("Hello") ].
index.html [internal JS]
<script>
alert("Hello");
</script>
my.js [External JS]
alert("Hello");
We can use our JavaScript Variable, to display our Variable’s Data inside the Alert Box at the Time of Execution.
For that, you have to Create a Variable in JavaScript. Assign a Value/Data for your Variable. After that, you just need to write your Variable’s name inside the alert method brackets. [ like alert(variableName)].
my.js
var myVariable = "hellow";
alert(myVariable);
We also can show texts like ” Hello World ” inside our Browser's Console Tab. For that, we have to Use JavaScript console.log method instead of JavaScript Alert Method.
For displaying texts like ” Hello World ” in Console using JavaScript, We have to use JavaScript console.log method. We have to write our Data/Text (which is Hello World) inside the console.log method's Brackets [ like console.log(“Hello World”)]
my.js
console.log("Hello World");
JavaScript Alert method can Display Long texts like ” Hello! I am an alert box!! “. There is No Limit for Character Length, but If you want your Alert Method to work Normally. Then Don’t put Character more then 1000 in JavaScript Alert Method.
Just Put your Long Text inside the JavaScript’s Alert Method and your Long Text will Display on your Alert Box.
my.js
alert("Hello! I am an alert box");
HTML Don't support Methods like Alert Method and we cant Run JavaScript Directly in Browser. To Show Alert Messages in HTML and Run JavaScript in Browsers, we have to use JavaScript inside our HTML Document. Then we can Display our Alert Message using JavaScript’s Alert Method.
index.html
<html>
<body>
<script>
alert("Your Message Here...!");
</script>
</body>
</html>