The first step to learning JavaScript programming: Start with "Hello, World!"
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!');
and press Enter. If all goes well, you should see the output "Hello, World!" similar to the screenshot below.
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>
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!');
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>
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> <🎜>
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!');
(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!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment