Coding With JavaScript For Dummies Everything To Know About JavaScript (2020) - 40153
Coding With JavaScript For Dummies Everything To Know About JavaScript (2020) - 40153
with JavaScript
For Dummies
Everything you need to know about Javascript programming
1st edition
2020
By Claudia Alves
"Programming isn't about what you know; it's
about what you can figure out.” - Chris Pine
.
Memlnc.com
INTRODUCTION
JAVASCRIPT IS EVERYWHERE
JAVASCRIPT ON THE WEB
JAVASCRIPT IN THE BACKEND
JAVASCRIPT AS LANGUAGE FOR DEVICE APPS
JAVASCRIPT AS A LANGUAGE FOR DESKTOP APPLICATIONS
JAVASCRIPT ON THE WEB
WEBSITES
SINGLE PAGE APPLICATIONS
LIBRARIES, FRAMEWORKS AND DEVELOPMENT "VANILLA JAVASCRIPT"
FOR THE WEB
HTML5 APIS
WEB COMPONENTS
JAVASCRIPT AS THE FIRST LANGUAGE
EASY TO USE
WIDE APPLICATION AREAS
IT IS AN OPEN AND STANDARD LANGUAGE FOR THE WEB
MULTIPLE PROFESSIONS START WITH JAVASCRIPT
FRONTEND DEVELOPER:
BACKEND DEVELOPER
FULLSTACK DEVELOPER
HOW TO LEARN JAVASCRIPT
LEARN JAVASCRIPT AND NOT A DERIVATIVE
KNOWLEDGE OF THE WEB PLATFORM
DIFFERENCES BETWEEN JAVA AND JAVASCRIPT
OPEN LANGUAGE / PROPRIETARY LANGUAGE
BEFORE STARTING
USES OF JAVASCRIPT
WHAT DO YOU NEED TO WORK WITH JAVASCRIPT
RECOMMENDED PRIOR KNOWLEDGE
CHAPTER I
JAVASCRIPT LANGUAGE VERSIONS
THE EVOLUTION OF JAVASCRIPT
ECMASCRIPT STANDARD
HTML 5 APIS
LANGUAGE VERSIONS
CONCLUSION TO JAVASCRIPT VERSIONS AND COMPATIBILITY
CHAPTER II
OPEN A CHILD WINDOW
A WELCOME MESSAGE
CURRENT DATE
BACK BUTTON
JAVASCRIPT LANGUAGE
JAVASCRIPT IS WRITTEN TO THE HTML DOCUMENT
THE PLACEMENT OF THE SCRIPTS DOES MATTER
WAYS TO WRITE JAVASCRIPT SCRIPTS
DIRECT EXECUTION OF JAVASCRIPT CODE
RUNNING JAVASCRIPT IN RESPONSE TO AN EVENT
HIDE JAVASCRIPT SCRIPTS IN OLD BROWSERS
HIDE JAVASCRIPT CODE WITH HTML COMMENTS
SHOW A MESSAGE FOR OLD BROWSERS WITH <NOSCRIPT>
MORE ABOUT SCRIPTING
INTERESTING METHODS OF PLACING JAVASCRIPT SCRIPTS
INDICATE THE LANGUAGE WE ARE USING
INCLUDE EXTERNAL JAVASCRIPT FILES
THE IMPORTANCE OF USING EXTERNAL JAVASCRIPT CODE FILES
CHAPTER III
JAVASCRIPT SYNTAX
COMMENTS IN THE CODE
UPPER CASE AND LOWER CASE
SEPARATION OF INSTRUCTIONS
VARIABLES IN JAVASCRIPT
VARIABLE CONCEPT
RULES FOR VARIABLE NAMING IN JAVASCRIPT
VARIABLE NAMES IN JAVASCRIPT ARE CASE SENSITIVE
DECLARATION OF VARIABLES IN JAVASCRIPT
VARIABLE DECLARATION WITH VAR
DECLARATION OF JAVASCRIPT VARIABLES WITH LET AND CONST
SCOPE OF VARIABLES IN JAVASCRIPT
VARIABLE SCOPE CONCEPT
GLOBAL VARIABLES
LOCAL VARIABLES
DIFFERENCES BETWEEN DECLARING VARIABLES WITH VAR, OR NOT
DECLARING THEM
VARIABLE DECLARATION WITH LET
WHAT CAN WE SAVE IN VARIABLES
DATA TYPES IN JAVASCRIPT
NUMERIC DATA TYPE
BOOLEAN TYPE
DATA TYPE CHARACTER STRING
ESCAPE CHARACTERS IN TEXT STRINGS
CHAPTER IV
JAVASCRIPT OPERATORS
EXAMPLES OF USING OPERATORS
ARITHMETIC OPERATORS
ASSIGNMENT OPERATORS
EXAMPLES
CHAIN OPERATORS
LOGICAL OPERATORS
CONDITIONAL OPERATORS
BIT-LEVEL OPERATORS
OPERATORS PRECEDENCE
JAVASCRIPT TYPEOF OPERATOR FOR TYPE CONTROL
RECOMMENDATIONS WITH TYPEOF
JAVASCRIPT CONTROL STRUCTURES
DECISION MAKING
IF STRUCTURE IN JAVASCRIPT
CONDITIONAL EXPRESSIONS
NESTED IF STATEMENTS
IF OPERATOR
JAVASCRIPT SWITCH STRUCTURE
FOR LOOP IN JAVASCRIPT
SAMPLE FOR-LOOP EXERCISE
WHILE AND DO WHILE LOOPS
WHILE LOOP
DO ... WHILE LOOP
EXAMPLE OF THE USE OF WHILE LOOPS
BREAK AND CONTINUE
BREAK
CONTINUE
ADDITIONAL EXAMPLE OF THE BREAK STATEMENT
NESTED LOOPS IN JAVASCRIPT
JAVASCRIPT FUNCTIONS
WHAT IS A FUNCTION
HOW TO WRITE A FUNCTION
HOW TO CALL A FUNCTION
WHERE DO WE PUT THE JAVASCRIPT FUNCTIONS
FUNCTION PARAMETERS
PARAMETERS
MULTIPLE PARAMETERS
PARAMETERS ARE PASSED BY VALUE
RETURN VALUES IN JAVASCRIPT FUNCTIONS
RETURNING VALUES IN FUNCTIONS
MULTIPLE RETURN
SCOPE OF VARIABLES IN FUNCTIONS
JAVASCRIPT FUNCTION LIBRARY
EVAL FUNCTION
PARSEINT FUNCTION
ARRAYS IN JAVASCRIPT
CREATION OF JAVASCRIPT ARRAYS
DATA TYPES IN ARRAYS
ARRAY DECLARATION AND SUMMARY INITIALIZATION
ARRAY LENGTH
MULTIDIMENSIONAL ARRAYS IN JAVASCRIPT
ARRAY INITIALIZATION
GENERAL INTRODUCTION TO OBJECTS IN JAVASCRIPT
WHAT IS AN OBJECT
HOW TO ACCESS OBJECT PROPERTIES AND METHODS
HOW TO CREATE OBJECTS
CREATE AND INSTANTIATE OBJECTS FROM FUNCTIONS
• OBJECT.FREEZE
FREEZE OBJECTS
FREEZE MATRICES
DEEP FREEZING
UNDEFINED IN JAVASCRIPT
NULL IN JAVASCRIPT
WORD PROCESSING
SMUGGLING OF CHARACTERS
LONG TEXT STRINGS
ACCESS THE CHARACTERS
COMPARE TEXT STRINGS
• STRING.FROMCHARCODE
HANDLE VALUES LARGER THAN THE MAXIMUM
• STRING.FROMCODEPOINT
STRING.RAW ()
Introduction
Getting started is easy, but there is a long way to go if you want to express all
the possibilities of language. Javascript is one of the standard languages of
the web and therefore ideal for many of the professionals who plan to
dedicate themselves to this medium. But even if you don't want to develop
specifically for the web, Javascript is an excellent alternative for making
mobile applications or desktop applications.
Perhaps not all developers need to reach an advanced level of Javascript, but
a basic knowledge will certainly be of great help at many points in their
professional careers. In any case, once the learning is completed, you will
have endless opportunities at your fingertips.
We'll start by looking at the state of Javascript today (2017) and the reasons
why Javascript is worth using in general. Then we will take care of
explaining how you can learn Javascript and get to whatever level we set
ourselves.
Javascript is everywhere
Javascript has become an ideal language to learn, since it has many and
varied applications, in addition to providing simplicity for people who are
starting out. To run it we only need a browser, although at the moment
Javascript has surpassed the scope of web clients, to be located almost
anywhere.
Javascript on the web
The environment where Javascript first appeared was the web. Its execution
focused on the scope of a web page and allowed developers to provide
interactivity, manipulate the document or the browser window, perform
calculations, etc. Netscape Navigator, a browser that disappeared today, has
the honor of having introduced Javascript as a language, although today it is
supported by all web clients with which a user can navigate.
Using Javascript for the web, in the browser environment, is also known as
client-side programming. Today it is still the most common environment for
Javascript execution, but it really is just one more among its possibilities.
Javascript in the backend
Certain developers came up with the idea that they could extract the
Javascript runtime, which until then had only been available within the scope
of the browser, to use it for any other purpose outside the web client. This is
how NodeJS was born, which is nothing more than Javascript outside the
browser.
With NodeJS we can program with Javascript applications that run directly
on the operating system and that are capable of solving any type of problem.
With this technology, Javascript became a general-purpose programming
language.
For years it has also been possible to use Javascript as a language for creating
applications for devices (mobile apps, tablets, TVs ...). The applications
developed are installed from the corresponding app stores of the main mobile
systems and the user in principle does not perceive any difference from these
with respect to the applications developed with the native languages. But, due
to the fact that they are programmed with Javascript and HTML5, they open
a new field of action for people experienced in developing for the web and
dispense with the learning of native languages for each mobile platform.
When we refer to websites here we mean sites where the most important part
is content, be they blogs, news pages, and even e-commerce.
In recent years, the web has become popular as a platform for business
applications. Applications called "management", which were previously run
with desktop programs, today have web fronts that allow us to use them from
the cloud, that is, from any browser connected to the Internet and without the
need to install software on the machine. In this type of application, it is
common to carry a large part of the processing load from the server side to
the client. In this new paradigm, the browser is responsible for doing many
more things than in traditional websites, such as creating the HTML code to
visualize the data or navigating between screens or application routes.
In Single Page Applications, also known as SPA, it is normal for the server to
deliver only the raw business data and for the browser to do all the work of
presenting that data in a suitable format (HTML is produced in the browser to
represent that data). But what most characterizes a SPA is that navigation is
always done within the same page and Javascript is in charge of presenting
one or another screen to the user without having to reload the entire page.
The two main factors that characterize SPAs, 1) the fact of bringing raw data
from the server (lighter) and 2) all navigation is done within the same
document, they produce web applications with a very fast response,
providing an experience of use close to that of a desktop application.
Libraries, frameworks and development "Vanilla
Javascript" for the web
The creation of a SPA is a much more advanced task than the development of
a website and in order to carry out this work it is important that the
development team is based on a Javascript framework, such as Angular,
React, VueJS, Ember or Polymer. .
Note: React and Polymer are considered more libraries, but with a series of
add-ons, which they themselves provide in many cases, they offer as many
features as those found in a framework. In case someone does not know yet, a
library is a set of functions, or classes and objects, that allows us to perform a
range of common tasks for the development of certain application needs. A
framework is mainly distinguished from a library because, in addition to
providing code to solve common problems, it offers an architecture that
developers must follow to produce applications and ensure better code
quality and greater ease of maintenance. In other words, the framework, in
addition to offering diverse utilities, marks a style and workflow when
developing applications.
There are more specialized libraries to solve each and every one of the things
that a general library like jQuery offers and that take up much less download
weight and processing time for browsers.
But beyond libraries and frameworks we must know that today, in addition to
the language itself, there are many other Javascript-based technologies in
browsers to solve a wide range of needs.
HTML5 APIs
HTML5 offers APIs for working with elements such as the camera,
geolocation, storage, bitmap or vector drawing, audio, video, etc. Everything
HTML5 offers is available in all browsers and is part of the Javascript
developer's toolkit, without using any library or framework.
Web Components
The next development revolution for the Internet, which has not yet exploited
in the middle of 2017, is called Web Components. It is based on a new API
(with several specifications together) aimed at creating components.
Components are like new HTML tags that any developer can create to solve
common or particular application problems.
Note: In the coming months, all browsers are expected to support Web
Components V1 and we can use it without any restrictions. Meanwhile there
is a Polyfill that allows to extend the support to Web Components to
browsers that do not yet have it. Polyfills are literally "gap fillers", which
make up for the deficiencies of old browsers with respect to the standards. In
the HTML5 APIs they have already begun to be used intensively to allow the
use of new features of the web languages in old or slightly updated clients.
Javascript as the first language
Note: Specialization is also present in these professions. It is truly amazing to see how profiles
develop in the world of the web and how new specialized professions are generated year after
year. What we used to call frontend, simply, today we can subdivide it into dozens of specific
profiles or professions such as "frontend engineer", "frontend web designer", "CSS architect",
"mobile frontend developer", "frontend devops" ...
How to learn Javascript
Learning Javascript at an advanced level takes months of study, but getting
started is easy and in no time you will be able to do amazing things with little
effort. In the Javascript manual you will be able to know the language, but to
start we want to give you a couple of tips.
Learn Javascript and not a derivative
Our first tip if you are just starting out is to learn Javascript and not a library
or framework. In the end, all the projects on the web use Javascript and
everything you can do with a library or framework can also be done with
Javascript, so the correct thing to do is start by mastering the language, and
then set new objectives in the medium or long term.
What should accompany the knowledge and use of Javascript are your skills
in everything that the browser (the web platform) offers you by default:
HTML5 and Web Components. Everything you do based on Javascript
"Vanilla", HTML5 and Web Components you have the certainty that it can
be used in any project where you can get to work, regardless of the library or
framework that is being used in each case.
Knowledge of the web platform
Our second advice is that, if you are going to work in this medium, you must
bear in mind each of the peculiarities of the web platform. There is a lot of
general knowledge that you need to acquire that will give you a foundation
on which to build your skills in the world of web development.
Knowledge of the medium: You must know what the Internet is, the Web,
the HTTP protocol, the domain name system and of course the fundamental
languages to specify the content and form: HTML and CSS.
Knowledge of tools: The professional must also know a large group of tools
for day-to-day work, from the command line terminal and basic
administration of servers, to the automation of tasks, through the version
control tools ( Git preference) and optimization.
Differences between Java and Javascript
Javascript was really called that because Netscape (the browser that launched
Javascript), which was allied with the creators of Java at the time (Sun
Microsystems), wanted to take advantage of the brand image and popularity
of Java, as a maneuver for the expansion of its new language. All in all, a
product was created that had certain similarities, such as language or name
syntax. He was made to understand that he was a little brother and
specifically oriented to do things on web pages, but also made many people
fall into the error of thinking that they are the same.
We want to make it clear that Javascript has nothing to do with Java, except
for the collaboration agreement of the creators of both languages, as it has
been read. They have always been totally different products that bear no more
relation to each other than the identical syntax, although in truth, the syntax
of both is inherited from another popular language called C.
Differences between Java and Javascript
We want to point out that currently the Javascript web approach does not
have to be considered unique. As we have said, it is possible to make almost
any type of program using Javascript and in recent years it has been
occupying more and more plots. Also, as new versions of the Javascript
standard have been introduced, it has become more robust and suitable also
for large applications.
Before starting
Without going any further, DesarrolloWeb.com uses Javascript for the top
menu, which shows different links within each main option. We are changing
the page from time to time, but in the current design of this website, elements
such as the "Login" box also have their dynamism with Javascript.
Currently almost all the slightly advanced pages use Javascript, as it has
become one of the insignia of what is called Web 2.0 and the rich user
experience. For example, popular websites like Facebook, Twitter or
Youtube use Javascript in abundance. To be more specific, when we click on
a link on the social network to comment on something, a small form is
displayed on the page that appears as if by magic and is then sent without
leaving the page itself. Also when we vote for a video on YouTube or when
the characters that we have written in the Twitter mini-posts are counted,
Javascript is used to perform small functionalities that cannot be done with
HTML alone. You can actually see Javascript examples inside any slightly
complex page. Some that we will have seen countless times are dynamic
calendars to select dates, calculators or currency converters, rich text editors,
dynamic browsers, etc.
The truth is that it does not take a lot of knowledge base to start programming
in Javascript. Most likely, if you read these lines you already know
everything you need to work, since you will have already had some
relationship with the development of websites and you will have detected that
to do certain things it is good to know a little Javascript.
Already to warn you from the outset, in this Javascript Manual we are going
to work with fully extended versions of the language in all browsers, so
anything we explain can be applied without any problem.
Javascript language versions
The evolution of Javascript
On the one hand, the language itself has been incorporating operators, control
structures, syntax rules to do repetitive things with less code. We owe these
improvements in the language to the ECMASCript standard, which we will
talk about immediately.
On the other hand, browsers have been incorporating new instructions, to be
able to manipulate modern elements of the page, such as divisions, CSS
styles and systems such as local storage, full-screen work, geolocation and a
long etc. All these improvements are defined under the standards of HTML 5
and its Javascript APIs.
In any case, what should be clear is that Javascript has been improving its
features as a language, while browsers have been offering greater support to
advanced functionalities for the control of page elements. That is why in
Javascript we generally have to be careful with the browser market and
compatibility with the functionalities that we want to use.
ECMASCript Standard
This is half true, since there are systems that allow the code to be translated
from one version to another of the standard, although at the moment we do
not want to get into these details. If you are interested, we recommend
reading the Webpack Manual, which is one of the many tools that you can
use to carry out this task.
HTML 5 APIs
It happens a bit the same as with the language versions. If the browser is very
old it may not have support for some APIs, so we have to be cautious. In
practice more than anything with Internet Explorer and some old mobile
browser.
In this first part of the manual we are not going to cover the HTML 5 APIs or
access to the browser resources. This area is the subject of study in the
second part, dedicated to Client-side Javascript Development.
Language versions
In the first part of this manual the objective is to learn Javascript well, so we
will limit ourselves to the study of language in particular. In this sense we
will use ES5, which is the version of the language that works in all current
browsers.
Really, any moderately modern browser will now have all the Javascript
functionalities that we are going to need and above all, those that we can use
in our first steps with the language. However, it may be useful to know the
first versions of Javascript that we discussed in this article, as a curiosity.
Javascript 1: It was born with Netscape 2.0 and it supported a large number
of instructions and functions, almost all that exist now have already been
introduced in the first standard.
Javascript 1.1: It is the Javascript version that was designed with the arrival
of 3.0 browsers. It implemented little more than its previous version, such as
dynamically processing images and creating arrays.
Javascript 1.2: The version of browsers 4.0. This has the disadvantage that it
is a little different on Microsoft and Netscape platforms, since both browsers
grew differently and were in full fight for the market.
Javascript 1.3: Version implemented by 5.0 browsers. In this version, some
differences and rough edges between the two browsers have been filed.
Javascript 1.5: Current version, at the time of this writing, implemented by
Netscape 6.
For its part, Microsoft has also evolved to present its 5.5 version of JScript
(that's what they call the javascript used by Microsoft's browsers).
In 2009 the version of ECMAScript 5 was published. This is the version that
we are going to deal with mainly in the manual, which works in all browsers
on the market.
In 2015 the sixth version of ECMAScript is launched, with a very significant
number of new features. This version is fully usable, except in Internet
Explorer. Its improvements are so important that all professional developers
use them and, if necessary, the code is translated to support older browsers.
This version is explained in the ES6 Manual.
There is currently a commitment to release one version of the ECMAScript
standard per year. Therefore, there are various standards with small
incremental changes, which have been incorporated at different rates between
browsers.
Conclusion to Javascript versions and compatibility
It is obvious that, after writing these lines, many other versions of Javascript
will be presented or will have been presented, because, as browsers are
improved and HTML versions are released, new needs arise for programming
dynamic elements. However, everything we are going to learn in this manual,
even other much more advanced uses, is already implemented in any
Javascript that exists today.
Chapter II
Quick effects with Javascript
Before diving into the matter, we can see a series of quick effects that can be
programmed with Javascript, which can give us a clearer idea of the
capabilities and power of the language. Below we will see several examples,
which we have highlighted for this introduction in the Javascript Manual, for
having a minimum of complexity and although they are very basic, they will
come in handy to have a more accurate idea of what Javascript is when it
comes to going through the following chapters.
Open a child window
First let's see that with a javascript line we can do quite attractive things. For
example we can see how to open a secondary window without menu bars that
shows the Google search engine. The code would be the following.
<script>
window.open ("http://www.google.com", "", "width = 550, height = 420,
menubar = no")
</script>
A welcome message
We may display a pop-up text box upon completion of loading the cover of
our website, which might welcome visitors.
<script>
window.alert ("Welcome to my website. Thanks ...")
</script>
Current date
Now let's look at a simple script to show today's date. Sometimes it is very
interesting to show it on the websites to give an effect that the page is "up to
date", that is, it is updated.
These lines should be inserted inside the body of the page where we want the
last update date to appear. We can see the example running here.
Another quick example can be seen below. It is a button to go back, like the
one we have in the toolbar of the browser. Now we will see a line of code
that mixes HTML and Javascript to create this button that shows the previous
page in the history, if any.
The button would be similar to the following, a normal button with the
default appearance that the browser and operating system you use give the
buttons. Below is an image of what the button would look like on my system.
The ease with which some interesting actions can be carried out has been
verified. As you can imagine, there would be many other simple Javascript
samples that we reserve for later chapters.
Javascript language
Let's see how to insert the Javascript code into an HTML document. In this
article we will explain some important rules and the most basic ways of
executing Javascript in the context of a page.
In this part of the manual on Javascript we are going to know the most basic
way of working with the language. In this article we will give the first
information on how to include scripts, mixing the Javascript code itself with
the HTML.
Then we will also see how code should be placed so that our website is
compatible with all browsers, even those that do not support Javascript. Many
ideas of how Javascript works have already been described in previous
chapters, but with the aim of leaving nothing in the pipeline, we will try to
grab from here all the important data of this language.
Javascript is written to the HTML document
The most important and basic thing that we can highlight at this moment is
that Javascript programming is done within the HTML document itself. That
is, the Javascript code, in most cases, is mixed with the HTML code itself to
generate the page.
This means that we must learn to mix the two programming languages and
we will quickly see that, so that these two languages can coexist without
problems between them, delimiters must be included that separate the HTML
tags from the Javascript instructions. These delimiters are the <SCRIPT> and
</SCRIPT> tags. All the Javascript code that we put on the page has to be
inserted between these two tags.
The placement of the scripts does matter
We can enter several scripts on the same page, each one that could be entered
within different <SCRIPT> tags. The placement of these scripts is not
irrelevant. In the beginning, with what we know so far and the scripts that we
have carried out for testing, it gives us a little the same where to place them,
but in certain cases this placement will be very important. In each case, and
when the time comes, it will be reported accordingly.
Javascript can also be written within certain page attributes, such as the
onclick attribute. These attributes are related to user actions and are called
event handlers.
Below we are going to take a closer look at these two ways of writing scripts,
which have as their main difference the moment in which the sentences are
executed.
Ways to write Javascript scripts
Until now in the Javascript Manual we have already had the opportunity to
try some simple scripts, however, we still have to learn one of the bases to be
able to work with the language and that is to learn the two ways of executing
Javascript code. There are two fundamental ways to run scripts on the page.
The first of these ways is direct script execution, the second is execution in
response to user action.
We will now explain each of these forms of execution available, but for those
who want it, we also recommend watching the video on Ways to include and
execute scripts.
Direct execution of Javascript code
It is the most basic method of running scripts. In this case, the instructions are
included inside the <SCRIPT> tag, as we have previously commented. When
the browser reads the page and finds a script, it interprets the lines of code
and executes them one after the other. We call this way direct execution
because when the page is read the scripts are executed directly.
<script>
var people = 4;
var amountEntrance = 9.50;
alert ('You need' + people * ticket amount + 'euros for everyone to enter the cinema');
</script>
<p> When the user clicks accept in the dialog box, the browser will display the full page. </p>
</body>
</html>
That Javascript code will execute as the page opens. When the browser, when
processing the page, finds this code, it will stop reading the page to execute
the Javascript script. As a result it will show in a dialog box "You need 38
euros for everyone to enter the cinema". When the user clicks the "accept"
button, they will continue reading the rest of the page and displaying the
content of the entire page in the browser window. Of course we will see
many other examples throughout the manual.
This method will be the one we use preferably in most of the examples in this
part of the Javascript Manual. In the second part of the Javascript Manual we
can learn many things and among them we will see in detail the second way
of executing scripts that we are going to relate below.
Running javascript in response to an event
It is the other way to run scripts, but before we see it we must talk about
events. Events are actions performed by the user. Programs like Javascript are
prepared to catch certain actions performed, in this case on the page, and
perform actions in response. In this way, interactive programs can be carried
out, since we control the movements of the user and respond to them. There
are many different types of events, for example, the push of a button, the
movement of the mouse, or the selection of text on the page.
We therefore check that Javascript code can be inserted into certain attributes
of HTML tags. However, it is not the only possible method. We can also
select page elements directly with Javascript and associate functions that will
be executed in response to events. Although it is a bit early so that you can
understand this whole process in detail, we are going to see a simple
example.
This time you have the code for an entire page. In it you can find the
Javascript code embedded inside the body of the page. Unlike the previous
code, when the browser reads the page it doesn't execute anything. It simply
memorizes the script and associates the function with the element that has
been defined. Specifically, we have defined an event of type "mouseenter" on
an element of the page that has an identifier "my element". This means that
each time the user places the mouse pointer over the element "my element", it
will execute the function "announcePasses".
Thus, not all browsers that can be used by users who visit our page
understand Javascript. In cases where the scripts are not interpreted, browsers
assume that their code is text from the page itself and as a consequence,
present the scripts in the body of the document, as if it were normal text. To
prevent script text from being written to the page when browsers don't
understand it, you have to hide them with HTML comments (<! - HTML
comment ->). In addition, in this article we will also see how to display a
message that is seen only in browsers that do not support Javascript.
Updated: At the present time we can say that almost 100% of the available
browsers support Javascript, or at least they recognize script tags, so, even if
it is disabled, they will not show the text of our Javascript programs.
Therefore, currently it is no longer essential to perform the operation of
hiding the code of the page scripts for old browsers. However, if we want to
make a completely correct page, it will be useful to learn how to hide a script
so that it is never displayed as text on the page.
Hide Javascript code with HTML comments
Let's look at a code example where HTML comments have been used to hide
Javascript, or better said, the code the Javascript scripts.
<SCRIPT>
<! -
Javascript code
// ->
</SCRIPT>
<SCRIPT>
javascript code
</SCRIPT>
<NOSCRIPT>
This browser does not understand the scripts that are running, you must update your browser
version to a newer one.
<br> <br>
<a href=http://netscape.com> Netscape </a>. <br>
<a href=http://microsoft.com> Microsoft </a>.
</NOSCRIPT>
More about scripting
In this article we will show one of the attributes that can be indicated in the
SCRIPT label, which indicates the language that we are going to use. In
addition, we will show another very useful way of associating Javascript code
on the page, by means of an external file. This point is fundamental and we
will have to pay special attention, since it is without a doubt the way of
working that is used most often.
Interesting methods of placing Javascript scripts
The <SCRIPT> tag has an attribute that is used to indicate the language that
we are using, as well as its version. For example, we can indicate that we are
programming in Javascript 1.2 or Visual Basic Script, which is another
language for programming scripts in the client browser that is only
compatible with Internet Explorer.
Within the <SCRIPT> tags, any text can be written and will be ignored by the
browser, however, browsers that do not understand the SRC attribute will
have this text by instructions. It is very rare for this to happen in the browser
landscape. So it is not really advisable to put any Javascript code inside a
script block that we are using to include an external file.
The file we include (in this case "external_file.js") must contain only
Javascript statements. We must not include HTML code of any kind, not
even the </SCRIPT> and </SCRIPT> tags.
The Importance of Using External Javascript Code
Files
From the point of view of code separation, each file should have only one
language. HTML documents are placed in ".html" files, CSS documents in
".css" files and Javascript also separated in their ".js" files.
The external file allows the browser to cache it, so when the page is revisited,
the code is already in the browser and you don't have to redownload it. This
point is especially important when we have many pages that load the same
Javascript code, since the browser will actually download the ".js" file once
and the other times will consume it from the cache, saving transfer and
increasing loading speed.
When you have more advanced notions about Javascript you will see that in
the script tag you can use attributes like "defer" or "async". Both attributes
cause the browser not to stop executing an external script that is in the middle
of the HTML content, but to continue analyzing the page and rendering its
content while the file is downloaded. Therefore, both attributes optimize the
page load and improve the speed with which the browser presents the content
to the user.
Note: When you use "defer" the file load is done in parallel with parsing the
HTML and other external files, but the execution is deferred until the browser
has finished parsing and rendering the page. When you use "async" you mean
that the script is downloaded at the same time that the page is analyzed and
that, once downloaded, it is executed, although it did not take long to analyze
the page completely.
An example of load and execution of the deferred Javascript we get it like
this.
Given these other interesting uses that exist in Javascript and that we must
know in order to take advantage of the possibilities of technology, we must
have learned everything essential to start working with Javascript in the
context of a web page.
Chapter III
Javascript syntax
We finally start to see Javascript source code! We hope that all the previous
information from the Javascript Manual has been assimilated, in which we
have basically learned various ways to include scripts on web pages. So far
everything we have seen in this manual may have seemed very theoretical,
but from now on we hope you find it more enjoyable to start seeing more
practical and directly related to programming.
The Javascript language has a syntax very similar to Java because it is based
on it. It is also very similar to that of the C language, so if the reader knows
any of these two languages it will be easy to handle with the code. Anyway,
in the following chapters we are going to describe all the syntax carefully, so
newbies will have no problem with it.
Comments in the code
A comment is a part of code that is not interpreted by the browser and whose
utility lies in making it easier for the programmer to read. The programmer,
as he develops the script, leaves individual phrases or words, called
comments, which help him or anyone else to read the script more easily when
modifying or debugging it.
Some Javascript comments have been seen previously, but now we are going
to count them again. There are two types of comments in the language. One
of them, the double bar, is used to comment on a line of code. The other
comment can be used to comment on several lines and is indicated with the
signs / * to start the comment and * / to end it. Let's see some examples.
<SCRIPT>
// This is a one line comment
/ * This comment can be extended
along several lines.
The ones you want * /
</SCRIPT>
Upper case and lower case
For example, the alert () function is not the same as the Alert () function. The
first displays text in a dialog box, and the second (with the first capital A)
simply does not exist, unless we define it ourselves. As you can see, for the
function to recognize Javascript, you have to write all lowercase. We will see
another clear example when we deal with variables, since the names we give
to the variables are also case sensitive.
For this reason Javascript statements do not need to end with a semicolon
unless we put two instructions on the same line.
It is not a bad idea, anyway, to get used to using the semicolon after each
instruction because other languages such as Java or C force them to be used
and we will be getting used to making a syntax more similar to the usual one
in advanced programming environments.
Variables in Javascript
This is the first of the articles that we are going to dedicate to variables in
Javascript within the Javascript Manual. We will see, if we do not already
know, that variables are one of the fundamental elements when making
programs, in Javascript as well as in most of the existing programming
languages.
So let's start by getting to know the concept of a variable and we'll learn how
to declare them in Javascript, along with detailed explanations of their use in
the language.
Variable concept
For example, if our program performs sums, it will be very normal for us to
store in variables the different addends that participate in the operation and
the result of the sum. The effect would be something like this.
adding1 = 23
adding2 = 33
sum = adding1 + adding2
In this example we have three variables, adding1, adding2 and sum, where
we save the result. We see that their use for us is as if we had a section where
to save a data and that they can be accessed just by putting their name.
Rules for variable naming in Javascript
Variable names must be constructed with alphanumeric characters (numbers
and letters), the underscore or underscore (_), and the dollar character $.
Apart from this, there are a number of additional rules for constructing names
for variables. The most important is that they cannot start with a numeric
character. We cannot use rare characters such as the + sign, a space, or a -
sign. Supported names for variables could be:
Age
country of birth
_Name
$ element
Other $ _Names
We must also avoid using reserved names as variables, for example we will
not be able to call our variable words like return or for, which we will see that
they are used for structures of the language itself. Let's now look at some
variable names that you are not allowed to use:
12 months
your name
return
for
more or less
pe% pe
Variable names in Javascript are case sensitive
Remember that Javascript is a case-sensitive language, so variables are also
affected by that distinction. Therefore, the variable named "myname" is not
the same as the variable "myName". "Age" is not the same as "age".
Keep this detail in mind, as it is a common source of code problems that are
sometimes difficult to detect. This is because sometimes you think you are
using a variable, which should have a certain data, but if you make a mistake
when writing it and put upper or lower case where it should not, then it will
be another different variable, which will not have the expected data. Since
Javascript does not force you to declare variables, the program will run
without producing an error, however, the execution will not produce the
desired effects.
Declaration of variables in Javascript
Javascript skips many rules for being a somewhat free language when
programming and one of the cases in which it gives a little freedom is when
declaring the variables, since we are not obliged to do so, contrary to what
happens in other programming languages like Java, C, C # and many others.
Variable declaration with var
Javascript has the word "var" that we will use when we want to declare one
or more variables. Not surprisingly, that word is used to define the variable
before using it.
var operand1
var operand2
You can also assign a value to the variable when it is being declared
var operand1 = 23
var operand2 = 33
It is also allowed to declare several variables on the same line, provided they
are separated by commas.
Let declaration: This new way of declaring variables affects their scope, since
they are local to the block where they are being declared.
Perhaps at this point in the Javascript manual it is not necessary to delve too
deeply into these declaration models and for those who are learning we
recommend focusing on the use of declarations with "var". However, if you
want to have more information about these new types of variables, we
explain them in the article Let and const: variables in ECMAScript 2015. If
you want to see other news about the Javascript standard that came in 2015,
we recommend reading the ES6 Manual.
Scope of variables in Javascript
The scope of variables is one of the most important concepts that we must
know when working with variables, not only in Javascript, but in most
programming languages.
In the previous article we already started to explain what variables are and
how to declare them. In this article of the Javascript Manual we intend to
explain in detail what this field of variables is and offer examples so that it
can be well understood.
At the beginning of the article we will refer to the scope of the variables
declared with "var". However there is a newer way to declare variables, with
"let", that directly affects your scope. At the end we will also offer some
notes and references to understand it.
Variable scope concept
Variables scope is called the place where they are available. In general, when
we declare a variable we make it available in the place where it has been
declared, this occurs in all programming languages and since Javascript is
defined within a web page, the variables that we declare on the page will be
accessible within she.
In Javascript we will not be able to access variables that have been defined on
another page. Therefore, the page where it is defined is the most common
scope of a variable and we will call this type of global variables the page. We
will also see that variables can be made with different scopes from the global
one, that is, variables that we will declare and will be valid in more limited
places.
Global variables
As we have said, global variables are those that are declared in the widest
possible scope, which in Javascript is a web page. To declare a global
variable to the page we will simply do it in a script, with the word var.
<SCRIPT>
global variable var
</SCRIPT>
Global variables are accessible from anywhere on the page, that is, from the
script where they have been declared and all the other scripts on the page,
including event handlers, such as onclick, which we already saw could be
included within certain HTML tags.
Local variables
We can also declare variables in narrower places, such as a function. We will
call these variables local. When local variables are declared, we can only
access them within the place where they have been declared, that is, if we had
declared them in a function, we can only access them when we are in that
function.
Variables can be local to a function, but can also be local to other scopes,
such as a loop. In general, any area bounded by keys is a local area.
<SCRIPT>
function myFunction () {
var variableLocal
}
</SCRIPT>
<SCRIPT>
var number = 2
function myFunction () {
var number = 19
document.write (number) // print 19
}
document.write (number) // print 2
</SCRIPT>
Note: To understand this code you will surely find it useful to consult the
chapter on creating functions in Javascript.
A tip for beginners might be to not declare variables with the same names, so
there is never confusion about which variable is valid at any given time.
Differences between declaring variables with var, or
not declaring them
As we have said, in Javascript we are free to declare or not the variables with
the word var, but the effects that we will achieve in each case will be
different. Specifically, when we use var we are making the varible that we are
declaring local to the scope where it is declared. On the other hand, if we do
not use the word var to declare a variable, it will be global to the entire page,
whatever the scope in which it has been declared.
<SCRIPT>
var number = 2
function myFunction () {
number = 19
document.write (number) // print 19
}
document.write (number) // print 2
// call the function
myFunction ()
document.write (number) // print 19
</SCRIPT>
In this example, we have a global variable to the page called number, which
contains a 2. We also have a function that uses the variable number without
having declared it with var, so the variable number of the function will be the
same global variable number declared out of function. In a situation like this,
executing the function will overwrite the variable number and the data that
was there before executing the function will be lost.
Variable declaration with let
Since ECMAScript 2015 there is the let statement. The syntax is the same as
var when declaring variables, but in the case of let the declaration affects the
block.
Block means any space delimited by keys, such as the statements inside the
keys of a for loop.
If that variable "i" had been declared in the for loop header using "var", it would exist outside the for
code block.
What can we save in variables
In a variable we can introduce various types of information. For example we
could enter simple text, whole or real numbers, etc. These different kinds of
information are known as data types. Each one has different characteristics
and uses.
Let's see what are the most common data types of Javascript.
Numbers
Chains
The character string type stores a text. Whenever we write a character string we must use quotation
marks (").
Booleans
We also have the boolean type, which stores information that can be valid
whether (true) or not (false).
Finally, it would be relevant to point out here that our variables can contain
more complicated things, such as an object, a function, or empty (null), but
we will see later.
Actually our variables are not forced to save a specific data type and
therefore we do not specify any data type for a variable when we are
declaring it. We can introduce any information in a variable of any type, we
can even change the content of a variable from one type to another without
any problem. We will see this with an example.
var city_name = "Valencia"
revised var = true
city_name = 32
revised = "no"
var adding1 = 23
var adding2 = "33"
var sum = adding1 + adding2
document.write (sum)
This script would show us on the page the text 2333, which does not
correspond to the sum of the two numbers, but to their concatenation, one
after the other.
Data types in Javascript
There is only one numeric data type in this language, unlike in most of the
better-known languages. All the numbers are therefore of the numerical type,
regardless of the precision they have or if they are real or integer numbers.
Integers are non-comma numbers, such as 3 or 339. Real numbers are
fractional numbers, such as 2.69 or 0.25, which can also be written in
scientific notation, for example 2,482e12.
Base 10 is the system that we usually use, the decimal system. Any number,
by default, is understood to be written in base 10.
Base 8, also called the octal system, which uses digits from 0 to 7. To write a
number in octal, just write that number preceded by 0, for example 045.
Base 16 or hexadecimal system, is the numbering system that uses 16 digits,
those between 0 and 9 and the letters from A to F, for the missing digits. To
write a number in hexadecimal we must write it preceded by a zero and an x,
for example 0x3EF.
Boolean type
myBoleana = true
<br>
myBoleana = false
Data type character string
The last type of data is the one used to save a text. Javascript has only one
data type to save text and any number of characters can be entered. A text can
be composed of numbers, letters and any other type of characters and signs.
Texts are written in quotation marks, double or single.
There are a series of special characters that are used to express certain
controls in a text string, such as a line break or a tab. These are the escape
characters and are written with special notation that starts with a backslash (a
forward slash opposite the normal one '') and then the code for the character
to be displayed is placed.
When developing programs in any language, operators are used, which are
used to make the calculations and operations necessary to carry out your
objectives. Even the smallest program imaginable needs operators to do
things, since a program that does not perform operations would only limit
itself to always doing the same.
It is the result of operations that makes a program vary its behavior according
to the data it has to work with and offers us results that are relevant to the
user who uses it. There are simpler or more complex operations, which can
be performed with operands of different types, such as numbers or texts, we
will see in this chapter, and the following, in detail, all these operators
available in Javascript.
Examples of using operators
Before going to list the different types of operators, let's see a couple of
examples of these to help us get a more accurate idea of what they are. In the
first example we are going to perform a sum using the sum operator.
3+5
This is a very basic expression that doesn't make much sense on its own. It
does the sum between the two operands number 3 and 5, but it does not help
much because nothing is done with the result. Usually more than one operator
is combined to create more useful expressions. The following expression is a
combination between two operators, one performs a mathematical operation
and the other is used to save the result.
myVariable = 23 * 5
In the previous example, the operator * is used to perform a multiplication
and the operator = is used to assign the result in a variable, so we save the
value for later use.
They are those used to carry out simple mathematical operations such as
addition, subtraction or multiplication. In javascript they are the following:
Examples
price = 128 // I introduce a 128 in the price variable
units = 10 // another assignment, then we will see assignment operators
invoice = price * units // multiply price by units, I get the invoice value
remainder = invoice% 3 // I get the remainder from dividing the invoice
variable by 3
price ++ // increase the price by one unit (now worth 129)
Assignment operators
They are used to assign values to variables, we have already used the
assignment operator = in previous examples, but there are other operators of
this type, which come from the C language and that many of the readers will
already know.
= Assignment. Assign the right part of the equals to the left part. To the right
the final values are placed and to the left a variable is generally placed where
we want to save the data.
+ = Assignment with sum. Add the right part to the left part and save the
result to the left part.
- = Allocation with subtraction
* = Multiplication allocation
/ = Division assignment
% = The rest is obtained and assigned
Examples
Character strings, or text variables, also have their own operators to perform
typical actions on strings. Although javascript only has one operator for
strings, other actions can be performed with a series of predefined functions
in the language that we will see later.
+ Concatenate two strings, paste the second string after the first one.
Example
string1 = "hello"
string2 = "world"
concatenated string = string1 + string2 // concatenated string is valid
"helloworld"
An important detail that can be seen in this case is that the operator + serves
two different uses, if its operands are numbers it adds them, but if it is strings
it concatenates them. This happens in general with all the operators that are
repeated in the language, javascript is smart enough to understand what type
of operation to perform by checking the types that are involved in it.
myNumber = 23
myString1 = "pepe"
myString2 = "456"
result1 = myNumber + myString1 // result1 is worth "23pepe"
result2 = myNumber + myString2 // result2 is valid "23456"
myString2 + = myNumber // myString2 is now "45623"
As we have seen, also in the case of the operator + =, if we are dealing with
text strings and intermixed numbers, it will treat the two operators as if they
were strings.
Note: As you may have imagined, many typical operations to perform with
strings are missing, for which there are no operators. It is because these
functionalities are obtained through the String class of Javascript, which we
will see later.
Logical operators
These operators are used to perform logical operations, which are those that
result in a true or a false, and are used to make decisions in our scripts.
Instead of working with numbers, to perform this type of operations, Boolean
operands, which we knew earlier, are used, which are true (true) and false
(false). Logical operators relate Boolean operands to result in another
Boolean operand, as we can see in the following example.
if (x == 2 && y! = 3) {
// the variable x is worth 2 and the variable y is different from three
}
In the above conditional expression we are evaluating two checks that relate
to a logical operator. On the one hand x == 2 will return true if the variable x
is 2, and on the other, y! = 3 will return true when the variable y has a value
other than 3. Both checks return one boolean each, which then The logical
operator && is applied to it to check if both checks were fulfilled at the same
time.
Example
myBoleano = true
myBoleano =! myBoleano // miBoleano now worth false
hunger = true
gotFood = true
comoMeal = I am hungry && I have food
Conditional operators
These are very unusual and you may never get to use them. Its use is made to
carry out operations with zeros and ones. All that a computer handles are
zeros and ones, although we
The numbers and letters for our variables actually these values are written
internally in the form of zeros and ones. In some cases we may need to
perform operations treating the variables as zeros and ones and for this we
will use these operands. In this manual it is a bit too big for us to carry out a
discussion about this type of operators, but here you can see these operators
in case you ever need them.
& Y bit
^ Bit Xor
| Or bit
<< >> >>> >>> = >> = << = Various kinds of changes
Operators precedence
The evaluation of a sentence that we have seen in the previous examples is
quite simple and easy to interpret, but when a multitude of different operators
come into play in a sentence, there may be confusion when interpreting it and
elucidating which operators are the ones that they run before others. To set
some guidelines in the evaluation of the sentences and that they are always
executed the same and with common sense, there is the precedence of
operators, which is nothing more than the order in which the operations they
represent will be executed. Initially, all operators are evaluated from left to
right, but there are additional rules, whereby certain operators are evaluated
before others. Many of these rules of precedence are derived from
mathematics and are common to other languages, we can see them below.
() []. Parentheses, square brackets, and the dot operator for objects
! - ++ - negation, negative and increments
* /% Multiplication division and module
+ - Add and subtract
<< >> >>> Bit level changes
<<=>> = Conditional operators
==! = Conditional operators of equality and inequality
& ^ | Bit-level logic
&& || Boolean logicians
= + = - = * = / =% = << = >> = >>> = & = ^ =! = Assignment
12 * 3 + 4 - 8/2% 3
In this case, the * / and% operators are executed first, from left to right, with
which these operations would be performed. First the multiplication and then
the division because it is more to the left of the module.
36 + 4 - 4% 3
Now the module.
36 + 4 - 1
Finally the additions and subtractions from left to right.
40 - 1
Which gives us the following value.
39
In any case, it is important to realize that the use of parentheses can save us a
lot of headaches and, above all, the need to know the operator precedence
table by heart. When we see unclear the order in which the sentences will be
executed, we can use them and thus force that the piece of expression found
inside the parentheses be evaluated before.
Javascript typeof operator for type control
We have been able to verify that, for certain operators, the type of data they
are handling is important, since if the data is of one type, different operations
will be performed than if they are of another.
For example, when we used the operator +, if it was numbers it added them,
but if it was character strings it concatenated them. We see then that the type
of data we are using does matter and that we will have to be aware of this
detail if we want our operations to be carried out as expected.
To check the type of a data you can use another operator that is available as
of javascript 1.1, the typeof operator, which returns a text string that
describes the type of the operator that we are checking.
Note: throughout our experience with Javascript we will see that many times
it is more useful to change the data type of a variable before doing a check
with tipeof to see if we can use it as an operand. There are several functions
to try to change the type of a variable, such as parseInt (), which we will see
later in the Second Part of the Javascript Manual.
In this example we can see that the different types of variables are printed on
the page. These can be the following:
Numbers, whether or not they have a decimal part, are always of the numeric
data type.
One of the variables is a little more complex, it is the date variable which is
an object of the Date () class, which is used for handling dates in scripts. We
will see it later, as well as the objects.
Also note that Javascript functions are treated as the
Recommendations with typeof
The most useful case I can now remember is asking if the type of a variable is
undefined, which can give you the answer about whether the variable has
been initialized or not.
variable let;
if (typeof variable == 'undefined') {
console.log ('The variable is undefined, it has no defined value);
}
Another case that is often used a lot is when debugging, when you need to
find errors in your code, in the face of erratic and unexpected operations. In
those cases it is useful to consult the type of the variables, because sometimes
in Javascript they bring you surprises that make your programs not work
well.
Javascript control structures
The scripts seen so far in the Javascript Manual have been tremendously
simple and linear: simple statements were executed one after the other from
start to finish. However, this does not always have to be the case and in fact,
in most cases things are much more complex.
They are used to perform some actions or others depending on the state of the
variables. That is, make decisions to execute some instructions or others
depending on what is happening at that moment in our programs.
For example, depending on whether the user who enters our page is of legal
age or not, we may or may not allow him to view the contents of our page.
IF
SWITCH
Loops
Loops are used to perform certain actions repeatedly. They are widely used at
all levels in programming. With a loop we can, for example, print the
numbers from 1 to 100 on a page without having to write the print instruction
a hundred times.
From 1 to 100
Print the current number
In javascript there are several types of loops, each one is indicated for a
different type of iteration and they are the following:
FOR
WHILE
DO WHILE
if (expression) {
// actions to be taken in the positive case
// ...
}
Optionally, actions can be indicated in case the evaluation of the sentence
returns negative results.
if (expression) {
// actions to be taken in the positive case
// ...
} else {
// actions to be taken in the negative case
// ...
}
Let's look at several things. To start, we see how the keys include the actions
that we want to carry out in case the expressions are fulfilled or not. These
keys must always be placed, except in the case that there is only one
instruction as actions to be performed, which are optional.
if (it rains)
alert ("Water falls");
It would be exactly like this code:
if (it rains) {
alert ("Water falls");
}
Or even, just like this other:
if (it rains) alert ("Water falls");
However, when we use the keys, the code is much clearer, because you can
see at a glance what instructions are depending on the positive case of the if.
This is a detail that may not be very important now, but it will be appreciated
when the program is more complex or when several programmers are in
charge of touching the same code.
Another detail that is obvious is the indentation (margin) that we have placed
in each of the instruction blocks to be executed in the positive and negative
cases. This indentation is totally optional, we have only done it this way so
that the IF structure is understood in a more visual way. Line breaks are also
not necessary and have also been placed for a better view of the structure. We
could perfectly put the entire IF statement in the same line of code, but that
won't help things be clear.
Note: We, as well as anyone with some experience in the programming area,
would advise using the necessary indents and line breaks so that the
instructions can be better understood. Maybe the day you make a code you
will be clear about what you have done and why it is so, but in a month, when
you have to reread that code, you may remember less than what you did in
your scripts and you will appreciate that they have a friendly format for that
can be easily read by people. If you work as a team these recommendations
will be even more important, since it is even more difficult to read source
code that other people have made.
Let's see some example of IF conditionals.
if (dia == "monday")
document.write ("Have a happy start to the week")
if (credit> = price) {
document.write ("you have bought the article" + new article) // show purchase
cart + = newArticle // insert the item in the shopping cart
credit - = price // I decrease the credit according to the price of the item
} else {
document.write ("you have run out of credit") // I report that you are short of money
window.location = "shoppingcart.html" // I go to the cart page
}
This example is a little more complex, and also a little fictional. What I do is
check if I have credit to make an alleged purchase. To do this, I look at
whether the credit is greater than or equal to the price of the item, if so, I
inform about the purchase, insert the item in the cart and rest the price of the
accumulated credit. If the price of the item is higher than the money
available, I report the situation and send the browser to the page where your
shopping cart is displayed.
Conditional expressions
The expression to evaluate is always placed in parentheses and is made up of
variables that are combined with each other using conditional operators. We
recall that conditional operators related two variables and always returned a
boolean result. For example, a conditional operator is the operator "is equal"
(==), which returns true if the two operands are the same or false if they are
different.
if (age> 18)
document.write ("you can see this page for adults")
In this example we use the conditional operator "is greater" (>). In this case,
it returns true if the variable age is greater than 18, so the following line
would be executed, informing us that the adult content can be seen.
Note: The list of operators that can be used with IF structures can be seen in
the chapter on conditional operators and logical operators.
The if structure is one of the most used in programming languages, to make
decisions based on the evaluation of a sentence. In the previous article in the
Javascript Manual we already started to explain the if structure and now we
are going to see some more advanced uses.
Nested IF statements
To make conditional structures more complex we can nest IF statements, that
is, put IF structures inside other IF structures. With a single IF we can
evaluate and perform one action or another according to two possibilities, but
if we have more possibilities to evaluate we must nest IFs to create the
necessary code flow to decide correctly.
For example, if I want to check if one number is less than or equal to another,
I have to evaluate three different possibilities. First I can check if the two
numbers are equal, if they are, I have already solved the problem, but if they
are not equal I will still have to see which of the two is greater. Let's look at
this example in Javascript code.
var number1 = 23
var number2 = 63
if (number1 == number2) {
document.write ("The two numbers are the same")
} else {
if (number1> number2) {
document.write ("The first number is greater than the second")
} else {
document.write ("The first number is less than the second")
}
}
We note again that the keys are optional in this case, since only one statement
is executed for each case. In addition, line breaks and indents are also
optional in any case and only serve to see the code in a more orderly way.
Keeping the code well structured and written in an understandable way is
very important, since it will make life more pleasant when programming and
later when we have to review the programs.
Note: In this manual I will use a notation like the one you have seen in the
previous lines. Also, I will keep that notation at all times. This will
undoubtedly make the codes with examples easier to understand, if we did
not do so it would be a real nuisance to read them. This same recipe is
applicable to the codes that you have to create and the main beneficiary will
be yourself and the colleagues who get to read your code.
IF operator
There is an operator that we haven't seen yet and it's a more schematic way of
doing some simple IFs. It comes from the C language, where very few lines
of code are written and where the less we write the more elegant we will be.
This operator is a clear example of saving lines and characters when writing
scripts. We will see it quickly, because the only reason I include it is so that
you know that it exists and if you find it on some occasion out there you can
identify it and how it works.
This example looks to see if the current time is less than 12. If so, it is now
before noon, so assign "Before Noon" to the variable time. If the hour is
greater than or equal to 12, it is already after noon, so the text "After noon" is
assigned to the moment variable.
Javascript SWITCH structure
Control structures are the way in which you can control the flow of programs,
to do different things depending on the states of the variables. In the
Javascript Manual we already started to see the control structures and now it
is SWITCH's turn, a slightly more complex structure that allows multiple
operations depending on the state of a variable.
In this article we will see that switch helps us to make decisions based on
different states of the variables. This expression is used when we have
multiple possibilities as a result of evaluating a sentence.
switch (expression) {
case value1:
Statements to execute if the expression has a value of value1
break
case value2:
Statements to execute if the expression has a value of value2
break
case value3:
Statements to execute if the expression is valued at value3
break
default:
Statements to execute if the value is not one of the above
}
The expression is evaluated, if it is worth value1 the sentences related to that
case are executed. If the expression is worth value2, the instructions related to
that value are executed, and so on, for as many options as we want. Finally,
for all cases not previously contemplated, the default case is executed.
The word break is optional, but if we do not put it after a value is found, all
the sentences related to this and all the following will be executed. That is, if
in our previous scheme there were no breaks and the expression were value1,
the sentences related to value1 would be executed, as well as those related to
value2, value3 and default.
switch (day_of_the_week) {
case 1:
document.write ("It's Monday")
break
case 2:
document.write ("It's Tuesday")
break
case 3:
document.write ("It's Wednesday")
break
case 4:
document.write ("It's Thursday")
break
case 5:
document.write ("It's Friday")
break
case 6:
case 7:
document.write ("It's weekend")
break
default:
document.write ("That day does not exist")
}
Note: We also have a video tutorial on SWITCH in Javascript that can be very helpful to
understand everything much better.
FOR loop in Javascript
The FOR loop is used to repeat one or more instructions a certain number of
times. Among all the loops, the FOR is usually used when we know for sure
the number of times we want it to run. The for loop syntax is shown below.
The FOR loop has three parts included in parentheses, which help us define
how we want repetitions to be performed. The first part is initialization,
which is executed only when starting the first iteration of the loop. In this
part, the variable that we will use to keep count of the times the loop is
executed is usually placed.
The second part is the condition, which will be evaluated every time an
iteration of the loop begins. Contains an expression to decide when to stop
the loop, or rather, the condition that must be met for the loop to continue
running.
Finally we have the update, which serves to indicate the changes that we
want to execute in the variables every time the loop iteration ends, before
checking if it should continue executing.
After the for, the sentences that we want to execute in each iteration are
placed, enclosed in curly braces.
An example of using this loop can be seen below, where the numbers from 0
to 10 will be printed.
var i
for (i = 0; i <= 10; i ++) {
document.write (i)
document.write ("<br>")
}
In this case, the variable i is initialized to 0. As a condition to perform an
iteration, it must be met that the variable i is less than or equal to 10. As an
update, the variable i will be increased by 1.
As you can see, this loop is very powerful, since in a single line we can
indicate many different and very varied things, which allows a fast
configuration of the loop and enormous versatility.
For example, if we want to write the numbers from 1 to 1,000 two by two, the
following loop will be written.
Note: Another detail, we do not use the keys encompassing the instructions of
the FOR loop because it only has one statement and in this case it is not
forced, as it happened with the IF instructions.
If we want to count down from 343 to 10 we would use this loop.
This is a loop that writes the headings from <H1> to <H6> on a web page
with a text that says "Level x heading".
Now that we are familiar with the for loop, we are in a position to learn how
to handle other control structures for repeating, such as the while and do ...
while loops.
WHILE and DO WHILE loops
We are dealing with the different control structures that exist in the Javascript
language and specifically looking at the different types of loops that we can
implement in this programming language. In previous articles of the
Javascript Manual we already saw the first of the loops that we should know,
the for loop and now we are going to deal with the other two types of control
structures to do repetitions. So let's now look at the two types of WHILE
loops that we can use in Javascript and the uses of each.
WHILE loop
These loops are used when we want to repeat the execution of some
sentences an indefinite number of times, as long as a condition is met. It is
easier to understand that the FOR loop, since it does not incorporate in the
same line the initialization of the variables its condition to continue executing
and its update. Only the condition that must be met for an iteration to be
performed is indicated, as we will see below.
while (condition) {
// statements to execute
}
An example of code where this loop is used can be seen below.
This is an example of the simplest thing to do with a while loop. What it does
is ask the user to enter a color and it does it repeatedly, as long as the entered
color is not red. To execute a loop like this we first have to initialize the
variable that we are going to use in the loop iteration condition. With the
initialized variable we can write the loop, which will check to execute that the
color variable is different from "red". In each iteration of the loop a new color
is requested from the user to update the color variable and the iteration is
finished, so we return to the beginning of the loop, where we have to re-
evaluate if what is in the color variable is "red" and so on as long as the text
"red" has not been entered as a color.
Note: In this example we have used the Javascript prompt function, which we
have not yet seen in this manual. This function is used to display a dialog box
where the user must type a text. This function belongs to the Javascript
window object and we discuss it in the article Window methods in Javascript.
DO ... WHILE loop
The do ... while loop is the last of the structures to implement repetitions
available in Javascript and is a variation of the while loop seen above. It is
generally used when we do not know how many times the loop will be
executed, just like the WHILE loop, with the difference that we know for
sure that the loop will execute at least once.
This type of loop was introduced in Javascript 1.2, so not all browsers
support it, only version 4 or higher. In any case, any code you want to write
with DO ... WHILE can also be written using a WHILE loop, so in older
browsers you will have to translate your DO ... WHILE loop into a WHILE
loop.
do {
// loop statements
} while (condition)
The loop is always executed once and at the end the condition is evaluated to
tell if the loop is executed again or its execution ends.
Let's look at the example we wrote for a WHILE loop in this other type of
loop.
var color
do {
color = prompt ("give me a color (write red to exit)", "")
} while (color! = "red")
This example works exactly the same as the previous one, except that we did
not have to initialize the color variable before entering the loop. Asks for a
color while the entered color is different from "red".
Example of the use of while loops
Let's see below a more practical example on how to work with a WHILE
loop. As it is very difficult to make practical examples with the little we
know about Javascript, we are going to advance an instruction that we do not
yet know.
var sum = 0
while (sum <1000) {
sum + = parseInt (Math.random () * 100)
document.write (sum + "<br>")
}
We assume that as far as the WHILE loop is concerned there will be no
problems, but where there may be problems is in the statement used to take a
random number. However, it is not necessary to explain the sentence here
because we plan to do it later. Anyway, if you want, you can see this article
that talks about random numbers in Javascript.
Break and continue
Imagine for example that you are doing a very long loop to find something on
hundreds or thousands of sites. But put yourself in the case that during the
first iterations you find that value you were looking for. Then there would be
no point in going through the rest of the loop to search for that item, as you
had already found it. In these situations it is convenient for us to know for the
loop to cancel the rest of the iterations. Obviously, this is just one example of
how we might need to control the loop a bit more. In real life as a
programmer you will find many other occasions where you will be interested
in doing this or other things with them.
Thus, there are two instructions that can be used in the different control
structures and mainly in the loops, which will help you control two types of
situations. They are the break and continue instructions:
Break
A loop is stopped using the word break. Stopping a loop means exiting it and
leaving everything as is to continue the program flow immediately after the
loop.
for (i = 0; i <10; i ++) {
document.write (i)
type = prompt ("tell me if I keep asking ...", "yes")
if (type == "no")
break
}
This example writes the numbers from 0 to 9 and in each iteration of the loop
asks the user if they want to continue. If the user says anything, it continues,
except when he says "no", a situation in which he exits the loop and leaves
the account where he had left off.
Continue
It is used to return to the beginning of the loop at any time, without executing
the lines below the word continue.
var i = 0
while (i <7) {
increase = prompt ("The account is at" + i + ", tell me if I increase",
"if")
if (increment == "no")
continue
i ++
}
This example would normally count from i = 0 to i = 7, but each time the
loop is executed it asks the user if he wants to increase the variable or not. If
you enter "no", the continue statement is executed, which returns to the
beginning of the loop without increasing the variable i by 1, since the
statements below the continue would be ignored.
Nesting a loop consists of putting that loop inside another. Loop nesting is
necessary to make certain processing a little more complex than what we
have seen in the previous examples. If in your experience as programmers
you have nested them a loop yet, be sure that sooner or later you will meet
that need.
A nested loop has a structure like the one below. We will try to explain it in
view of these lines:
Due to the flow of the program in nesting schemes like the one we have seen,
the loop that is nested (further in) is the one that is executed the most times.
In this example, for each iteration of the outermost loop the nested loop will
run full once, that is, it will do its 10 iterations. These values would be
written to the web page, in the first iteration of the external loop and from the
beginning:
0-0
0-1
0-2
0-3
0-4
0-5
0-6
0-7
0-8
0-9
For each iteration of the outer loop the 10 iterations of the inner or nested
loop will be executed. We have seen the first iteration, now we are going to
see the following iterations of the outer loop. In each one accumulates a unit
in variable i, with what these values would come out.
1-0
1-1
1-2
1-3
1-4
1-5
1-6
1-7
1-8
1-9
2-0
2-1
2-2
2-3
2-4
2-5
2-6
2-7
2-8
2-9
So until the two loops are finished, which would be when the value 9-9 is
reached.
Let's see an example very similar to the previous one, although a little more
useful. The aim is to print all the multiplication tables on the page. From 1 to
9, that is, the table from 1, the table from 2, from 3 ...
Note: We will see more things with nested loops in later chapters, although if
we want to go a little ahead to see a new example that strengthens this
knowledge, we can see an example in the Javascript Workshop on nested
loops, where the table is built with all the colors cigars in 256 color
definitions.
Javascript functions
Now we are going to see a very important topic, especially for those who
have never programmed and with Javascript they are taking their first steps in
the world of programming since we will see a new concept, that of function,
and the uses it has. For those who already know the concept of function it
will also be a useful chapter, because we will also see the syntax and
operation of functions in Javascript.
What is a function
When making a slightly large program, there are certain processes that can be
conceived independently, and which are easier to solve than the whole
problem. Furthermore, these are usually carried out repeatedly throughout the
execution of the program. These processes can be grouped into a function,
defined so that we do not have to repeat that code over and over in our
scripts, but simply call the function and it is in charge of doing everything it
should.
Note: If we want, we can expand this description of the functions in the article Function concept.
The functions are constantly used, not only those that you write, but also
those that are already defined in the system, since all programming languages
usually have a lot of functions to carry out common processes, such as
obtaining the time, printing a message on the screen or convert variables from
one type to another. We've already seen some function in our simple
examples above. For example, when we were making a document.write () we
were actually calling the write () function associated with the page document,
which writes text to the page.
In the chapters of functions we will first see how to perform our own
functions and how to call them later. Throughout the manual we will see
many of the functions defined in Javascript that we must use to perform
different types of common actions.
How to write a function
A function must be defined with a special syntax that we will know next.
function functionname () {
function instructions
...
}
First write the word function, reserved for this use. Then the name of the
function is written, which, like variable names, can have numbers, letters and
some additional character as in underscore. Then the different instructions of
the function are placed in braces. The braces in the case of functions are not
optional, and it is also useful to always place them as seen in the example, so
that the structure of instructions included in the function is easily recognized.
To execute the function we use its name followed by the parentheses. For
example, this would call the writeWelcome () function we just created.
write Welcome ()
Where do we put the Javascript functions
a) Put the function in the same script block: Specifically, the function can be
defined in the <SCRIPT> block where the function call is, although it does
not matter if the call is before or after the function code , within the same
<SCRIPT> block.
<SCRIPT>
myFunction ()
function myFunction () {
// I do something ...
document.write ("This is fine")
}
</SCRIPT>
This example works correctly because the function is declared in the same
block as its call.
b) Put the function in another script block: It is also valid that the function is
in a <SCRIPT> block before the block where the call is.
<HTML>
<HEAD>
<TITLE> MY PAGE </TITLE>
<SCRIPT>
function myFunction () {
// I do something ...
document.write ("This is fine")
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
myFunction ()
</SCRIPT>
</BODY>
</HTML>
To make this issue of function placement clear, let's look at the following
example, which would give an error. Look carefully at the following code,
which will throw an error, because we make a call to a function that is
declared in a subsequent <SCRIPT> block.
<SCRIPT>
myFunction ()
</SCRIPT>
<SCRIPT>
function myFunction () {
// I do something ...
document.write ("This is fine")
}
</SCRIPT>
With this we hope to have resolved all the doubts about the placement of the
code of the Javascript functions. In the following articles we will see other
interesting topics such as the parameters of the functions.
Function parameters
The ideas that we have previously explained about functions are not the only
ones that we must learn to handle them to their full potential. Functions also
have data input and output. In this article we will see how we can send data to
Javascript functions.
Parameters
Parameters are used to send values to functions. A function will work with
the parameters to perform the actions. To put it another way, parameters are
the input values that a function receives.
To call a function that has parameters, place the value of the parameter in
parentheses. To call the example function you would have to write:
The parameters can receive any type of data, numeric, textual, boolean or an
object. We do not really specify the type of the parameter, so we must take
special care when defining the actions we perform within the function and
passing values to it, to ensure that everything is consistent with the types of
data that we expect our variables or parameters to have.
Multiple parameters
In the example we have a function that receives a parameter and modifies the
value of the parameter assigning it the value 32. We also have a variable,
which we initialize to 5 and later we call the function passing this variable as
a parameter. As within the function we modify the value of the parameter, it
could happen that the original variable changes its value, but since the
parameters do not modify the original value of the variables, it does not
change its value.
In this way, once the function is executed, when printing the value of
miVariable on screen, the number 5 will be printed, which is the original
value of the variable, instead of 32, which was the value with which we had
updated the parameter.
We are learning about the use of functions in Javascript and at the moment
we may have already realized the great importance they have in making
programs more or less advanced. In this article of the Javascript Manual we
will continue learning things about functions and specifically that with them
you can also return values. In addition, we will see some interesting use case
on the functions that can clarify a bit the scope of local and global variables.
Returning values in functions
Javascript functions can also return values. In fact, this is one of the most
essential utilities of the functions, which we must know, not only in
Javascript but in general in any programming language. So, by invoking a
function, you can perform actions and offer a value as output.
For example, a function that calculates the square of a number will have that
number as input and as the output it will have the value resulting from
finding the square of that number. The data entry in the functions we saw
earlier in the article on function parameters. Now we have to learn about the
exit.
To specify the value that the function will return, the word return is used,
followed by the value that you want to return. In this case, the content of the
result variable is returned, which contains the calculated mean of the two
numbers.
To illustrate this, you can see this example, which will call the mean ()
function and save the result of the mean in a variable and then print it on the
page.
var my media
myAverage = mean (12.8)
document.write (myMedia)
Multiple return
Actually in Javascript functions can only return one value, so in principle we
cannot make functions that return two different data.
Note: in practice nothing prevents us from having a function return more than
one value, but since we can only return one thing, we would have to put all
the values that we want to return in a data structure, such as an array.
However, that would be a more or less advanced use that we are not going to
see at the moment.
Now, although we can only return one data, in the same function we can
place more than one return. As we say, we are only going to be able to return
one thing, but depending on what has happened in the function it may be of
one type or another, with some data or others.
Within the functions we can declare variables. On this matter we must know
that all the variables declared in a function are local to that function, that is,
they will only be valid during the execution of the function.
Note: Even if we think about it, we can realize that the parameters are like
variables that are declared in the function's header and that are initialized
when calling the function. The parameters are also local to the function and
will be valid only when the function is running.
It could be the case that we can declare variables in functions that have the
same name as a global variable to the page. So, inside the function, the
variable that will be valid is the local variable and outside the function the
global variable to the page will be valid.
On the other hand, if we do not declare the variables in the functions, it will
be understood by javascript that we are referring to a global variable to the
page, so if the variable is not created it creates it, but always global to the
page instead of local to the function.
function variables_glogales_y_locales () {
var local variable = 23
globalGlobal = "qwerty"
}
In this case variableLocal is a variable that has been declared in the function,
so it will be local to the function and will only be valid during its execution.
On the other hand, variableGlobal has not been declared (because before
using it, the word var has not been used to declare it). In this case the variable
variableGlobal is global to the whole page and will continue to exist even if
the function ends its execution. Also, if the variable variableGlobal existed
before calling the function, as a result of executing this function, a
hypothetical value of that variable would be pounded and replaced by
"qwerty".
eval (string)
This function receives a character string and executes it as if it were a
Javascript statement.
parseFloat (string)
Converts the string to a number and returns it.
escape (character)
Returns a character that it receives as a parameter in an ISO Latin 1 encoding.
unescape (character)
It does the exact opposite of the escape function.
isNaN (number)
Returns a boolean depending on what it receives per parameter. If it is not a
number it returns true, if it is a number it returns false.
The libraries that are implemented through objects and those of the browser
handling, which are also managed with objects, we will see later.
Note: We don't want to mislead people with this short list of native Javascript
functions. There really are many other functions that we will see throughout
this manual, what happens is that they are associated with objects. For
example, as we have pointed out, there are character string functions, which
are associated with string objects, functions for working with advanced
mathematical calculations, which are associated with the Math class,
functions for working with the object of the browser window, with the
document, etc.
Examples of using the functions incorporated in Javascript
So far we have simply known a list of the native functions of the Javascript
language. Now we can see several examples of the use of native Javascript
functions, which we have available in any browser and in any version of
Javascript.
We will see three functions from different fields that are quite fundamental in
the usual work with this language, explained through examples.
Eval function
This function is very important, so much so that there are some Javascript
applications that could not be performed if we do not use it. Its use is very
simple, but it may be a little more complex to understand in which cases to
use it because sometimes its application is a little subtle.
document.write (3 + 5)
The eval function executes the instruction passed to it by parameter, so it will
execute this statement, which will result in an 8 being written to the web
page. First the sum in parentheses is solved, so we get the 8 and then the
write on screen instruction is executed.
ParseInt function
This function receives a number, written as a string, and a number that
indicates a base. You can actually receive other types of variables, since
variables have no type in Javascript, but it is usually used by passing a string
to convert the text variable to a number.
The different bases that the function can receive are 2, 8, 10 and 16. If we do
not pass any value as a base, the function interprets the base as decimal. The
value returned by the function always has base 10, so if the base is not 10 it
converts the number to that base before returning it.
Let's look at a series of calls to the parseInt function to see what it returns and
to understand the function a little more.
As you can see, the function tries to convert the string to number and if it
can't it returns NaN.
IsNaN function
This function returns a boolean depending on whether it receives a number or
not. The only thing you can receive is a number or the expression NaN. If it
receives a NaN it returns true and if it receives a number it returns false. It is
a very simple function to understand and use.
We have a very interesting Javascript Workshop that has been carried out to
strengthen the knowledge of these chapters. It is a script to validate a form
field so that we know for sure that within the field there is always an integer.
It can be very interesting to read it now, since we use the isNaN () and
parseInt () functions. See the workshop
We hope that the examples seen in this article have been interesting.
However, as we noted earlier, there are quite a few other native Javascript
functions that we should be aware of, but which are associated with native
Javascript classes and objects. But before moving on to that point we want to
offer a small basic guide for working with object-oriented programming in
Javascript.
Arrays in Javascript
In programming languages there are special data structures that help us store
more complex information than simple variables. A typical structure in all
languages is the Array, which is like a variable where we can enter several
values, instead of just one as it happens with normal variables.
Note: The arrays were introduced in Javascript versions 1.1 or higher, that is,
we can only use them from browsers 3.0. For older browsers you can
simulate the array using object-oriented programming syntax, but the truth is
that currently this limitation should not concern us. Furthermore, given the
complexity of the task of simulating an array by means of objects, at least at
the time we meet and the few occasions when we will need it, we think that it
is better to forget about that matter and simply work with arrays usually. So
in this article and the following we are going to see how to use the authentic
Javascript array.
Creation of javascript arrays
The first step in using an array is to create it. For this we use a Javascript
object already implemented in the browser. We will now see a topic to
explain what object orientation is, although it will not be necessary to
understand the use of arrays. This is the statement to create an array object:
It is important to note that the word Array in Javascript code is written with
the first letter capitalized. As in uppercase and lowercase javascript if they
matter, if we write it in lowercase it will not work.
As you can see, we are defining a variable called fastArray and we are
indicating in the square brackets several values separated by commas. This is
the same as having declared the array with the Array () function and then
loading the values one by one.
Array length
All arrays in javascript, apart from storing the value of each of their boxes,
also store the number of positions they have. To do this they use a property of
the array object, the length property. We will see in objects what a property
is, but in our case we can imagine that it is like a variable, in addition to the
positions, that stores a number equal to the number of boxes that the array
has.
To access a property of an object, the dot operator must be used. The name of
the array that we want to access is written to the number of positions it has,
without brackets or parentheses, followed by a period and the word length.
The following example will help us to better understand the routes through
the arrays, the operation of the length property and the dynamic creation of
new positions. We are going to create an array with 2 positions and fill its
value. Later we will introduce a value in position 5 of the array. Finally we
will print all the positions of the array to see what happens.
It can be clearly seen that the number of positions is 6, from 0 to 5. What has
happened is that when entering a data in position 5, all the boxes that were
not created until the fifth are also created.
Positions 2 through 4 are uninitialized. In this case our browser has written
the word null to express this, but other browsers may use the word undefined.
We will see later what this null is and where we can use it, the important
thing now is that you understand how arrays work and use them correctly.
Multidimensional arrays in Javascript
As we are seeing, arrays are quite important in Javascript and also in most
programming languages. Specifically, we have already learned to create
arrays and use them in previous articles in the Javascript Manual. But we still
have some important things to explain, such as arrays of various dimensions.
Multidimensional arrays are a data structure that stores values in more than
one dimension. The arrays that we have seen so far store values in one
dimension, so we only use an index to access positions. 2-dimensional arrays
store their values, so to speak, in rows and columns and therefore we will
need two indexes to access each of their positions.
With the previous lines we have created three 1-dimensional arrays and three
elements, like the ones we already knew. Now we will create a new array of
three elements and we will introduce into each of its boxes the arrays created
previously, with which we will have an array of arrays, that is, a 2-
dimensional array.
The method of looping through another is to put one loop inside another,
which is called a nested loop. In this example we are going to put one FOR
loop inside another. In addition, we are going to write the results in a table,
which will complicate the script a bit, but this way we will be able to see how
to build a table from Javascript as we make the nested tour of the loop.
Note: You may have noticed that sometimes generating HTML code from
Javascript becomes complex. But the problem is not only that the code is
difficult to produce, but the worst thing is that you create a code that is
difficult to maintain, in which both the part of the programming in Javascript
is mixed with the part of the presentation in HTML. What you have also seen
is just a very simple code, with a really elementary table, imagine what would
happen when the table or the data were more complex. Fortunately, there are
better ways to generate HTML output than we have seen now, although it is a
bit advanced at the moment. Anyway, we leave you a link to the manual of
the Javascript Handlebars templates system, which is a simple library
alternative to generate HTML output from Javascript.
We can see the running example and examine the entire script code.
Array initialization
To finish with the topic of arrays, we are going to see a way to initialize its
values at the same time that we declare it, so we can carry out the process of
entering values in each of the positions of the array in a faster way.
The normal method of creating an array we saw was through the Array
object, putting the number of boxes in the array in parentheses or not putting
anything, so that the array is created without any position. To introduce
values to an array it is done the same, but putting the values with which we
want to fill the cells separated by commas between the parentheses. Let's see
it with an example that creates an array with the names of the days of the
week.
Javascript still has a more summarized way than the one we just saw, which
we explained in the first article where we covered arrays. To do this we
simply put the data of the array we are creating in square brackets. To finish
we will show an example on how to use this syntax to declare arrays of more
than one dimension.
Note: To start getting a bit soaked about objects we have a small article
published in DesarrolloWeb about object-oriented programming. It would be
highly recommended that you read it, because several concepts are explained
in which we will not go into so much detail. If you already know the POO,
continue reading without pause, but if you want to go deeper, remember that
we also have a complete Object Orientation Manual. If you like to watch
videos we also recommend the What are the objects class taught in the Video
Programming Course.
What is an object
Although we are not going to go into detail with the concetos, as they are
very well explained in references that we have already indicated, objects are a
programming language tool in which two fundamental things come together:
data and functionality. Every computer program basically deals with those
two things in some way. With what we have seen so far we had the data in
variables and the functionality in functions, right? because in the world of
objects, both data and functionality are in the same structure, the object.
The thing is that now you need to learn new names with which to refer to the
data and functionality grouped into an object:
Note: To know what the browser objects are, which we have available in
Javascript to solve the needs of web pages, you have to read the manual on
working with Javascript to use and manipulate browser resources.
How to access object properties and methods
In Javascript we can access the properties and methods of objects in a similar
way to what we do in other programming languages, with the operator dot
(".").
The properties are accessed by placing the name of the object followed by a
period and the name of the property to be accessed. In this way:
myObject.myProperty
To call the methods we use a similar syntax, but putting the parameters that
we pass to the methods in parentheses. As follows:
myObject.myMethod ()
How to create objects
As we have said, most of the objects with which you are going to work in
Javascript in order to create interaction, effects and diverse behaviors on web
pages, they give you ready-made. The browser itself offers them to you so
you simply have to use them. That's study material from the Javascript
Manual and browser objects. Having clarified that point, it should be noted
that Javascript is somewhat particular when creating objects, basically
because traditionally there is no "class" concept.
{
name: 'Miguel Angel Alvarez',
SitioWeb: 'DesarrolloWeb.com'
}
In the previous code we have only defined properties, but we have other
articles where you can see how to define methods as well. To know more
about object literals we recommend reading the article on Javascript object
literals, where we will explain more carefully this usual syntax for creating
objects in this language.
In traditional Javascript we have said that classes do not exist, but we can
create instances of objects from functions, as we will see in the next point.
Create and instantiate objects from functions
For those who do not know, instantiating an object is the action of creating an
instance of a class, so that you can work with it later. Class is the definition
of the characteristics and functionalities of an object. Classes do not work
directly, these are only definitions. To work with a class we must have an
instantiated object of that class. We remember that in Javascript there are no
classes, but we can use functions.
You will notice that we are using the word "this" inside. That word is a
reference to the object to be created with this function. In javascript to create
an object from a function the new statement is used, in this way.
Modify property
The TypeError error will be called when you try to change non-adjustable
properties (except for a writable value as shown above).
The configurable key controls whether the property can be deleted from the
object (via the delete parameter), and whether the rest of the keys can be
changed (except that the value of the key is writable to false):
var o = {};
Object.defineProperty (o, 'a', {
get: function () {return 1; },
configurable: false
});
console.log (o.a); // 1
delete o.a; // Nothing will happen
console.log (o.a); // 1
If the configurable key value of the o.a property is true, none of the previous
errors will be thrown, and the property will eventually be deleted.
Add the default attributes and values of the keys
It is important to take into account the default values of the keys. There is a
big difference between assigning a value to a property of the object directly
and using the Object.defineProperty () function as shown in the following
example:
var o = {};
oa = 1;
// Rewards expression
Object.defineProperty (o, 'a', {
value: 1,
writable: true,
configurable: true,
enumerable: true
});
"But in return
Object.defineProperty (o, 'a', {value: 1});
// Rewards
Object.defineProperty (o, 'a', {
value: 1,
writable: false,
configurable: false,
enumerable: false
});
function TestDefineSetAndGet () {
Object.defineProperty (this, 'myproperty', pattern);
}
Object.defineProperties ()
General structure
obj
The object in which you want to define properties or modify them.
props
An object with its own enumerated properties specifying the property
descriptors that will be added to or modified by the object and which will be
associated with attribute names. There are two types of descriptors: data
descriptors and accessor descriptors, see the Object.defineProperty () function
page for more details.
Data descriptors and access descriptors are objects, sharing the following
required keys:
* configurable: If the value of this key is true, you can modify the property
descriptor (not the value of the property) and the property can be deleted
from the object. The default value is false.
enumerable: If the value of this key is true, this property will appear when
enumerating the object's enumeration properties. The default value is false.
The following optional keys can exist in metadata:
* value: Specifies the value associated with the property, and any value can
be allowed in JavaScript (such as numbers, functions, objects, etc.). The
default value is undefined.
writable: If the value of this key is true, the value associated with this
property can be modified by using the assignment coefficients. The default
value is false.
The following optional keys can be found in access descriptors:
* get: The function that will be set as a getter function for this property, or the
undefined value if there is no getter function associated with this property;
the value returned by this function will be used as a value for the property.
The default value is undefined.
set: The function that will be set as a setter function for this property, or the
undefined value if there is no setter function associated with this property;
this function accepts one argument that is the new value that the user
attempted to attribute to this property. The default value is undefined.
Returned value
The object that passed to the function.
the description
The Object.defineProperties () function defines all properties on the obj
object, which are dependent on the object (and must also be enumerated).
Examples
Assuming that the operating environment is not modified, as all the names
and properties indicate their initial values, the following function is
equivalent to the object.defineProperties () function:
var d = {};
return d;
}
return obj;
}
------------------------------------------------
Object.entries ()
The difference between this function and the loop for ... is that the for ... in
loop will override the statistically significant properties in the prototype
string as well.
General structure
Object.entries (obj)
obj
The object whose dependent properties will be returned as pairs [key, value].
Returned value
A matrix containing the values of the dependent properties of the obj object
in the form of pairs [key, value].
Examples
Example of a simple object:
Note that if you pass a broker that does not represent an object, it will be
converted to an object, as in the following text string:
But an empty matrix will be returned for any initial data type, because the
initial values do not have any attributes associated with them:
if (! Object.entries)
Object.entries = function (obj) {
var ownProps = Object.keys (obj),
i = ownProps.length,
resArray = new Array (i); // preallocate the Array
while (i--)
resArray [i] = [ownProps [i], obj [ownProps [i]]];
return resArray;
};
If you want to support IE browsers that are released less than 9, you must
provide an alternative function for the Object.keys function (which you will
find on its page).
Object.freeze ()
The Object.freeze () function blocks an object, prevents the addition of new
properties to it, prevents the deletion of properties in it, and prevents the
modification of the value, scalability, scalability, or writeability of its
properties; «Frozen».
General structure
Object.freeze (obj)
obj
The object that will freeze.
Returned value
Frozen object.
the description
Any properties of frozen objects can not be added or deleted; any attempt to
do so will either fail silently or cause the TypeError exception (this error will
usually be in the strict style).
You can not change the values of attributes that have data, getter and setter
functions, note that the values of objects assigned to attributes can still be
modified unless they are also frozen.
Arrays can be frozen like objects, as we can not modify the values of their
elements, or add or delete elements from them.
Examples
Freeze objects
In the following example, we will create an object named obj, add new
properties, modify properties in it, and delete the other:
var obj = {
prop: function () {},
foo: 'bar'
};
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;
Note that the Object.freeze () function will return the frozen object, but it will
also freeze the original object, so it is not necessary to save the returned
object from the function to freeze the original object:
function fail () {
'use strict';
obj.foo = 'sparky'; // TypeError
delete obj.quaxxor; // TypeError
obj.sparky = 'arf'; // TypeError
}
fail ();
Attempting to make modifications using the Object.defineProperty ()
function will cause the TypeError error to be thrown:
fail ();
Deep freezing
It is true that the frozen object will not be adjustable, but it is not necessarily
"fixed"; in the following example, the freeze will be superficial:
obj1 = {
internal: {}
};
Object.freeze (obj1);
obj1.internal.a = 'aValue';
obj1.internal.a // 'aValue'
In order to make the object dormant, each of the properties of that object
must be frozen. This is called "deep freeze":
obj2 = {
internal: {}
};
deepFreeze (obj2);
obj2.internal.a = 'anotherValue';
obj2.internal.a; // undefined
These general attributes return a simple value, they do not represent the
functions or attributes of an object.
Infinity
NaN
Undefined
Null
1.1 Infinity
Infinity
the description
The Infinity property is a property of the global object, that is, it is a variable
in the public domain.
Examples
The following examples show the result of mathematical operations on the
value of Infinity:
1.2 NaN
The public property NaN is a value that does not represent a number (an
abbreviation for the Not-A-Number).
General structure
NaN
the description
The NaN property is a property of the global object, that is, it is a variable in
the public domain.
The initial value of the NaN property is Number.NaN. The NaN property is
not configurable and is not writable in modern browsers, but try to avoid
writing it.
The value of NaN is rarely used in programs, but it is the value that will be
returned when the functions of the Math object (such as Math.sqrt (-1)) fail or
when a numeric value (such as parseInt ("blabla") fails).
The value of NaN (via the ==,! =, === and != ==) parameters is not equal to
any other value, including the other NaN values; so use the Number.isNaN ()
or isNaN ) To see if the value involved is NaN, or try to compare the value
with itself, the NaN value is the only value that does not equal itself.
• Writeable – no
• Statistically – no
• Adjustable - No
General structure
undefined
the description
It is true that we can use the word undefined as an identifier in any field other
than the public domain (because undefined is not a reserved word), but it is
not appropriate to do so, and this will make it difficult to maintain and debug
program errors.
// "foo string"
(function (undefined)
{
console.log (undefined, typeof undefined);
}
)
('foo');
Examples
var x;
if (x === undefined) {
// The software expressions will be implemented here
}
else {
// The software expressions will not be implemented here
}
Note that we used the coefficient of matching (===) instead of using the
normal equalizer (==), because x == undefined will return true if x is null,
while the corresponding coefficient is not null. See the Comparison
Transactions page for details.
The typeof parameter is the undefined value
Alternatively, we can use the typeof parameter to see if the value of the
variable is undefined:
var x;
if (typeof x === 'undefined') {
// The software expressions will be implemented here
}
One reason for using the typeof parameter is that it will not throw an error
when the variable is not declared:
// The variable is not known yet
if (typeof x === 'undefined') { // without problems
// The software expressions will be implemented here
}
General structure
null
the description
Null is used via null, note that null is not an identifier of a property in the
public object (ie it is not like the undefined property), but null indicates that
there is no definition from the baseline, and indicates that the variable does
not refer to any object.
// The variable does not exist, as it has not been known or created before
console.log (foo); // ReferenceError: foo is not defined
String
RegExp
The String object is a syntax function for text strings, or a set of characters.
General structure
The initial values of text strings can take the following form:
'string text'
"string text"
" 中文 español deutsch English िह दी اﻟﻌﺮﺑﯿﺔportuguês বাংলা русский 日
日本語 ਪੰਜਾਬੀ ਪੰਜਾਬੀ 국어 மழழ Hebrew"
Text strings can be created using the String public object directly:
String (thing)
thing
Any value we want to convert to a text string.
Templates
Starting with the ECMAScript 2015, template literals can be created:
`hello world`
`hello!
world! `
`hello $ {who}`
escape `<a> $ {who} </a>`
Smuggling of characters
We can use the + operator to add text strings to each other as follows:
You can also use the backslash at the end of each line to indicate that the text
string will be completed in the next line; but make sure that there is no space
or any other character after the backslash (except for the new lineface),
otherwise it will not work. Here's an example of this method:
Text strings are useful for holding data that represents textual words. One of
the most commonly used operations on text strings is to check their length
(across the length property), to collect text strings using + and +, and to check
for or place subtext strings using the indexOf () function, The substring ()
function.
Access the characters
There are two ways to access the characters in a text string. The first is to use
charAt ():
Another method added to the ECMAScript 5.1 standard is to treat the text
string as matrix-like objects. The characters are associated with a numeric
index:
When you access characters using square brackets, trying to delete or assign a
value to those attributes will not work; these attributes will not be writable or
set
Compare text strings
var a = 'a';
var b = 'b';
if (a <b) { // true
console.log (a + 'is less than' + b);
} else if (a> b) {
console.log (a + 'is greater than' + b);
} else {
console.log (a + 'and' + b + 'are equal.');
}
Text strings defined by double or single quotation marks and text strings
returned from the String function without the use of the new reserved word
are primitive strings, and JavaScript automatically converts these initial
values to String objects, allowing When using the function (or trying to
access a property) on an initial string, JavaScript encapsulates the initial text
string within an object and calls the respective function (or required
property):
var s_prim = 'foo';
var s_obj = new String (s_prim);
Note that String objects and initial text strings produce different results when
used with the eval () function, as the passed string of text will be treated as
eval, and String objects will behave like other objects, ie, the object will be
returned. The following example illustrates this:
For these reasons, codes can not work when you encounter String objects
instead of primary text strings, but developers do not throw away these
differences. We can convert the String object to the initial text string that is
equivalent by using the valueOf () function:
- String.prototype
This property allows adding attributes that are available to all objects whose
type is String.
* String.fromCharCode ()
Create a text string using a string of Unicode values.
String.fromCodePoint () *
Create a text string using a string of character values (code points).
* String.raw ()
Create a text string from a raw template.
String.fromCharCode ()
General structure
Returned value
A string containing characters that are linked to the Unicode values passed to
the function.
the description
This function returns a primitive text string and does not return a String
object.
Since the fromCharCode function is a static method of the String object, you
should always use it as String.fromCharCode (), since you can not use it as
part of your String object.
Examples
For all valid Unicode values (up to 21 bits), using the fromCharCode ()
function alone is not appropriate, because characters with large values use
two digits to represent a single character; therefore, String.fromCodePoint ()
Part of the ECMAScript 2015 standard (ES6) to return such pairs, allowing
the representation of characters with values greater than the maximum.
String.fromCodePoint ()
General structure
Returned value
A text string that contains characters associated with the values of the
characters passed to the function.
Exceptions
the description
This function returns a primitive text string and does not return a String
object.
Since the fromCodePoint function is a static method of the String object, you
should always use it as String.fromCodePoint (), since you can not use it as
part of your String object.
Examples
Support browsers
The String.raw () function is a tag function for template literals, similar to the
preceding r in Python or the previous @ in C # (but there are differences
between them). Used to get the raw text string from the template (ie,
unexplained text).
General structure
String.raw`templateString`
callSite
Object to call template like: {raw: ['foo', 'bar', 'baz']}.
... substitutions
The values to be replaced.
templateString
A text string representing the template, and the values to be replaced ($ {...}).
Returned value
A raw text string for the text string that represents the template.
Exceptions
The TypeError exception will be called if the first broker is not a properly
defined object.
the description
In most cases, the String.raw () function is used with text strings that
represent the templates. The first format mentioned above is rarely used,
because the JavaScript engine will automatically call this format with the
necessary arguments.
Examples
The following examples show that the raw () function is used:
String.raw`Hi \ n $ {2 + 3}! `;
// 'Hi \ n5!', The character after 'Hi'
// is not a newline character,
// '\' and 'n' are two characters.
String.raw`Hi \ u000A! `;
// 'Hi \ u000A!', Same here, this time we will get the
// \, u, 0, 0, 0, A, 6 characters.
// All kinds of escape characters will be ineffective
// and backslashes will be present in the output string.
// You can confirm this by checking the .length property
// of the string.
let name = 'Bob';
String.raw`Hi \ n $ {name}! `;
// 'Hi \ nBob!', Substitutions are processed.