Introduction To JavaScript
Introduction To JavaScript
to JavaScript
Introduction to JavaScript
JavaScript is a programming language that adds interactivity to your website. This happens
in games, in the behavior of responses when buttons are pressed or with data entry on
forms; with dynamic styling; with animation, etc. This article helps you get started with
JavaScript and furthers your understanding of what is possible.
What is JavaScript?
JavaScript is a powerful programming language that can add interactivity to a website. It was
invented by Brendan Eich.
JavaScript is versatile and beginner-friendly. With more experience, you'll be able to create
games, animated 2D and 3D graphics, comprehensive database-driven apps, and much
more!
JavaScript itself is relatively compact, yet very flexible. Developers have written a variety of
tools on top of the core JavaScript language, unlocking a vast amount of functionality with
minimum effort. These include
JavaScript is one of the most popular modern web technologies! As your JavaScript skills
grow, your websites will enter a new dimension of power and creativity.
However, getting comfortable with JavaScript is more challenging than getting comfortable
with HTML and CSS. You may have to start small, and progress gradually. To begin, let's
examine how to add JavaScript to your page for creating a Hello world! example.
1) Go to your test site and create a new folder named scripts. Within the scripts folder,
create a new text document called main.js, and save it.
2) In your index.html file, enter this code on a new line, just before the closing
</body> tag:
3) This is doing the same job as the <link> element for CSS. It applies JavaScript to
the page, so it can have an effect on the HTML (along with the CSS, and anything
else on the page).
5) Make sure the HTML and JavaScript files are saved. Then load index.html in your
browser. You should see something like this:
What happened?
The heading text changed to Hello world! using JavaScript. You did this by using a function
called querySelector() to grab a reference to your heading and then store it in a variable
called myHeading. This is similar to what we did using CSS selectors. When you want to do
something to an element, you need to select it first.
Following that, the code set the value of the myHeading variable's textContent property
(which represents the content of the heading) to Hello world!
a) Variables
Variables are containers that store values. You start by declaring a variable with the let
keyword, followed by the name you give to the variable:
A semicolon at the end of a line indicates where a statement ends. It is only required when
you need to separate statements on a single line. However, some people believe it's good
practice to have semicolons at the end of each statement. There are other rules for when
you should and shouldn't use semicolons.
You can name a variable nearly anything, but there are some restrictions. If you are unsure,
you can check your variable name to see if it's valid.
JavaScript is case-sensitive. This means myVariable is not the same as myVariable. If you
have problems with your code, check the case!
After assigning a value to a variable, you can change it later in the code:
Note that variables may hold values that have different data types:
b) Comments
Comments are snippets of text that can be added along with the code. The browser ignores
text marked as comments. You can write comments in JavaScript just as you can in CSS:
If your comment contains no line breaks, it's an option to put it behind two slashes like this:
c) Operators
An operator is a mathematical symbol that produces a result based on two values (or
variables). In the following table, you can see some of the simplest operators, along with
some examples to try in the JavaScript console.
There are a lot more operators to explore, but this is enough for now. See Expressions and
operators for a complete list.
d) Conditionals
Conditionals are code structures used to test if an expression returns true or not. A very
common form of conditionals is the if...else statement. For example,
The expression inside the if () is the test. This uses the strict equality operator (as
described above) to compare the variable icecream with the string chocolate to see if the
two are equal. If this comparison returns true, the first block of code runs. If the comparison
is not true, the second block of code—after the else statement—runs instead.
e) Functions
Functions are a way of packaging functionality that you wish to reuse. It's possible to define
a body of code as a function that executes when you call the function name in your code.
This is a good alternative to repeatedly writing the same code. You have already seen some
uses of functions. For example,
These functions, document.querySelector and alert, are built into the browser.
If you see something which looks like a variable name, but it's followed by parentheses— ()
—it is likely a function. Functions often take arguments: bits of data they need to do their job.
Arguments go inside the parentheses, separated by commas if there is more than one
argument.
For example, the alert() function makes a pop-up box appear inside the browser window,
but we need to give it a string as an argument to tell the function what message to display.
You can also define your own functions. In the next example, we create a simple function
that takes two numbers as arguments and multiplies them:
Try running this in the console; then test with several arguments. For example
f) Events
Real interactivity on a website requires event handlers. These are code structures that listen
for activity in the browser, and run code in response. The most obvious example is handling
the click event, which is fired by the browser when you click on something with your mouse.
To demonstrate this, enter the following into your console, then click on the current webpage:
There are a number of ways to attach an event handler to an element. Here we select the
<html> element. We then call its addEventListener() function, passing in the event's name
to listen to ('click') and a function to run when the event happens.
With this review of JavaScript basics completed (above), let's add some new features to our
example site.
Before going any further, delete the current contents of your main.js file — the bit you
added earlier during the "Hello world!" example — and save the empty file. If you don't, the
existing code will clash with the new code you are about to add.
● Choose an image you want to feature on your example site. Ideally, the image will be
the same size as you added previously, or as close as possible.
● Save this image in your images folder.
● Rename the image firefox2.png.
● Add the following JavaScript code to your main.js file.
● Save all files and load index.html in the browser. Now when you click the image, it
should change to the other one.
This is what happened. You stored a reference to your <img> element in myImage. Next, you
made its onclick event handler property equal to a function with no name (an "anonymous"
function). So every time this element is clicked:
Next, let's change the page title to a personalized welcome message when the user first
visits the site. This welcome message will persist. Should the user leave the site and return
later, we will save the message using the Web Storage API. We will also include an option to
change the user, and therefore, the welcome message.
1) In index.html, add the following line just before the <script> element:
2) In main.js, place the following code at the bottom of the file, exactly as it is written. This
takes references to the new button and the heading, storing each inside variables:
3) Add the following function to set the personalized greeting. This won't do anything yet, but
this will change soon.
The setUserName() function contains a prompt() function, which displays a dialog box,
similar to alert(). This prompt() function does more than alert(), asking the user to enter
data, and storing it in a variable after the user clicks OK. In this case, we are asking the user
to enter a name. Next, the code calls on an API localStorage, which allows us to store data
in the browser and retrieve it later. We use localStorage's setItem() function to create and
store a data item called 'name', setting its value to the myName variable which contains the
user's entry for the name. Finally, we set the textContent of the heading to a string, plus the
user's newly stored name.
4) Add the following condition block. We could call this initialization code, as it structures the
app when it first loads.
This first line of this block uses the negation operator (logical NOT, represented by the !) to
check whether the name data exists. If not, the setUserName() function runs to create it. If it
exists (that is, the user set a user name during a previous visit), we retrieve the stored name
using getItem() and set the textContent of the heading to a string, plus the user's name,
as we did inside setUserName().
5) Put this onclick event handler (below) on the button. When clicked, setUserName() runs.
This allows the user to enter a different name by pressing the button.
Also, try clicking OK without entering a name. You should end up with a title that reads
Mozilla is cool, for fairly obvious reasons.
To avoid these problems, you could check that the user hasn't entered a blank name. Update
your setUserName() function to this:
In human language, this means: If myName has no value, run setUserName() again from the
start. If it does have a value (if the above statement is not true), then store the value in
localStorage and set it as the heading's text.
Conclusion
If you have followed all the instructions in this article, you should end up with a page that
looks something like the image below.
We have just scratched the surface of JavaScript. If you enjoyed playing, and wish to go
further, take advantage of the resources listed below.
If you're considering a career in Web3
Development, there's no better time
than now.
Link: https://link.almabetter.com/9w63