1 Create a simple HTML page
In order to use JavaScript in our browser, we need to include it in an HTML page.
<h1>Hello World</h1>
<script type="text/javascript" src="scripts.js"></script>
In order to use JavaScript in our browser, we need to include it in an HTML page.
<h1>Hello World</h1>
<script type="text/javascript" src="scripts.js"></script>
Let’s see if we included our file correctly.
In the same folder, let’s create a file called scripts.js
in which we call a simple function.
A variable is a named element that can contain a value.
Instead of typing 'hello world'
directly, let’s assign that value to a variable called message
.
There are different types of variables in JavaScript. Each of them has different capabilities.
true
or false
var name = 'Sam Walton'; // String
var age = 24; // Number
var student = true; // Boolean
var cities = ['Toronto', 'Paris', 'London'] // Array
// Object
var body = {
'eyes': 'brown',
'height': 175,
'hair': ['dark', 'short'],
}
alert(name + ' is ' + age + ' years old');
If you want to access a specific element of an array, you can use the syntax cities[0]
, where 0
(zero) is the index of the element you want to access.
For an object, you can simply use the key: body.eyes
or body['eyes']
.
alert('The first city is ' + cities[0]);
alert(name + ' is ' + body.height + 'cm tall');
Sometimes, depending on the value of a variable, we want to perform an action or another.
With booleans for example, we might want to do something if its value is true
, and do something else if its value is false
.
We can use a if
conditional statement: the message “Sam Walton is a student” will only be shown if student
is true
;
We can also add a else
statement, which will only be displayed if the first condition is not met.
if (student) {
alert(name + ' is a student');
}
if (age < 18) {
alert(name + ' is a minor');
} else {
alert(name + ' is an adult');
}
When we have a list of several variables, we might want to perform the same action for each of them.
In order to avoid repeating ourselves, we will use a forEach
loop.
alert(name + ' has been to:');
cities.forEach(function(city) {
alert(city);
});
In an object, what we can loop over are the keys.
To get a list of an object’s keys, we can call the function Object.keys(my_object)
. This returns an array. And we know how to loop through an array.
In the loop, as we have the key bodyPart
, we can get the value by writing body[bodyPart]
which is like writing:
body['eyes']
body['height']
body['hair']
var bodyParts = Object.keys(body);
// Returns the array ['eyes', 'height', 'hair']
bodyParts.forEach(function(bodyPart) {
alert(bodyPart + ' is ' + body[bodyPart]);
});