Hello, World! — Основы JavaScript
По традиции начнем с написания программы «Hello, World!». Эта программа будет выводить на экран текст. Чтобы вывести что-то на экран, нужно дать компьютеру специальную команду. В языке JavaScript такая команда — console.log() :
Иногда для удобства мы будем показывать в комментариях результат запуска строчек кода, вот так: => РЕЗУЛЬТАТ . Например, // => 4 .
Комментарии
Кроме собственного кода в файлах с исходным кодом могут находиться комментарии. Это текст, который не является частью программы и нужен программистам для пометок. С их помощью добавляют пояснения, как работает код, какие здесь ошибки нужно поправить или не забыть что-то добавить позже.
Комментарии в JavaScript бывают двух видов.
Однострочные комментарии начинаются с // . После этих двух символов может следовать любой текст, вся строка не будет анализироваться и исполняться. Комментарий может занимать всю строку. Если одной строки мало, то создаются несколько комментариев:
Комментарий может находиться на строке после какого-нибудь кода:
Многострочные комментарии начинаются с /* и заканчиваются */ .
Такие комментарии обычно используют для документирования кода, например, функций.
Дополнительные материалы
![]()
Остались вопросы? Задайте их в разделе «Обсуждение»
Вам ответят команда поддержки Хекслета или другие студенты
Об обучении на Хекслете
- Статья «Как учиться и справляться с негативными мыслями»
- Статья «Ловушки обучения»
- Статья «Сложные простые задачи по программированию»
- Урок «Как эффективно учиться на Хекслете»
- Вебинар «Как самостоятельно учиться»
Открыть доступ
Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно
How To Write Your First JavaScript Program
The “Hello, World!” program is a classic and time-honored tradition in computer programming. It’s a short and complete first program for beginners, and it’s a good way to make sure your environment is properly configured.
This tutorial will walk you through creating this program in JavaScript. However, to make the program more interesting, we’ll modify the traditional “Hello, World!” program so that it asks the user for their name. We’ll then use the name in a greeting. When you’re done with this tutorial, you’ll have an interactive “Hello, World!” program.
Prerequisites
You can complete this tutorial by using the JavaScript Developer Console in your web browser. Before beginning this tutorial, you should have some familiarity with working with this tool. To learn more about it, you can read our tutorial “How To Use the JavaScript Developer Console.”
Creating the “Hello, World!” Program
To write the “Hello, World!” program, first open up your preferred web browser’s JavaScript Console.
There are two primary ways that we can go about creating the “Hello, World!” program in JavaScript, with the alert() method and with the console.log() method.
Using alert()
The first way that we can write this program is by using the alert() method, which will display an alert box over your current window with a specified message (in this case, it will be “Hello, World!”) and an OK button that will allow the user to close the alert.
Within the method we will pass the string data type as the parameter. This string will be set to the value Hello, World! so that that value will be printed to the alert box.
To write this first style of “Hello, World!” program, we’ll encase the string within the parentheses of the alert() method. We’ll end our JavaScript statement with a semicolon.
Once you press the ENTER key following your line of JavaScript, you should see the following alert pop up in your browser:

The Console will also print the result of evaluating an expression, which will read as undefined when the expression does not explicitly return something.
Pop-up alerts can be tedious to continue to click out of, so let’s go over how to create the same program by logging it to the Console with console.log() .
Using console.log()
We can print the same string, except this time to the JavaScript console, by using the console.log() method. Using this option is similar to working with a programming language in your computer’s terminal environment.
As we did with alert() , we’ll pass the "Hello, World!" string to the console.log() method, between its parentheses. We’ll end our statement with a semicolon, as is typical of JavaScript syntax conventions.
Once we press ENTER , the Hello, World! message will be printed to the Console:
In the next section, we’ll go over how to make this program more interactive for the user.
Prompting for Input
Every time we run our existing “Hello, World!” program, it produces the same output. Let’s prompt the person running our program for their name. We can then use that name to customize the output.
For each of our JavaScript methods we used above, we can begin with one line prompting for input. We’ll use JavaScript’s prompt() method, and pass to it the string "What is your name?" to ask the user for their name. The input that is entered by the user will then be stored in the variable name . We’ll end our expression with a semicolon.
When you press ENTER to run this line of code, you’ll receive a pop-up prompt:

The dialog box that pops up over your web browser window includes a text field for the user to enter input. Once the user enters a value into the text field, they will have to click on OK for the value to be stored. The user can also prevent a value from being recorded by clicking on the Cancel button.
It is important to use the JavaScript prompt() method only when it makes sense within the context of the program, as overusing it can become tedious for the user.
At this point, enter the name that you will want the program to greet. For this example, we’ll use the name Sammy .
Now that we have collected the value of the user’s name, we can move on to using that value to greet the user.
Greeting the User with alert()
As discussed above, the alert() method creates a pop-up box over the browser window. We can use this method to greet the user by making use of the variable name .
We’ll be utilizing string concatenation to write a greeting of “Hello!” that addresses the user directly. So, let’s concatenate the string of Hello with the variable for name:
We have combined two strings, "Hello, " and "!" with the name variable in between. Now, we can pass this expression to the alert() method.
Once we press ENTER here, we’ll receive the following dialog box on the screen:

In this case the user’s name is Sammy, so the output has greeted Sammy.
Now let’s rewrite this so that the output is printed to the Console instead.
Greeting the User with console.log()
As we looked at in a previous section, the console.log() method prints output to the Console, much like the print() function can print output to the terminal in Python.
We’ll be using the same concatenated string that we used with the alert() method, which combines the strings "Hello, " and "!" with the name variable:
This entire expression will be put within the parentheses of the console.log() method so that we will receive a greeting as output.
For a user named Sammy, the output on the Console will be as follows:
You now have a JavaScript program that takes input from a user and prints it back to the screen.
Conclusion
Now that you know how to write the classic “Hello, World!” program, as well as prompt the user for input, and display that as output, you can work to expand your program further. For example, ask for the user’s favorite color, and have the program say that their favorite color is red. You might even try to use this same technique to create a Mad Lib program.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Code in JavaScript
JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.
JavaScript Hello World In 3 Different Ways
In this tutorial, you will learn to write hello world in Javascript in 3 different ways. JavaScript hello world is the first program written by programmers so we have explained each step of the process.
Table Of Contents
Javascript Hello World
"Hello World" is the first program written by beginner programmers. In javascript, there are 3 different ways you can write hello world.
1. Using console.log
The first way to write Hello World in Javascript is to use the console.log method. console is an object that is used to write messages to the console.
One of the methods of console objects is console.log . This method is used to output the text in the console.
To open console in the browser, you can use the F12 key. You can also use the ctrl + shift + i key combination.
The output will be:
2. Using alert
The second way to write Hello World in Javascript is by using the alert method. The alert is a method that creates an alert box or a pop-up window with the text you provide.
To use the alert method, you need to add the following code in the script tag of the body tag.
Note : All the execution of javascript code will stop after the alert method is called until the user clicks on the OK button.
3. Using document.write
The third way to write Hello World in Javascript is to use the document.write method.
The document.write method writes the text in the HTML document. You will see the output in the browser.
Note : It is not recommended to use the document.write method because when it is executed after the page is loaded completely, it will overwrite the existing content in the HTML document.
We have seen all three ways to write hello world in javascript. Now as a beginner, we will see how to run Javascript files with a browser or without a browser.
Internal javascript
To write javascript code in an HTML file use the <script> tag and place your javascript code inside it.
You can put the <script> tag anywhere in the file but it is recommended to place it just before the end of the <body> tag.

report this ad
External Javascript
To write the "Hello World" program in an external javascript file, you have to create a file with a .js extension.
In this file, you have to write javascript code. To output "Hello World" in this file, use the console.log() method.
Here is the code for the hello-world.js file:
Now you can connect it to some HTML file by using <script src="hello-world.js"></script> tag.
Now run the page and you will see "Hello, World!" in the console.
Here is the code for the HTML file.
Running javascript file without browser
You can also run a javascript code without the browser. To do that, you have to use nodeJs .
To run a javascript code without the browser, you have to install nodeJS first. To install nodeJS on your system, follow the instructions on nodejs.org.
Once you have installed nodeJS , you can run a javascript code by using the nodeJS command.
Suppose your hello-world.js file is saved in /js/hello-world.js .
To run this file run the following command:
Conclusion
In this tutorial, you have learned 3 ways for javascript hello world. Also, we learned how to run javascript programs with a browser and without a browser.
Frequently asked questions
How do you say hello world in JavaScript?
You can use console.log() to display "Hello, World!" in the console and use the document.write() method to write it in the webpage.
How do you display hello world in an alert box using JavaScript?
Use the alert() method to display "Hello, World!" in the alert box.
how do you write hello world in an alert box?
To write "Hello World!" in the alert box write alert("Hello World!")

report this ad

report this ad
JavaScript Hello World Program with Code Examples
This tutorial will teach you how to create a simple JavaScript ‘Hello World‘ Program. You’ll see all four ways to print ‘Hello World’ in JavaScript with code examples and explanations.
“Hello World” is a traditional word and it is not mandatory you can use any other word. The basic purpose of creating the ‘Hello World’ program is to illustrate to beginners how a JavaScript program works.
Before starting, if you don’t know where to add JavaScript code in HTML. Then, you can check out our complete guide on how to add JavaScript to HTML.
How to Print Hello World in JavaScript
In JavaScript, we have four different ways to print ‘Hello World!‘.
- innerHTML – to write inside an HTML element
- alert() – to create an alert box
- document.write() – use to output in HTML. Just for testing purposes, not recommended
- console.log() – for debugging
Let’s see the JavaScript syntax to write Hello World in detail.
1. Use innerHTML to write JavaScript Hello World in HTML
This innerHTML method is used to print inside HTML elements. By using this method, you can print Hello World inside the HTML elements. We use it with the getElementsById() method.
Just see lines no. 12 to 14 in the code example given below. You can also copy the JavaScript Hello World script and paste it into your HTML document to see the result by yourself.
Code Explanation:
In the above code, I print ‘Hello World’ in the h2 element. To do this first I specified the id attribute for the h2 element so that I can access this element through the document.getElementById method. The ‘Hello World’ is enclosed in pair of double quotes because it is a text string. And it is the visible part that you will see in your browser.
However, you can use both double or single quotes. Inside the parenthesis or round brackets, I used the name of the id which is ‘demo‘ to write a text string inside the h2 element.
After the execution of the code, the output will look similar to the one below.
Tip: You can also access elements by JavaScript getElementsByTagName() method.
Let’s see the second method.
2. Use alert() to Create JavaScript Hello World Alert Box
This method is used to create an alert box in JavaScript. This alert box will appear when we open our HTML webpage or click a button. This is on us how we want JavaScript to show the alert box.
Let’s create a JavaScript Hello World alert box. The syntax to create the ‘Hello World’ alert box is given below.
Code Explanation: In the code above, I used an alert statement which is alert();. And inside the round brackets, I wrote the text string along with double quotes. And the JavaScript code is enclosed in the pair of <script> tags. If you’re using an external JavaScript file then <script> tags are not necessary.
You can copy the code and paste it at the end of <body> tags. Or you can paste it into your external JavaScript file without <script> tags. After saving the code, the output will be like this below.
Let’s see the third method to output “Hello World!” in JavaScript.
3. Use document.write() to write Hello World in HTML
This method is for testing purposes we don’t use it regularly and it is not recommended. Just see lines no. 11 to 13 in the code example below.
Code Explanation: In the above code, I used a JavaScript document. write(); statement. And inside round brackets, I wrote text string. The output will look like this below.
The downside of using this statement is that it overwrites HTML content. For example, you created a button through JavaScript and it will show a text line on click. But when you click the button all the HTML content missing.
Let’s see the last method.
4. Use console.log() to write Hello World
This method is used for JavaScript debugging purposes. In this method, we use our browser’s console to write JavaScript code. The benefit of using the console.log is that it outputs the result on the same screen on the next line.
It really helps in debugging. You can write JavaScript code without any text editor using just your browser. Let’s print Hello World to the console.
Firstly, open your browser’s console. To do this, open a new tab in your browser. Then, right-click and click inspect as shown below.
After that click on the console, and write your code there as shown below.
To print JavaScript “Hello World” in the console, just see the code example below.
You can copy this line of code and paste it into your browser’s console. Then, click enter and see if the result will be the same as shown below.
So, this is how you can create a simple JavaScript Hello World program.
That’s it. Hope you liked it. If you have any questions related to this tutorial then feel free to ask in the comments section below.
Leave a Comment Cancel Reply

report this ad