Javascript Helloworld Example

JavaScript interview questions and answers

There are two different ways to include javascript within webpage: You can write as inline code in HTML page within head tag

1 For that we need to add script tag in HTML page.

In this example, I added one <script> tag in html head tag. I also added another <script> tag in html body tag. Depends on the requirement you can decide where you want to add JS code which we’ll cover in next chapter.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Hello world</title>

    <script>

        alert('hello world');

    </script>

</head>

<body>

    <script>

        alert('hello world');

    </script>

</body>

</html>

2. You can write code in separate JS file and reference it to the HTML page.

For that you have to create new JS file and use “src” attribute to call that file.

Here I have created helloworld.js under JS folder and call it through “src” attribute.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        alert('test');
    </script>
    <script src="js/helloworld.js"/>
</head>
<body>
    <script>
        alert('test');
    </script>
</body>
</html>