JavaScript is one of my favorite programming language
With JS we make our website interactive that make our website much rich in usability
We can write js in the html page itself inside <script> tag
or we can separately write js in external .js file
to link html file we must write <script src="js/script.js"></script>
where script.js is script name
js is not strictly type programming language
var we can assign anything
Statements
Statements are instructions to be executed by the web browser. Every statement should be finished with a semicolon ( ; ). The Javascript code is composed of multiple statements that will be executed in sequential order, from top to bottom.
console.log('statement 1'); console.log('statement 2');
Each web browser has its own Javascript interpreter that is responsible for executing the statements we write. They are also called Javascript engines. See the table below for the interpreters of the most popular web browsers:
Browser | Interpreter |
---|---|
Google Chrome | V8 |
Mozilla Firefox | Gecko, SpiderMonkey e Rhino. |
Safari | Nitro |
Microsoft Edge | Chakra |
Opera | Carakan |
Case Sensitive
Javascript is a case sensitive language, which means that:
// This:
console.log('something');
// Is not the same as this:
Console.log('something');
The last example will result in an error because there's no object called "Console" with a capital "C". Because of this, we should be very careful with the names of objects, properties and methods so we don't make mistakes that will generate errors in our code
Comments
Like every other programming language, we can use comments in Javascript to indicate lines of code that should be ignored by the interpreter. The double forward slashes ( // ) are used for one-line comments and multi-line comments can be done just like in CSS, starting with ( /* ) and ending with ( */ ).
DOM - Document Object Model
Now that we've had a short introduction about how Javascript works, we need to learn how we can interact with the elements of our page.
What is the DOM?
The Document Object Model is an object created by the web browser as soon as the page is loaded. This object contains all the nodes of our HTML page, which are the HTML elements. A simple example is provided below:
<html>
<head>
<title>My Title</title>
</head>
<body>
<h1>My Header</h1>
<a href="#" >My Link</a>
</body>
</html>
When the page is loaded, the browser generates the DOM tree, as shown below:
On the image we can see that the parent element of all other elements in the DOM is the Document object. So we will always use this object to select elements on our page.
With the DOM we'll be able to:
- Add, change and remove HTML elements
- Change attributes of HTML elements (like the 'class' or the 'src' of an image.)
- Change the CSS
- React upon page events (click, scroll, form input, hover, etc)
Working With the DOM
To interact with the HTML elements of our page we'll need to use some methods and properties of the document object.
getElementById and innerHTML
To select HTML elements we can search for them by their class name, Id, tag name (h1, p, img, div, etc.) and more. Let's start by the Id which is the easiest way.
if we have on navbar with id= nav_title we can use getElementByIU ,document and innerhtml to change the content of that id
// Getting the content of an element document.getElementById("nav_title").innerHTML; // Changing the content of an element document.getElementById("nav_title").innerHTML = "This will be the new content of the element.";
Now based on what we've seen above, let's try to send the content of the blue box to the console then change its content.
console.log( document.getElementById("nav_title").innerHTML );
document.getElementById("blue_box").innerHTML = "Some new content";
In order to work with data in a computer program, we need variables.
Variables are used to store data so we can use it later. Therefore we need to give them names so we can refer to them. The name of a variable is also called the identifier.
We create variables using the "var" keyword followed by its name, then an equal sign and the value we want to assign to it.
var user_name = "guest user";
After assigning the string value "guest user" to the variable, we can access it anytime we want. To test it, let's create a variable like above and then run the following statement:
console.log(user_name);
What's the use of sending this value to the console? This is a good method of testing. Now that we know that our variable was created and the value has been correctly assigned to it we can use it to form the greeting message and place it inside that html element.
document.getElementById("user_greeting_message").innerHTML = "Hello " + user_name + "!";
To form the message above we are doing string concatenation. In the next lesson we'll talk about data types and you will learn more details about this.
Before we move ahead, we need to know some rules for naming variables.
Variable names or Identifiers
Variable names can contain:
- Letters
- Numbers
- Underscores (_)
- Dollar signs ($)
Important: Variable names can contain numbers but they can't start with numbers. White spaces are also not allowed.
See below a few examples of names:
a // ok
name // ok
$name // ok
students_name // ok
student_1 // ok
1_b // invalid because it starts with a number
my-name // invalid because it has a dash (only underscores are allowed)
my name // invalid because it contains a white space
new // invalid because 'new' is a Javascript reserved word, like will be explained below.
If you speak a foreign language avoid using characters that don't exist in english, like ç, å, é, д, 国, etc. Although they are acceptable, we should also write universal code that can be easily maintained by anyone who understands english.
Keywords
Keywords (or reserved words) are used for internal functions and commands and therefore can't be used as variable names. See below some examples of keywords:
- function
- if
- else
- var
- new
- return
- break
- default
- in
Case Sensitive
As explained earlier, Javascript is a "case sensitive" language, so have this in mind when creating your variable names. If you name a variable as "username" and then try to call it as "Username" you will get an error.
Keep your names meaningful and self-explanatory
Good code should be easily understood not only by who wrote it but also by other people, so think of that when naming your variables. If we're to create a program to get the first and last name of a person, which of the names below do you think we should choose:
//Option # 1:
var first_name = "John";
var last_name = "Doe";
//Option # 2:
var name1 = "John";
var name2 = "Doe";
//Option # 3:
var a = "John";
var b = "Doe";
It should be pretty obvious that the first option is the best one. The second option is acceptable but not very good. The third option is terrible.
Naming convention
Programming languages normally have naming conventions to make the code more easily readable. Javascript programmers usually choose the lower camelCase style for naming variables. This means first letter lowercase and the first letters of subsequent words in uppercase.
// camelCase examples:
firstName
lastName
exchangeRate
maxContainerWidth
screenSize
Using only lower case characters and underscores to separate words, like last_name or max_container_width is also common. Pick the style you feel most comfortable with and keep consistent. Also try to keep the names as short as possible, which means that firstName is better than firstNameOfTheUser.
Data Types
In the previous lesson we learned that we can use variables to store values. These values can be of different types. The most basic ones are Strings, which are text values like "John", "I'm 34 years old" or "www.google.com" and Numbers.
These two types plus the Booleans (true or false) and Null and Undefined, are know as the primitive data types. Besides the primitives we also have two important data types which are the Arrays and Objects. We are going to explore each of these data types in details.
array is special type of objet whose key is number
To find out what's the type of a variable we can use the typeof operator:
var firstName = "John";
console.log( typeof firstName ); // the result will be "string"
var age = 40;
console.log( typeof age ); // the result will be "number"
Strings
Text values are called strings. Actually the best definition for a string is a sequence of characters. Strings are identified with single or double quotation marks.
Let's create some example variables to store string values:
var firstName = "John"; // we can use double quotation marks
var lastName = 'Doe'; // or single quotation marks
var passportNumber = 'XYZ0123';
var phoneNumber = "909299999";
var email = 'john_doe@gmail.com';
var bio = "John Doe started his web developer career in 2010 and has contributed to many important projects, like...";
Note that in the examples above we have the phoneNumber value composed by numbers only. Why is it string and not number type?
Although the value is composed by numbers only, it won't be used in any calculations so the string type is more indicated.
On the other hand if we are to store the year of birth of a person we might as well use the number type, because we can subtract the current year by the year of birth to find the person's age.
There are important operations that can be done with strings, as shown below:
Concatenation
var firstName = "John";
var lastName = "Doe";
var fullName = firstName + " " + lastName;
console.log(fullName);
// The result will be "John Doe"
// Therefore the plus sign (+) is used for concatenation with string values.
Length and Index
As said above, strings are sequences of characters. Those sequences has a size (length) and each of the characters has their specific position in the sequence, which is the index.
var firstName = "John";
console.log(firstName.length); // The result will be 4
/*
The length property of a string represents its number of characters.
Each character has its own index, starting from zero.
White spaces also count.
*/
console.log(firstName[0]); // The result will be 'J'
// We can access each character of a string using their index inside brackets.
String replace
There are useful ways of using the replace method. Let's say we have the following url: "https://www.udemy.com". We can easily remove the https:// by replacing it with an empty string. To use this method first inform the piece of text you want to replace and then the piece of text to replace it.
var url = "https://www.udemy.com";
console.log( url.replace( "https://" , "" ) ); // It will show "www.udemy.com"
There are many other operations we can do with strings but we are not going to explore them now. If you want you can learn more here.
Booleans
Booleans are the "true" and "false" values. They are a fundamental piece of any programming language and they are used to control all the logic of our programs.
Booleans are created when we use comparison operators:
Operator | Description |
---|---|
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
== | Equal to |
=== | Identical (same type and value) |
!= | Not equal to |
!== | Not equal value or not equal type |
20 > 2; // true
2 >= 2; // true
5 < 5; // false
5 <= 10; // true
20 == 20; // true
'john' == 'johnny' // false
'a' == 'A' // false
20 === "20"; // false - same value but different types
20 != 10; // true
10 != 10; // false
"10" !== 10; // true - type is different
/*
Be careful when using greater than and less than operators with different data types.
That can lead to unexpected results
*/
We'll use booleans on conditional structures. Let's say you will offer finance options for you customers on orders of US$1000 or above:
var orderValue = 2800;
if( orderValue >= 1000 ) {
console.log("You are eligible to finance your order.");
} else {
console.log("Finance options are not available for orders below US$1000");
}
We'll explore conditionals in depth in the next few lessons.
Null and Undefined
Variables not always have values. Null and Undefined represent the lack of value.
Undefined
When we create a variable but do not assign any value to it. Its value and data type becomes undefined.
var noValue;
console.log(noValue); // undefined
console.log(typeof noValue); // undefined
Undefined can also appear on other cases, for example when we try to access an index that does not exist in a string:
var name = "Peter";
console.log(name[0]); // Console will show "P"
console.log(name[4]); // Console will show "r"
console.log(name[10]); // Console will show undefined
When we talk about arrays and objects we'll see that:
Null
Null is not exactly a data type and for many people it should be avoided.
Null is normally used to reset the value of a variable that had a value previously:
var temperature = 35;
console.log(temperature);
temperature = null;
console.log(temperature); // The console will show null
console.log(typeof temperature); // The console will show object - which could be misleading
However, the same can be done with undefined:
var temperature = 35;
console.log(temperature);
temperature = undefined;
console.log(temperature); // The console will show undefined
In fact, Javascript even consider null and undefined to be equal:
console.log(undefined == null); // The console will show true
Some people probably just use it to differentiate when a value has never been assigned to a variable and when its value has just been reset.
In our examples we'll leave null aside and use undefined when needed.
Type conversion
const a='123432';
Functions
Functions are blocks of code designed to perform a specific task. Functions can help organize the code, avoid repetition and reduce the complexity of the code.
Let's start with a simple example.
// Creating the function
function sum_numbers() {
var num1 = 5;
var num2 = 2;
var sum = x + y;
console.log(sum);
}
// The function is only executed after being invoked:
sum_numbers(); // The console will show 7
Some important observations about what we've just done:
- We use the function keyword to create a function.
- Then we name the function following the same rules as for naming variables.
- Inside parenthesis we'll add the arguments (or parameters) of the function. Even if the function has no arguments, like above, we need to open and close parenthesis when creating and when invoking it.
- Inside the curly braces '{ }' we'll write the block of code we want to be executed every time the function is invoked.
- Semicolons are not needed at the end of function the declarations
Function arguments
The arguments of the function are like variables that can be used inside the functions. In the example above our function will always sum 5 + 2, which is not very useful. By using arguments we can make it dynamic and sum different numbers everytime.
function sum_args(num1,num2) {
var sum = num1 + num2;
console.log(sum);
}
/* Now when invoking the function we can use any numbers we want: */
sum_args(10,25); // The console will show 35
sum_args(1000,375); // The console will show 1375
sum_args(-2,47); // The console will show 45
The return statement
Our function is now dynamic but it's performing only one task: sending the result to the console. This can be useful for testing purposes but not more than that. It would be good if our function could return the value so we could do anything we want with it.
That's what the return statement will do:
function sum_args(num1,num2) {
var sum = num1 + num2;
return sum;
}
Now we can do anything we want with it, like using in other calculations and sending the result to an HTML element.
var average = sum_args(6,10) / 2;
console.log( sum_args(13,21) );
Can you sum -27 and 55 and show the result in the element below?
Data Types - Arrays
Arrays are ordered sequences of values. Those values can be of any data type and are separated by comma. Arrays have to be declared inside braces.
var students = [ "John" , "Mary", "Paul" ];
var primeNumbers = [ 2, 3, 5, 7, 11, 13 ];
Like strings, arrays also have length and their elements have their own indexes.
students = [ "John" , "Mary", "Paul" ];
console.log(students.length); // The console will show 3
console.log(students[0]); // The console will show "John"
Array elements can also be arrays and objects.
var groups = [
[ "John" , "Mary" ],
[ "Peter" , "Joana", "Andrew", "Julio" ],
[ "Caroline" , "Helen", "Mark" ]
];
This was an example of a multidimensional array. Can you guess what is the length of the groups array?
The groups array has 3 elements.
console.log(groups.length); // The console will 3
console.log(groups[1]); // The console will [ "Peter" , "Joana", "Andrew", "Julio" ]
/* We can access arrays inside arrays by adding the index notation as many times as needed */
console.log(grupos[1][2]); // The console will "Andrew"
Array operations
var courses = [ "HTML", "Python", "PHP" ];
courses.push("Javascript");
console.log(courses); // The console will show [ "HTML", "Python", "PHP", "Javascript" ]
courses.unshift("Bootstrap");
console.log(courses); // The console will show [ "Bootstrap", "HTML", "Python", "PHP", "Javascript" ]
courses.pop();
console.log(courses); // The console will show [ "Bootstrap", "HTML", "Python", "PHP" ]
courses.shift();
console.log(courses); // The console will show [ "HTML", "Python", "PHP" ]
It's also possible to redefine elements using the index notation
var ingredients = [ "bread", "cheese", "ham" ];
ingredients[0] = "whole bread";
console.log(ingredients); // The console will show [ "whole bread", "cheese", "ham" ]
The slice method extracts part of an array. We do it by choosing a start and an end index (end element not included).
var students = [ "Peter" , "Joana", "Andrew", "Julio", "Kate", "Marie" ];
console.log( students.slice(0,3) );
// The console will show [ "Peter" , "Joana", "Andrew" ]
By omitting second value we go until the last element with it included.
var students = [ "Peter" , "Joana", "Andrew", "Julio", "Kate", "Marie" ];
console.log( students.slice(3,) );
// The console will show ["Julio", "Kate", "Marie"]
We can also use negative numbers to start counting backwards from the end of an array. To get the last three elements of an array we do:
var students = [ "Peter" , "Joana", "Andrew", "Julio", "Kate", "Marie" ];
console.log( students.slice(-3,) );
// The console will show ["Julio", "Kate", "Marie"]
Data Types - Objects
Objects, like arrays, are lists of elements. But unlike arrays, objects are not ordered. Instead of identifying elements by index, we identify them by key. So an object is a list of key / value pairs separated by colon (:).
Objects have to be declared inside curly braces { }.
var employee = {
'name': 'James Taylor',
'yearOfBirth': 1948,
'ID': 'SBJ0001',
'role': 'IT Analyst'
};
Objects keys are also called properties. To access the properties we can use braces or the dot notation:
console.log( employee['ID'] ); // The console will show 'SBJ0001'
console.log( employee.ID ); // Same thing using the dot notation
Important: the dot notation only works with properties that follow the variables naming rules.
var test = {
'property1': 'Some value',
'2a': 'Some other value',
09335: 'Another value',
'hello-world': 'Last value'
};
// 'property1' can be retrieved using the dot notation:
console.log( test.property1 ); // The console will show 'Some value'
// The other ones can't because they don't follow the naming rules. They can only be retrieved with braces.
console.log( test['hello-world'] ); // The console will show 'Last value'
We can alter values assigned to properties and add new properties.
var employee = {
'name': 'James Taylor',
'yearOfBirth': 1948,
'ID': 'SBJ0001',
'role': 'IT Analyst'
};
employee.role = 'IT Manager'; // alter a value
employee.passport = 'KV09888'; // add a new property
console.log(employee);
/* The console will show:
{
'name': 'James Taylor',
'yearOfBirth': 1948,
'ID': 'SBJ0001',
'role': 'IT Manager',
'passport': 'KV09888'
};
*/
From now on you'll commonly work with multidimensional arrays and objects mixed together. We just need to pay attention to their structure (braces and curly braces) and use the correct indentation so it's easy to interpret them.
var courses = [
{
'title': 'Learn code in Python 3',
'reviews': 6802,
'students': 130129,
'categories': ['programming', 'technology']
},
{
'title': 'Learn PHP - Beginner to Advanced',
'reviews': 1204,
'students': 30521,
'categories': ['web development', 'programming']
},
{
'title': 'Learn Microsoft Excel 2020',
'reviews': 4209,
'students': 18560,
'categories': ['productivity', 'business']
}
];
Some other aspects worth remembering:
- Arrays are identified by braces [ ].
- Arrays are ordered lists of values separated by comma.
- Objects are identified by curly braces { }.
- Objects elements are key / value pairs separated by colon.
- Objects elements are separated by comma.
Therefore we can conclude the following:
- The courses variable is an array containing 3 elements.
- The elements of courses array are objects.
- Each of these objects has 4 elements
- The objects have values of different data types. Strings ('title'), numbers ('reviews' and 'students') and arrays ('categories')
How do we get to the 'web development' category of the PHP course then?
console.log( courses[1]['categories'][0] );
We can use this 'path' to alter the value:
courses[1]['categories'][0] = 'full stack web development';
console.log( courses[1]['categories'][0] ); // The console will show ['full stack web development', 'programming']
Objects methods
Objects values can be functions. In this case we call them methods. Methods can use other object properties using the keyword this.
var student = {
'firstName': 'Marie',
'lastName': 'Smith',
'fullName': function() {
return this.firstName + ' ' + this.lastName;
}
}
console.log( student.fullName() ); // The console will show 'Marie Smith'
Important:
- Note that functions declared inside objects don't need names after the function keyword. To invoke them we use the name of the property, in this case fullName.
- We can only use the dot notation to invoke methods. We can't do student[fullName()]
Did you know that everything in Javascript is an object?
Javascript is an object oriented programming language so it treats basically everything as an object.
Objects, arrays, functions and everything except for the primitive data types, are objects.
Although the strings and numbers primitives are not considered to be objects, they have methods and other object-like features.
Let's recap a few times we worked with methods:
console.log('Hello World'); // log is a method of the console object
Math.round(2.7); // round is a method of the Math object
var num = 3;
var num_string = num.toString(); // toString is a method that can be applied to different data types.
document.getElementById("caixa_azul").innerHTML; // getElementById is a method of the document object.
// innerHTML is a property of the object returned by the get method.
var courses = [ "HTML", "Python", "PHP" ];
courses.push("Javascript"); // push is a method of the array data type.
We won't dive deeper into this subject now but you can learn more here.
Events
When we talk about events in Javascript, it's about actions that happen inside the browser. Let's see a few examples of events:
Event | Description |
---|---|
onclick | When the user clicks (PCs) or touches (mobile devices) an element in the page. |
onchange | When an HTML element changes. It's commonly used with form fields. |
onmouseover | When the user moves the cursor over an element. |
onmouseout | When the user moves the cursor out of an element. |
onkeydown | When some key is pressed. |
We can tell the browser which function should be executed when those events are detected. This will open a new door for us because now we'll be able to interact with the user.
HTML:
<button id="click-me">Click here</button>
<button id="hover-me">Move the cursor over here</button>
<button id="leave-me">Move the cursor out of here</button>
Javascript:
document.getElementById("click-me").onclick = function() {
alert('You clicked the button');
};
document.getElementById("hover-me").onmouseover = function() {
alert('You moved the cursor over the button');
};
document.getElementById("leave-me").onmouseout = function() {
alert('You moved the cursor out of the button');
};
onkeydown
The onkeydown event can be applied to a specific element like a form field, or to the document object. Let's see the example below.
document.onkeydown = function() {
alert('You pressed a key');
};
It's also possible to monitor only a specific key. First we need to know how Javascript recognizes which key has been pressed. For this let's use the event object to get some information about it:
document.onkeydown = function(event) {
alert('You pressed the following key: ' + event.keyCode);
};
The keyCode property returns the Unicode of the pressed key.
This way we can see that the code for letter 'a' is 65. With this information we can create something that will only fire when this specific key has been pressed.
document.onkeydown = function(event) {
if(event.keyCode == '65') {
alert("Do something if letter 'a' is pressed.");
}
};
Event manipulation via html attribute
In the examples above we've been using the dom elements to set the events in the Javascript code. We can also set those events using HTML attributes:
<button onclick="show_alert()">Click here</button>
Now we just need to create the function to be executed when the event is detected.
function show_alert() {
alert('You clicked the button');
}
document.getElementById("color_button").onclick = function() {
document.getElementById("color_button").style['background-color'] = "purple";
document.getElementById("color_button").style.transform = "translateX(100px)";
};
More getElement methods
Up to this point we only used the getElementById to select elements. Now let's explore a few other methods.
getElementsByClassName
This method selects elements by class. The difference now is that classes are not unique, we can have multiple elements sharing the same class. Therefore, this method will always return an array containing the HTML elements that have that class.
<div class="example">Element #1</div>
<div class="example">Element #2</div>
<div class="example">Element #3</div>
Element #1Element #2Element #3
var elements = document.getElementsByClassName("exemplo");
console.log(elements);
// The console will show an array: [ {...}, {...}, {...} ]
// Each of the elements of the array are the HTML elements that share that class
These elements can be accessed by the index, in thsi case [0], [1] and [2]. By using the index, we can manipulate their content:
elements[0].innerHTML = "Changing the text of the first element";
getElementsByTagName
This methods works just like the previous one, but this time we'll select element using the tag name (div, h1, p, img, etc).
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
Paragraph 1
Paragraph 2
Paragraph 3
var paragraphs = document.getElementsByTagName("p");
console.log(paragraphs);
// The console will show an array: [ {...}, {...}, {...} ]
Now, using the index to alter these elements doesn't seem to be very efficient. How can we make changes to all of these elements no matter how many of them exist in the page?
The answer is: Loops! The subject of our next lesson.
For and For/In Loops
Loops are structures of repetition. If we want to repeat a statement five times, we don't have to write it five times, we just need to run a loop.
We can also use loops to run through the elements of an array. No matter the size of the array, we just need to write the statements once.
For loop
for (var a = 0; a < 5 ; a+=1) {
console.log(a);
}
/* The console will show:
0
1
2
3
4
*/
Note that we just used three statements separated by semicolon to start the loop. The between curly braces we wrote the code to be executed at each iteration of the loop.
Let's understand those three statements inside parenthesis:
- var a = 0: The first statement is executed one time before the loops starts. In this case we start a variable and assign zero to it.
- a < 5: The second statement is a condition that need to return true so the loop continues to be executed. When the condition return false, the loop will stop running.
- a+=1: The third statement is executed at the end of each iteration. In this case we use it to increment the value of the variable on each iteration. This prevents our loop from running forever and killing the browser.
Using the loop to run through the elements of an array
The run throught the elements of an array we'll use its length in the condition:
var students = ['Peter', 'Mary', 'Joseph', 'John', 'Charles'];
for (var a = 0; a < students.length ; a++) {
console.log(students[a]);
}
/* The console will show:
Peter
Mary
Joseph
John
Charles
*/
For/In Loop
The for/in loop comes handy when we need to run through objects, since this kind of data type doesn't have the length property.
O funcionamento dele é bem simples. Consideremos um objeto de alunos, cujas chaves são as matrículas e os valores são os nomes dos alunos.
To initialize this loop we just need to create a variable that will represent each of the objects's properties at each iteration.
var car = {
'Year': 2018,
'Model': 'Evoke',
'Manufacturer': 'Land Rover',
'FuelType': 'Diesel'
}
for (var prop in car) {
console.log( prop + ': ' + car[prop] );
}
/* The console will show:
Year: 2018
Model: Evoke
Manufacturer: Land Rover
FuelType: Diesel
*/
Loops and the getElementBy methods...
Now that we know how loops work, let's change the css of all elements of our page that share a specific class.
<div class="example">Element 1</div>
<div class="example">Element 2</div>
<div class="example">Element 3</div>
var elements = document.getElementsByClassName("example");
for (var a = 0; a < elements.length ; a+=1) {
elements[a].style.color = "orange";
elements[a].style['font-weight'] = "bold";
}
The incremental operator can also be written like: a++.
var elements = document.getElementsByClassName("example");
for (var a = 0; a < elements.length ; a++) {
elements[a].style.color = "orange";
elements[a].style['font-weight'] = "bold";
}
While and Do/While Loops
The While and Do/While Loops are similar to the for loops, but the way we write them is a bit different.
While loop
var count = 0;
while (count < 5) {
console.log(count);
count++;
}
/* The console will show:
0
1
2
3
4
*/
The logic is the same but just the condition is written inside parenthesis. The startinf variable (var count = 0) needs to be declared before writing the loop and the incremental operator should be written inside the loop.
Do/while loop
The do/while loop works the same way, the only difference is that the condition is written at the end of the loop. This means that this loop always runs at least once, before testing the condition.
var count = 10;
do {
console.log(count);
count++;
} while (count < 5); // This loop requires the semicolon after the condition.
// The console will show: 10
Note that the condition never returned true, but since the validation is only done at the end of the first iteration, we were able to run the loop one time before testing the condition.
Conditionals
Conditionals are used to determine if a block of code should or should not be executed depending on a given set of conditions.
if / else if / else
Let's start with a simple example of checking the age of a person.
var age = 17;
if (age < 18) {
console.log('Underage');
} else {
console.log('Overage');
}
// The console will show: 'Underage'
In this example we only have one condition and if it's not true we jump directly to the else statement. But we could have more conditions by using else if statements.
var age = 70;
if (age < 18) {
console.log('Underage');
} else if (age >= 65) {
console.log('Senior');
} else {
console.log('Adult');
}
// The console will show: 'Senior'
No matter how many conditions we write, when one condition returns true, all the other conditions are ignored by Javascript. If none of the conditions return true, the code inside the else statement will be executed, although the else statement is not mandatory.
Testing multiple conditions at once with and / or
Let's analyze the grade and absences of a student and determine if he's been approved in the course. To be approved the student needs the grade to be 7 or higher and the number of absences to be 5 or lower.
grade = 7;
absences = 3;
// Solving the problem with && (and):
if (grade >= 7 && absences <= 5) {
console.log( 'The student has been approved' );
} else {
console.log( 'The student has failed' );
}
// Solving the problem with || (or):
if (grade < 7 || absences > 5) {
console.log( 'The student has failed' );
} else {
console.log( 'The student has been approved' );
}
// Both ways are correct
// change the values of the variables to test
Evaluating values as conditions
In Javascript, just like Python, PHP etc., we can evaluate values as true or false without booleans. Javascript considers to be false:
All other values, numbers, strings, objects and arrays are considered to be true.
Therefore, it's common to use conditionals like this:
var name = "";
if (name) {
console.log("The name is " + name);
} else {
console.log("The name has not been informed");
}
// The console will show "The name has not been informed"
// This method could be used to test if a form field is empty, for example
Ternary If
There's another way of writing conditionals using the ternary notation.
The syntax is: condition ? code to be executed if true : code to be executed if false;
So rewriting the example above we have:
var name = "";
console.log( name ? "The name is " + name : "The name has not been informed" );
// As you can see, we can write less code to get to the same result.
Using else if in ternary conditionals
We can declare else if statements with the ternary notation by placing the next condition where the else would be and then just continuing with the same structure.
The syntax is: condition ? code to be executed if true : another condition ? code to be executed if true : code to be executed if false;
Let's rewrite the age example from above.
var age = 70;
console.log( age < 18 ? 'Underage' : age >= 65 ? 'Senior' : 'Adult' );
This time the fewer lines of code we achieve comes with a trade-off: We are making the code readability worse. For this reason, ternary conditionals should be used only for simple if / else structures.
Nested loops and conditionals
When we use loops inside loops or conditionals inside conditionals, this is called nesting. Let's see a few examples below:
Nested conditionals
Suppose our page receives two pieces of information about a person, her age and membership status (member / not a member). Then we need to show the price of a product based on the following rules:
We can start testing if age >= 65 or if the person is a member, in this case the product is free. If not, we then need to start another conditional because we still have two price possibilities.
var isMember = false;
var age = 25;
if (isMember == true || age >= 65) {
console.log('Free');
} else {
if (age < 18) {
console.log('$ 6.00');
} else {
console.log('$ 12.00');
}
}
// The console will show: $ 12.00'
Nested Loops
When dealing with multidimensional arrays and objects, it is fairly common to use nested loops.
Let's use an employees list as an example.
var employees = [
{
'name': 'Charles Silva',
'age': 45,
'children': ['Andrew Silva', 'Maria Silva']
},
{
'name': 'Elizabeth Green',
'age': 32,
'children': ['Peter Green']
},
{
'name': 'George Banks',
'age': 39,
'children': ['Philipp Banks', 'Rose Banks', 'Tara Banks']
}
];
<p>
List of Employees' Children:
<ul id="children">
</ul>
</p>
Can you send the list of all employees' children to the list above?
document.getElementById("children").innerHTML = "";
for (var a = 0; a < employees.length; a++) {
var childrenList = employees[a].children;
for (var b = 0; b < childrenList.length; b++) {
var child = childrenList[b];
document.getElementById("children").innerHTML += "" + child + " ";
}
}
List of Employees' Children:
- Print the names inside these li's
Variable Scope
Variable scope defines the accessibility of a variable from different parts of the code. There are two main scopes in Javascript: Global and Local.
Local scope
Functions in Javascript have their own local scope. This means that variables created inside functions cannot be accessed from outside the function.
function create_name() {
var name = 'Mary';
console.log(name);
}
create_name(); // The console will show 'Mary'
console.log(name); // The console will show an error because
// we don't have access so the name variable.
Global Scope
Variables created outside functions belong to the global scope and can be accessed from anywhere in the code, including from inside functions.
var name = 'Helen';
function show_name() {
console.log(name);
}
show_name(); // The console will show 'Helen'
Variables created without the var keyword also belong to the global scope, even if they were created inside functions.
This is something that should only be done intentionally as it can result in errors in your program that can be hard to spot.
function create_name() {
name = 'Mary';
console.log(name);
}
create_name(); // The console will show 'Mary'
console.log(name); // The console will show 'Mary'
Local scope inside blocks (loops, conditionals, etc.)
Before version ES6 (ECMAScript 2015), only functions had their own local scope. ES6 introduced a new keyword called let which creates a local scope inside these blocks.
var a = 0;
if (true) {
let a = 20;
}
console.log();
console.log(a); // This will return 0, because a was created as
// a local variable inside the block
An example with problems with variable scope on nested loops:
for (var a = 0; a < 3 ; a++) {
console.log('Parent loop count: ', a);
for (var a = 0; a < 3 ; a++) {
console.log('Child loop count: ', a);
}
}
By running the above code we can see that the a variable used inside the child loop affected the variable of the parent loop, because they have the same names and variable created inside loops are accessible from outside of it.
To solve this, we can use the let keyword.
for (let a = 0; a < 3 ; a++) {
console.log('Parent loop count: ', a);
for (let a = 0; a < 3 ; a++) {
console.log('Child loop count: ', a);
}
}
Now the loops are working fine.
ATTENTION: ES6 features are not compatible with some versions of Internet Explorer (IE), therefore this keyword should not be used in front end web development projects.
To maintain full compatibility, it's recommended to change the names of variables when working with nested loops.
for (var a = 0; a < 3 ; a++) {
console.log('Parent loop count: ', a);
for (var b = 0; b < 3 ; b++) {
console.log('Child loop count: ', b);
}
}
The const keyword - for constants
ES6 also introduced a new keyword called const. Like let, they also belong to the local scope. The difference is that we can't change constants values.
const PI = 3.14159;
PI = 0; // This will result in error because we can't change the constant's value.
// Why would we want to change PI's value anyway?
By using constants when they are appropriate we add more security to our code, because when there's an attempt to change them, an error raised will indicate something is wrong. But please note that constants will also break in some versions of IE.
BOM - Browser Object Model
The Browser Object Model represents the browser window. Through this object we can interact with certain properties of the browser, like the width of the window, cursor position, scroll bar, etc.
While the DOM is accessed through the document object, the BOM is accessed through the window object.
console.log( window.innerWidth );
/* This property returns the internal width of the browser's window */
Thw window object can be omitted:
console.log( innerWidth );
However, it is recommended to mention the window object to avoid confusion with variables. Unless for specific methods that are very well known and unique enough not to be confused with variables and your own functions, like the alert method:
alert( "Message" );
// this is actually:
window.alert( "Message" );
Or the console.log:
window.console.log("this works");
Global variables are also stored in the window object:
var myName = "Tom";
console.log(window.myName);
This means that if you create a new variable called innerWidth, it's going to overwrite the original property from the window object, so be extra careful when naming variables. See here a list of all window properties and methods.
There are many interesting things we can do with the BOM, let's see one example below:
window.onmousemove
The onmousemove event tracks the cursor movement around the browser's window. Let's use it to show a message when the cursor is at a specific position relative to the top of the window.
window.onmousemove = function(e){
if (e.pageY < 5) {
alert("Don't miss our flash sale. Go to the the products section for exclusive discounts.");
}
};
In the next lessons we'll explore more features of the window object.
Date & Time
In Javascript we can easily work with Date & Time using the Date class. To create an object of this type we use the new keyword, something that will be further explained later.
// Creating a Date object
var dateObj = new Date();
console.log(dateObj);
By doing this, we create an object with the current date and time formed by weekday, month, day, year, hours, minutes, seconds and timezone.
Methods of the Date object
Method | Description |
---|---|
getDate() | Returns the day of the month (1 to 31) |
getDay() | Returns the weekday (0 - Sunday to 6 - Saturday) |
getFullYear() | Returns the full year (YYYY) |
getMonth() | Returns the month (0 to 11) |
getHours() | Returns the hours (0 to 23) |
getMinutes() | Return the minutes (0 to 59) |
getSeconds() | Returns the seconds (0 to 59) |
getMilliseconds() | Returns the milliseconds (0 to 999) |
getTime() | Returns the number of milliseconds since the Epoch(Jan 1st, 1970, 00:00:00) |
setTime() | Creates a specific date from milliseconds since the epoch. |
Unix Epoch
The Epoch is something present in most programming languages. We can consider it the starting point of counting the time. This is useful to do calculations with date and time.
Javascript uses the Unix Epoch, which is: Jan 1st, 1970, 00:00:00, UTC.
var dateObj = new Date();
console.log(dateObj.getTime());
The getTime() method returns the number of milliseconds since the Epoch (Remember that 1 second = 1000 milliseconds). See the table below for a few conversions done with milliseconds:
Time | Milliseconds (ms) |
---|---|
1 second | 1.000 |
1 minute | 60.000 |
1 hour | 3.600.000 |
1 day | 86.400.000 |
1 year (365 days) | 31.536.000.000 |
How to calculate how many hours have passed since the Epoch?
var dateObj = new Date();
dateObj = dateObj.getTime();
var hours = dateObj / 3600000;
console.log(Math.floor(hours));
How to create specific dates
In the examples above we created date objects without passing any arguments, this is why they represented the current time. But we can also pass arguments to create specific dates.
var dateObj = new Date(2020,2,18);
console.log( dateObj );
We can also pass strings as arguments in three different formats:
var dateObj = new Date("2020-03-18");
console.log( dateObj );
Challenge: Calculating date intervals
If a product is ordered on March 26, 2020 and delivered on April, 02, 2020, how many days does it take to be delivered?
Time methods
The window object has two methods that allow us to delay the execution of a block of code or execute it repetitively between an interval of time.
setTimeout
The setTimeout function accepts two arguments: the function that should be executed after the stipulated time and the stipulated time in milliseconds.
This function passed as an argument is a callback function, something that will be further explained later in the course.
window.setTimeout(callback function,time in milliseconds)
Let's send one message to the console, wait 3 seconds, then send another.
console.log("Message 1");
window.setTimeout(function() {
console.log("Message 2");
},3000);
Another example would be showing an element for a given period of time, let's say a spinner loader.
document.getElementById("show-loader").onclick = function () {
document.getElementById("spinner-loader").style.display = "block";
window.setTimeout(function(){
document.getElementById("spinner-loader").style.display = "none";
}, 5000);
};
setInterval
The SetInterval method is similar to the setTimeout, the difference is that it keeps repeating the callback function forever, unless you stop it.
var count = 0;
window.setInterval(function(){
console.log(count);
count++;
}, 1000);
Interrupting time methods
Both setTimeout and setInterval can be interrupted. To do this we need to assign them to a variable and then use the clearTimeout or clearInterval respectively.
Let's limit the above code to 5 seconds:
var count = 0;
var timeInterval = window.setInterval(function(){
console.log(count);
count++;
if (count > 5) {
window.clearInterval(timeInterval);
}
}, 1000);
The clock challenge
Use the Date object and the setInterval methods to make the clock below work in real time.
Break and Continue
The break and continue statements are used mainly with loops and their purpose is either to interrupt the loop or just jump the current iteration.
Break
The break statement interrupts the loop execution or a switch statement:
var x = 0;
while (x < 10) {
console.log(x);
x++;
if (x == 5) {
break;
}
}
In the above example we interrupted the loop before its condition (x < 10) returned false. Neste exemplo, conseguimos interromper o loop antes de atingir a condição (x < 10). This is just a simple example, but in some cases it could be very useful to interrupt a loop when something specific happens.
Continue
The continue statement is used to jump the current iteration of a loop.
Let's create a loop that will print only the even numbers from 0 to 20. First let's learn about the modulus operator (%).
This operator return the remainder of a division, so for instance if we do 6 % 4 the result is 2, which is the remainder of this division.
This means that we can use this operator to find out if a number is odd or even. The division of any even number by 2 produces no remainder while the division of any odd number by 2 always produce a remainder of 1. Therefore:
var num = 0;
while (num < 20) {
num++;
if (num % 2 != 0) {
continue;
}
console.log(num);
}
Forms
Knowing how to handle forms is an essential skill in web development. In this lesson we'll learn how to work with form fields.
Retrieving the value of a field
Earlier in the course we've learned how to get the value from input fields unsing the value property. Now let's see how to get the vaues of different types of fields.
Select Box
Show the selected options here:
document.getElementById("show_option").onclick = function () {
var selectField = document.getElementById("options");
var selectedOption = selectField.options.selectedIndex;
var selectedValue = selectField.options[selectedOption].innerHTML;
document.getElementById("selected_option").innerHTML = selectedValue;
};
There's an easy way of doing this, since select boxes have a value property that stores the value of the selected option. However with this method we can only get the value, not the inner html.
var selectedOption = document.getElementById("options").value;
console.log(selectedOption);
Besides getting the selected valur from a select box, we can also use Javascript to force the selection of an option. We do this by defining the value attribute.
document.getElementById('options').value = "opt3";
Radio Buttons
Show the selected option:
document.getElementById("show_radio").onclick = function () {
var radio = document.getElementsByName("gender");
var radio_selected;
for (var a = 0; a < radio.length; a++) {
if (radio[a].checked) {
radio_selected = radio[a].value;
}
}
document.getElementById("selected_radio").innerHTML = radio_selected;
};
CheckBoxes
Show a list of the selected options:
document.getElementById("Show_check").onclick = function () {
var check = document.getElementsByName("interest");
document.getElementById("selected_check").innerHTML = "";
for (var b = 0; b < check.length; b++) {
if (check[b].checked) {
document.getElementById("selected_check").innerHTML += '<li>' + check[b].value + '</li>';
}
}
};
The onchange event
In the previous lesson we were getting values from form fields and showing them after pressing a button. We can also do it without buttons, by monitoring changes to the form fields.
Show the selected options here:
document.getElementById("education_level").onchange = function () {
var selectField = document.getElementById("education_level");
var selectedOption = selectField.options.selectedIndex;
var selectedValue = selectField.options[selectedOption].innerHTML;
document.getElementById("selected_level").innerHTML = selectedValue;
};
The other field types can also be monitored with the onchange event, we just need to pay attention to which element is changing. Radio buttons and checkboxes have multiple items, so we need to apply the event to each of the items using a loop:
Show the items selected:
var check = document.getElementsByName("meal");
for (var a = 0; a < check.length; a++) {
check[a].onchange = function () {
document.getElementById("selected_check").innerHTML = "";
for (var b = 0; b < check.length; b++) {
if (check[b].checked) {
document.getElementById("selected_check").innerHTML += '<li>' + check[b].value + '</li>';
}
}
}
}
Difference between radio and check is radio can only have one value but check can have more than one value.
The onchange event
In the previous lesson we were getting values from form fields and showing them after pressing a button. We can also do it without buttons, by monitoring changes to the form fields.
Show the selected options here:
document.getElementById("education_level").onchange = function () {
var selectField = document.getElementById("education_level");
var selectedOption = selectField.options.selectedIndex;
var selectedValue = selectField.options[selectedOption].innerHTML;
document.getElementById("selected_level").innerHTML = selectedValue;
};
The other field types can also be monitored with the onchange event, we just need to pay attention to which element is changing. Radio buttons and checkboxes have multiple items, so we need to apply the event to each of the items using a loop:
Show the items selected:
var check = document.getElementsByName("meal");
for (var a = 0; a < check.length; a++) {
check[a].onchange = function () {
document.getElementById("selected_check").innerHTML = "";
for (var b = 0; b < check.length; b++) {
if (check[b].checked) {
document.getElementById("selected_check").innerHTML += '<li>' + check[b].value + '</li>';
}
}
}
}
jQuery - Introduction
jQuery is a Javascript library (or framework) that simplifies the language. With jQuery we need less lines of code than if we were using pure Javascript.
Let's see a basic example of changing the background of all elements that have a given class:
Vanilla Javascript*:
var elements = document.getElementsByClassName("example");
for (var a = 0; a < elements.length; a++) {
elements[a].style['background-color'] = "black";
}
* Vanilla Javascript is the name used for pure javascript, with no libraries.
jQuery:
$(".example").css("background-color", "black");
With jQuery we can manipulate the DOM and the CSS of elements, track events, create effects and animations etc.
jQuery runs on all browsers and you can find thousands of plugins online that are based on jQuery. With those plugins you easily create photo gallery, grids, sliders, popups, form validation and much more.
Installing jQuery
To start using jQuery we need to download the .js file that contains all the code for the library. To to this, go to https://jquery.com/download/.
You can download the most recent compressed production on version, or use a CDN link.
For this course we'll use the CDN version because it's easier to set-up. For your projects it's always good to have all files in your own server.
Now we just need to make the link on our pages, just like we do it with Javascript.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
In the beginning of the course we learned that we should always place the script for our javascript files at the end of the body element, right before closing it.
But the link to jQuery is better to include in the head element of our page. This is because many components of our page might depend on jQuery to run, like the plugins mentioned above. So we need to make sure that it's loaded before any other javascript file.
Now that we have jQuery loaded in our html pages, let's start exploring it. In the next lesson we'll start learning the basic functions of
jQuery - Introduction
jQuery is a Javascript library (or framework) that simplifies the language. With jQuery we need less lines of code than if we were using pure Javascript.
Let's see a basic example of changing the background of all elements that have a given class:
Vanilla Javascript*:
var elements = document.getElementsByClassName("example");
for (var a = 0; a < elements.length; a++) {
elements[a].style['background-color'] = "black";
}
* Vanilla Javascript is the name used for pure javascript, with no libraries.
jQuery:
$(".example").css("background-color", "black");
With jQuery we can manipulate the DOM and the CSS of elements, track events, create effects and animations etc.
jQuery runs on all browsers and you can find thousands of plugins online that are based on jQuery. With those plugins you easily create photo gallery, grids, sliders, popups, form validation and much more.
Installing jQuery
To start using jQuery we need to download the .js file that contains all the code for the library. To to this, go to https://jquery.com/download/.
You can download the most recent compressed production on version, or use a CDN link.
For this course we'll use the CDN version because it's easier to set-up. For your projects it's always good to have all files in your own server.
Now we just need to make the link on our pages, just like we do it with Javascript.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
In the beginning of the course we learned that we should always place the script for our javascript files at the end of the body element, right before closing it.
But the link to jQuery is better to include in the head element of our page. This is because many components of our page might depend on jQuery to run, like the plugins mentioned above. So we need to make sure that it's loaded before any other javascript file.
Now that we have jQuery loaded in our html pages, let's start exploring it. In the next lesson we'll start learning the basic functions of
syntax Parser:
a program that reads your code and determines what it does and it its grammar is valid.
Your code isn't magic someone else wrote a program to translate it for the computer.
lexical environment: where something sits physically in the code you write
'lexical' means having to do with words or grammar. A lexical environment exists in programming languages in which where you write something is important
execution context: A wrapper to help manage the code that is running
there are lots of lexical environments. Which one is currently running is managed via execution contexts. It can contain things beyond what you've written in your code.
Objects , Name/ value pairs is a name which maps to a unique value
the name may be defined more than once, but only can have one value in any given context.
That value may be more name/ value pairs
Object is simply collection of name value pairs
execution context(Global)
execution context creates 2 things for us 1)Global object & 2) this(special variable)
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
There are altogether 2 phase
1) Creation Phase
2) Execution Phase
Execution Context is Created (CREATION PHASE): Set up the variable and function in memory
Global object this outer Environment
Undefine is never define value for a variable
In execution phase everything is setup and is easy to understand
here code we have written is run line by line interpreting ,controlling ,compiling and executing code.
single Threaded means one command at a time
Synchronous execution means one at a time
Function Invocation simply means running or calling a function
Execution Stack
any time you execute function in JS new execution context is created and is kept in execution stack
funcion two(){
console.log(v);
}
function one(){
var v=2;
two();
}
var v=1;
a();
output in console will be
1
where function sits determines its outer environment references but as it's being executed those execution contexts are stacking up and it's running synchronously
scope is where variable is available in your code
let is similar to var it is used for block scoping
if you execute to execute variable before let we will get error. It is still in memory but engine don't allow it.
namespace is a container for variables and functions. It keep variable and function with the same name separate
Function are objects in JavaScript.
every thing you can do with other types you can do with functions.
assign them to variable ,pass them around ,create them on the fly
function is a special type of object
Expression is a unit of code that result in a value. It doesn't have to save to a variable.
OBJECT-ORIENTED JAVASCRIPT
inheritance means getting some features or characters from others.
in JS , one object gets access to the properties and methods of another object with inheritance
PROPTOTYPAL INHERITAANCE
classical vs prototypal inheritance
classical inheritance is inheritance done for long time in different popular programming language. It is very verbose.
Prototypal Inheritance is
- simple
- extensible
- easy to understand
Comments
Post a Comment