Hello, World! Your First JavaScript Programs
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!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of the picture and uses jQuery to calculate the average color of each area. Then, use

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Key Points Enhanced structured tagging with JavaScript can significantly improve the accessibility and maintainability of web page content while reducing file size. JavaScript can be effectively used to dynamically add functionality to HTML elements, such as using the cite attribute to automatically insert reference links into block references. Integrating JavaScript with structured tags allows you to create dynamic user interfaces, such as tab panels that do not require page refresh. It is crucial to ensure that JavaScript enhancements do not hinder the basic functionality of web pages; even if JavaScript is disabled, the page should remain functional. Advanced JavaScript technology can be used (

Data sets are extremely essential in building API models and various business processes. This is why importing and exporting CSV is an often-needed functionality.In this tutorial, you will learn how to download and import a CSV file within an Angular
