Introduction¶
JavaScript (JS), unlike Java, is a scripting language that is, among other things, used on websites.
JavaScript and browsers¶
JavaScript has been designed as a language whose starting environment will be a web browser. All web browsers are equipped with engines that can interpret JavaScript code. The code is executed on the client-side, there is no direct access to the user's machine except the currently running browser. The code of the client-side
is not private - anyone accessing the page has the possibility to display the code.
JavaScript and servers¶
With the creation of Node.js in 2009, JavaScript gained the ability to execute code outside the browser (the so-called server-side
). Node.js is a bootable environment, giving access to an asynchronous input/output system (it has access to a file system for example). Node.js can also use external packages. These packages can be installed using the NPM (Node package manager). NPM for Node.js has a similar function to Maven for a project created in Java for example.
In this knowledge base we focus on JS in web browsers.
Running JS code¶
We can "connect" the JS code directly to the HTML page. We can do this using the script
tag.
We can:
- write directly inside the
script
tag. - put in an external file whose path is given in the
src
tag ofscript
attribute.
The following examples show both approaches:
<script type="text/javascript">
console.log("Example of a message displayed in a console using the so-called inline code");
</script>
<script type="text/javascript" src="code.js"></script>
NOTE: In both cases, the
type
attribute is optional.NOTE: Storing the JS code in separate files is the preferable approach.
Console.log¶
The Object console
is an object available globally in a web browser. It has a set of methods whose main use is to log information into a special screen. This console can be displayed in the web browser's programming tools, e.g. using the Console
tab in the Chrome
browser (which can usually be accessed using the F12
shortcut).
Some of the most common methods are log
, info
, warn
or error
, which accept the arguments that are later on displayed on the console, e.g:
console.log("This text will be displayed on browser console");
Comments¶
JS, like other programming languages, allows you to write comments in the code that are ignored by the code interpreter. Two types of comments can be used in JS - line and block comments, and their writing is identical to Java, i.e:
-
A block comment starts with
/*
characters and ends with*/
characters. Anything in between these characters is ignored when interpreting the code. These comments cannot be nested, but linear comments can be used inside them. -
A line comment starts with
//
and ends with//
and applies to the end of the line of the script. Anything after these characters up to the end of the current line is ignored when interpreting the code.