Introduction¶
JavaScript (JS), unlike Java, is a scripting language that includes use on websites.
JavaScript and browsers¶
JavaScript was designed as a language whose running environment will be a web browser. All web browsers are equipped with engines that can interpret JavaScript code. The code executed on the client side does not have direct access to the user's machine apart from the currently running browser. The client-side
code is not private, i.e. everyone visiting the website can view 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 an executable environment that gives access to the asynchronous input/output system (eg has access to the file system). Node.js can also use external packages. These packages can be installed using the dependency manager - NPM (Node package manager). NPM for Node.js performs a similar function as Maven for a project created e.g. in Java.
In this knowledge base, we focus on JS in web browsers.
Running JS code¶
JS code can be "connected" directly to the HTML page. We can do this with the script
tag.
We can use this code:
- write directly inside the
script
tag - put in an external file, the path of which is given in the
src
attribute of thescript
tag.
The following examples show both of these approaches:
<script type="text/javascript">
console.log("An example of a message displayed in the console using the so-called inline code");
</script>
<script type="text/javascript" src="code.js"></script>
NOTE: In both of the above cases, the
type
attribute is optional.NOTE: Saving JS code in separate files is definitely the preferred approach.
Login¶
Object console
is a globally accessible object in the web browser. It has a set of methods the main use of which is logging information on a special screen. This console can be displayed in the web browser developer tools, e.g. by using the Console
tab in the Chrome
browser (which can most often be accessed using the F12
shortcut).
Some of the more commonly used methods are log
, info
, warn
or error
which take arguments then 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 your code that are ignored by the code interpreter. In JS, you can use two types of comments - line and block comments, and their notation is the same as in Java, i.e.:
-
A block comment starts with the characters
/*
and ends with the characters*/
. Anything between these characters is ignored when interpreting the code. These comments cannot be nested, but you can have linear comments inside them. -
A line comment starts with the characters
//
and is valid until the end of the given line in the script. Anything after these characters up to the end of the current line is ignored when interpreting the code.