Home Web Front-end JS Tutorial Hello, World! Your First JavaScript Programs

Hello, World! Your First JavaScript Programs

Feb 16, 2025 pm 01:08 PM

The first step to learning JavaScript programming: Start with "Hello, World!"

Hello, World! Your First JavaScript Programs

Learning any programming language and writing "Hello, World!" programs is a traditional and important starting step. This is a simple program that outputs the phrase "Hello, World!" to the console, marking the beginning of your programming journey. We will follow this tradition and write this program in JavaScript. It will be a simple statement that prints "Hello, World!" to the console.

You need to open your commonly used console (Node REPL, browser console or ES6 console on web pages). Once the console is opened, just enter the following code:

console.log('Hello, World!');
Copy after login
Copy after login
Copy after login

and press Enter. If all goes well, you should see the output "Hello, World!" similar to the screenshot below.

Hello, World! Your First JavaScript Programs

Congratulations, you just wrote your first JavaScript program! It may seem trivial, but as one wise man said, every master of programming begins with a line of code (or something similar).

JavaScript application in browser

JavaScript is an interpreted language that requires a host environment to run. Due to its origin, JavaScript is mainly running in browsers, but it can also run in other environments; for example, the first program we just wrote is running in Node REPL. Node can also be used to run JavaScript on the server. But by far, the most common use of JavaScript is still to make web pages interactive. So, before we proceed, we should understand the composition of the web page.

Three-layer structure of web pages

Almost all web pages are composed of three key elements - HTML, CSS and JavaScript. HTML is used to mark content; CSS is the presentation layer; JavaScript increases interactivity.

Each layer is built on the foundation of the previous layer. A web page works just by relying on the HTML layer—in fact, many websites remove the CSS layer on "naked day". Websites that use only HTML layers will be presented in their purest form, which looks very old-fashioned, but should still be fully functional.

Keep hierarchical separation

Separating the focus of each layer so that each layer is responsible for only one thing, is widely considered a best practice. Putting them together results in very complex pages, all the code is mixed in one file, resulting in "label soup" or "code pasta". This used to be the standard way to make a website, and there are still many such examples online.

Non-invasive JavaScript

When JavaScript was initially used, it was designed to be inserted directly into HTML code, as shown in the following example, a message will be displayed when a button is clicked:

<button id='button' href='#' onclick='alert("Hello World")'>Click Me</button>
Copy after login
Copy after login

This makes it difficult to see what's going on, as JavaScript code is mixed with HTML. This also means that the code is tightly coupled to HTML, so any changes to HTML require changes to JavaScript code to prevent breakage.

JavaScript code can be separated from the rest of HTML by placing it inside its own tag. The following code will achieve the same result as above:

console.log('Hello, World!');
Copy after login
Copy after login
Copy after login

This is better because all JavaScript code is located in one place, between two script tags, rather than mixing with HTML tags.

We can go a step further and separate the JavaScript code from HTML and CSS completely and put it in its own file. This can be done by using the src attribute in the script tag to specify the file to be linked:

<button id='button' href='#' onclick='alert("Hello World")'>Click Me</button>
Copy after login
Copy after login

Then put the JavaScript code in a file named main.js in the same directory as the HTML document. The concept of completely separating JavaScript code is one of the core principles of non-invasive JavaScript.

Similarly, CSS should be placed in separate files, so the only code in the webpage is the actual HTML and a link to the CSS and JavaScript files. This is often considered a best practice and the approach to be adopted in this book.

Self-closing tag

If you have used XML or XHTML, you may have encountered such self-closed tags:

<button id='button'>Click Me</button>
<🎜>
Copy after login

This is unnecessary in HTML5, but it still works.

Elegant downgrade and progressive enhancement

Elegant downgrade is the process of building a website that makes it work best in modern browsers using JavaScript, but can still run with reasonable standards in older browsers or if JavaScript or some of its features are not available . An example of this is the programs for HD (HD) broadcasts—they work best on HD TVs, but still run on standard TVs; just the picture quality will be lower. These programs can even run on black and white TVs.

Progressive enhancement is the process of building a web page from scratch, with a basic level of functionality, and then add additional enhancements if the browser is available. If you follow the three-layer principle, the JavaScript layer enhances web pages instead of becoming an integral element of the page, then this should feel natural. An example might be a telephone company offering basic level phone calls, but if your phone supports it, there are additional services like call waiting and calling number display.

Whenever you add JavaScript to a web page, you should always consider the approach you want to take. Are you trying to start with many amazing effects, push the boundaries, and then make sure that the experience will be elegantly downgraded for those who may not have the latest and greatest browsers? Or do you want to start by building a functional website that runs on most browsers and then use JavaScript to enhance the experience? The two methods are similar, but the subtleties vary.

Your second JavaScript program

We will end this chapter with a second JavaScript program that will run in the browser. This example is more complex than the previous one, with many concepts that will be introduced in more detail in later chapters, so don't worry if you don't know everything at this stage! The purpose is to show you the capabilities of JavaScript and introduce some important concepts that will be introduced in the upcoming chapters.

We will follow the practice of non-invasive JavaScript mentioned earlier and put our JavaScript code in a separate file. First create a folder called rainbow. In this folder, create a file named rainbow.html and another file named main.js.

Let's start with HTML. Open rainbow.html and enter the following code:

console.log('Hello, World!');
Copy after login
Copy after login
Copy after login

Hello, World! Your First JavaScript Programs

(The rest of the content is similar to the original text, except that the language is adjusted and some paragraphs are merged, keeping the original meaning unchanged.)

Don't destroy the network

An important concept in JavaScript language development is that it must be backward compatible. That is, all the old code must work the same way when interpreted by the engine running the new specification (it's kind of like saying that PlayStation 4 still has to be able to run games created for PlayStation 1, 2, and 3). This is to prevent JavaScript from "breaking the web" by making major changes that would prevent old code on some websites from running as expected in modern browsers.

Therefore, new versions of JavaScript cannot do things that are impossible in previous versions of languages. All that is changed is the representation that implements a specific function to make it easier to write. This is called syntax sugar because it allows writing existing code snippets in a more concise and concise way.

The fact that all versions of JavaScript are backward compatible means that we can use the translator to convert our code from one version of JavaScript to another. For example, you could write code using the latest JavaScript version and translate it into version 5 code that runs in almost any browser.

There is a new ECMAScript version every year, which means that browsers may always be slightly behind when it comes to implementing the latest features (they are doing this faster, but most browsers still take two years to go ES6 module can only be supported). This means that if you want to use the latest coding technology, you may end up with a translator (such as Babel).

FAQ (FAQ) About Your First JavaScript Program

(This part of the content is similar to the original text, but the language has been adjusted to make it smoother and more natural.)

The above is the detailed content of Hello, World! Your First JavaScript Programs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles