Ephrem__Tesfaye__IP-I__Chapter__Four__Note__&__Question (2)
Ephrem__Tesfaye__IP-I__Chapter__Four__Note__&__Question (2)
Topic Contents
4. JavaScript Basics
4.1 Client side scripting and its advantage
4.2 Advantages and limitations of JavaScript
4.3 JavaScript basic syntax
4.4 Flow control in JavaScript
4.5 Event handler in JavaScript
Objectives
After studying this chapter, you should be able to:
Discuss what scripting language is and differentiate it from programming languages
Understand what client side scripting is and use JS as a client side scripting language
Understand the basic syntax of JS
Solve different programming problems using JS and develop algorithmic thinking
Manipulate the DOM
Handle user events and respond appropriately for the user’s actions
Fast editing: It is particularly efficient since it uses a small amount of data structures and
variables.
Interactivity: It helps to make web pages more interactive by adding combinations and
visualization interfaces. The use of scripting languages is demanded by modern web pages.
It includes background and foreground colors and so on, which helps to create enhanced
web pages.
Functionality: Scripting languages contain different libraries, which help to create new
applications in web browsers. They are different from normal programming languages.
Types of Scripting Languages
There are two main types of scripting languages: server-side and client-side. They differ on where
the code is run from, which affects not only the actual languages chosen but also the performance
and their capabilities.
Server-side scripting language
The term server-side scripting language refers to those that run off a web server. Since it performs
from the back-end side, the script is not visible to the visitor. Because of that, it is a more secure
approach.
They are often used to create dynamic websites and platforms, handle user queries, and generate
and provide data and others. A famous example of server-side scripting is the use of PHP in
WordPress.
Examples: PHP, Python, Node.js, Perl, and Ruby.
Client-side scripting language
Unlike the above, client-side scripting languages run off the user’s browser. It is usually performed
at the front end, which makes it visible to visitors and makes it less vulnerable to exploits and
leaks. As such, it is often used to build user interfaces and lighter functionality such as that.
Since it runs locally, they usually provide better performance and, therefore, do not strain your
server.
Examples: JavaScript.
Client-side scripting generates code that may be executed on the client end without needing server-
side processing. These scripts are typically embedded into HTML text. Client-side scripting may
be utilized to check the user's form for problems before submitting it and to change the content
based on the user input.
Client-side scripting is mostly utilized to create dynamic user interface elements like pull-down
menus and animation buttons, navigation tools, data validation, and more. Nowadays, it is
increasing and evolving every day. This means that writing web programming for clients is now
much easier and quicker and, in turn, reduces the load on servers.
Application of Client-side Scripting-
Client-side scripting can be utilized to make websites more interactive. It is typically used at the
front end, which is where users can view the web page using the browser. The most important
functions of scripting on the client side are listed below:
To retrieve information from a web browser or the user's screen.
Used in the context of online games.
To personalize the web page without having to load it again.
Client-side scripting can be used to verify credentials. If the user has entered incorrect
details when logging in, the web page will display an error message on the user's machine
and will not submit data to the website server.
To create ads that engage with users rather than just display pictures.
Create animated images that change as we move our mouse across them.
Client-side scripts can be used to check for installed plugins and notify the user that the
plugin is needed.
You’ve likely seen this in action if you’ve ever attempted to register for a website, entered a
username, and immediately received feedback that the username you’ve entered is already taken
by someone. The red border around the text input and the appearance of the “sorry, this username
is already in use” message are examples of JavaScript altering the contents of the page, and
blocking the form submission is an example of JavaScript altering the browser’s default behavior.
In short, JavaScript allows you to create highly responsive interfaces that improve the user
experience and provide dynamic functionality, without waiting for the server to load up a new
page. For example, we can use JavaScript to do any of the following:
Suggest the complete term a user might be entering in a search box as he types. You can
see this in action on Google.com
Show and hide content based on a user clicking on a link or heading, to create a
“collapsible” content area
Both advantages and disadvantages apply to JavaScript. A client's browser is frequently used to
execute JavaScript directly. Similar advantages to server-side languages are also possible for
JavaScript.
Following are the advantages of JavaScript
Simple − JavaScript is simple to comprehend and pick up. Both users and developers will find the
structure to be straightforward. Additionally, it is very doable to implement, saving web developers
a tonne of money when creating dynamic content.
Speed − JavaScript is a "interpreted" language, it cuts down on the time needed for compilation in
other programming languages like Java. Another client-side script is JavaScript, which accelerates
programme execution by eliminating the wait time for server connections. No matter where
JavaScript is hosted, it is always run in a client environment to reduce bandwidth usage and speed
up execution.
Interoperability − Because JavaScript seamlessly integrates with other programming languages,
many developers favour using it to create a variety of applications. Any webpage or the script of
another programming language can contain it.
Server Load − Data validation can be done within the browser itself rather than being forwarded
to the server because JavaScript is client-side. The entire website does not need to be reloaded in
the event of any discrepancy. Only the chosen area of the page is updated by the browser.
Following are the disadvantages of JavaScript
Cannot Debug − Although some HTML editors allow for debugging, they are not as effective as
editors for C or C++. Additionally, the developer has a difficult time figuring out the issue because
the browser doesn't display any errors.
Unexpected stop of rendering − The website's entire JavaScript code can stop rendering due to a
single error in the code. It appears to the user as though JavaScript is absent. The browsers,
however, are very forgiving of these mistakes.
Client-side Security − The user can see the JavaScript code; it could be misused by others. These
actions might involve using the source code anonymously. Additionally, it is very simple to insert
code into the website that impair the security of data transmitted via the website.
Inheritance − JavaScript does not support multiple inheritance; only one inheritance is supported.
This property of object-oriented languages might be necessary for some programmes.
Browser Support − Depending on the browser, JavaScript is interpreted differently. Therefore,
before publication, the code needs to run on various platforms. We also need to check the older
browsers because some new functions are not supported by them.
Adding JavaScript to a Page
Like CSS, you can embed a script right in a document or keep it in an external file and link it to
the page. Both methods use the script element.
Embedded script
Including JavaScript code inline:
Insert your JavaScript code directly inside the HTML tag using the special tag attributes such as
onclick, onmouseover, onkeypress, onload, etc.
<body>
<button onclick="alert('Hello World!')">Click Me</button>
</body>
Note: You should avoid placing large amount of JavaScript code inline as it clutters up your HTML
with JavaScript and makes your JavaScript code difficult to maintain
To embed a script on a page, just add the code as the content of a script element:
<script>
… JavaScript code goes here
</script>
External scripts
The other method uses the src attribute to point to a script file (with a .js suffix) by its URL. In this
case, the script element has no content.
<script src="my_script.js"></script>
The advantage to external scripts is that you can apply the same script to multiple pages (the same
benefit external style sheets offer).
Script placement
The script element go anywhere in the document, but the most common places for scripts are in
the head of the document and at the very end of the body. It is recommended that you don’t sprinkle
them throughout the document, because they would be difficult to find and maintain.
For most scripts, the end of the document, just before the </body> tag, is the preferred placement
because the browser will be done parsing the document and its DOM structure. Consequently, that
information will be ready and available by the time it gets to the scripts and they can execute faster.
In addition, the script download and execution blocks the rendering of the page, so moving the
script to the bottom improves the perceived performance.
Variables
A variable is like an information container. You give it a name and then assign it a value, which
can a number, text string, an element in the DOM, or a function—anything, really. This gives us a
convenient way to reference that value later by name. The value itself can be modified and
reassigned in whatever way our scripts’ logic dictates.
The following declaration creates a variable with the name “unity” and assigns it the value 5:
var unity = 5;
We start by declaring the variable using the var keyword. The single equals sign (=) indicates that
we are assigning it a value. Because that’s the end of our statement, we end the line with a
semicolon.
Re-declaring JavaScript variables: If you re-declare a JavaScript variable, it will not lose its
value. In the below example, the variable “width” will still have the value 20 after the execution
of these statements.
var width= "20";
Remember that a variable holds a value, and that value vary. In JavaScript, you can reassign values
to a variable you once declared with var.
When you assign a new value to a variable, you write the variable name, followed by (=) sign and
your new value.
var width = 10; (declaring a variable by the name “width” and assigning the variable
a value of 10)
width = 11; (changing or reassigning value 11 to width variable)
width = 12; (changing or reassigning value 12 to width variable)
Latest variable value always overrides the previous values: At this point, our width variable has a
value of 12 because it is the latest value.
You can use anything you like as a variable name, but make sure it’s a name that will make sense
to you later on. You wouldn’t want to name a variable something like “data”; it should describe
the information it contains. In our very specific example above, “numberFive” might be a more
useful name than “unity.” There are a few rules around variable naming:
It must start with a letter or an underscore.
It may contain letters, digits, and underscores in any combination.
It may not contain character spaces. As an alternative, use underscores in place of spaces
or close up the space and use camel case instead (for example, my_variable or myVariable).
It may not contain special characters (! . , / \ + * = etc.).
You can change the value of a variable at any time by re-declaring it anywhere in your
script. Remember: JavaScript is case-sensitive, and so are those variable names.
Data types
The values we assign to variables fall under a few distinct data types.
Undefined
The simplest of these data types is likely “undefined.” If we declare a variable by giving it a name
but no value, that variable contains a value of “undefined.”
var foo;
alert(foo); // This will open a dialog containing "undefined".
Odds are you won’t find a lot of use for this right away, but it’s worthknowing for the sake of
troubleshooting some of the errors you’re likelyto encounter early on in your JavaScript career. If
a variable has a valueof “undefined” when it shouldn’t, you may want to double-check that it
has been declared correctly or that there isn’t a typo in the variable name.
Null
Similar to the above, assigning a variable of “null” (again, case-sensitive) simply says, “Define
this variable, but give it no inherent value.”
var foo = null;
alert(foo); // This will open a dialog containing "null".
Numbers
You can assign variables numeric values.
var foo = 5;
alert(foo); // This will open a dialog containing "5".
The word “foo” now means the exact same thing as the number five as far as JavaScript is
concerned. Because JavaScript is “loosely typed,” we don’t have to tell our script to treat the
variable foo as the number five. The variable behaves the same as the number itself, so you can do
things to it that you would do to any other number using classic mathematical notation: +, -, *, and
/ for plus, minus, multiply, and divide, respectively.
In this example, we use the plus sign (+) to add foo to itself (foo + foo).
var foo = 5;
alert(foo + foo); // This will alert "10".
Strings
Another type of data that can be saved to a variable is a string, which is basically a line of text.
Enclosing characters in a set of single or double quotes indicates that it’s a string, as shown here:
var foo = "five";
alert( foo ); // This will alert "five"
The variable foo is now treated exactly the same as the word “five”. This applies to any
combination of characters: letters, numbers, spaces, and so on. If the value is wrapped in quotation
marks, it will be treated as a string of text. If we were to wrap the number five (5) in quotes and
assign it to a variable, that variable wouldn’t behave as a number; instead, it would behave as a
string of text containing the character “5.”
Earlier we saw the plus (+) sign used to add numbers. When the plus sign is used with strings, it
sticks the strings together (called concatenation) into one long string, as shown in this example.
var foo = "bye"
alert (foo + foo); // This will alert "byebye"
Notice what the alert returns in the following example when we define the value 5 in quotation
marks, treating it as a string instead of a number.
var foo = "5";
alert( foo + foo ); // This will alert "55"
If we concatenate a string and a number, JavaScript will assume that the number should be treated
as a string as well, since the math would be impossible.
var foo = "five";
var bar = 5;
alert( foo + bar ); // This will alert "five5"
Booleans
We can also assign a variable a “true” or “false” value. This is called a Boolean value, and it is the
lynchpin for all manner of advanced logic. Boolean values use the true and false keywords built
into JavaScript, so quotation marks are not necessary.
Now that we know how to save values to variables and arrays, the next logical step is knowing
how to compare those values. There is a set of special characters called comparison operators that
evaluate and compare values in different ways:
== Is equal to
!= Is not equal to
=== Is identical to (equal to and of the same data type)
!== Is not identical to
Is greater than
>= Is greater than or equal to
< Is less than
<= Is less than or equal to
There’s a reason all of these definitions read as parts of a statement. In comparing values, we’re
making an assertion, and the goal is to obtain a result that is either inherently true or inherently
false. When we compare two values, JavaScript evaluates the statement and gives us back a
Boolean value depending on whether the statement is true or false.
alert( 5 == 5 ); // This will alert "true"
alert( 5 != 6 ); // This will alert "true"
alert( 5 < 1 ); // This will alert "false"
Equal versus identical
The tricky part is understanding the difference between “equal to” (==) and “identical to” (===).
We already learned that all of these values fall under a certain data type. For example, a string of
“5” and a number 5 are similar, but they’re not quite the same thing. Well, that’s exactly what ===
is meant to check.
alert( "5" == 5 ); // This will alert "true". They're both "5".
alert( "5" === 5 ); // This will alert "false". They're both "5", but they're not the
same data type.
alert( "5" !== 5 ); // This will alert "true", since they're not the same data type.
Even if you have to read it a couple of times, understanding the preceding sentence means you’ve
already begun to adopt the special kind of crazy one needs to be a programmer. Welcome! You’re
in good company.
Mathematical Operators
The other type of operator is a mathematical operator, which performs mathematical functions on
numeric values. We touched briefly on the straightforward mathematical operators for add (+),
subtract (-), multiply (*), and divide (/). There are also some useful shortcuts you should be aware
of:
+= Adds the value to itself
++ Increases the value of a number (or a variable containing a number value) by 1
-- Decreases the value of a number (or a variable containing a number value) by 1
Logical operators
Logical operators are used to determine the logic between variables or values. Logical operators
to perform multiple comparisons. We use these operators when we want to write conditional
statements. We will learn about conditional statements later. For now, let's just focus on the
operators.
There are three logical operators in JavaScript:
Logical AND (&&): This returns true if both operands are true. Meaning, if either one of
the variables were initialized as false, the && expression would evaluate to false.
true && true = true
true && false = false
false && false = false
false && true = false
(1==1 && 2==2 && 3==7) // returns False
Logical OR (| |): The OR operator, represented by two pipes, returns true if one operand is
true
true || true = true
true || false = true
false || false = false
false || true = true
(1==1 || 3==2 || 3 == 7) // returns True
Logical not (!): This returns true if operand is false and vice versa.
! False = True
! True = False
! (1==1 || 3==2) // returns False
NB: Priority order when evaluating JavaScript operators: Priority of operator (operator
precedence) determines the grouping of terms in an expression and decides how an expression is
evaluated.
Example: var x = 2 + 3 * 4; here, x is assigned 14, not 9 because operator * has a higher precedence
than +, so it first gets multiplied with 3*4 and then adds into 2.
The following is a list showing operators that have the highest precedence on top:
Grouping: ()
Postfix increment: … ++
Postfix decrement: … --
Logical not: !
Comparison: < , >= , = = = , !=
Logical AND: &&
Logical OR: | |
Functions
I’ve introduced you to a few functions already in a sneaky way. Here’s an example of a function
that you might recognize:
alert("I've been a function all along!");
A function is a bit of code that doesn’t run until it is referenced or called. alert() is a function built
into our browser. It’s a block of code that runs only when we explicitly tell it to. In a way, we can
think of a function as a variable that contains logic, in that referencing that variable will run all the
code stored inside it.
All functions share a common pattern. The function name is always immediately followed by a set
of parentheses (no space), then a pair of curly braces that contain their associated code. The
parentheses sometimes contain additional information used by the function called arguments.
Arguments are data that can influence how the function behaves. For example, the alert function
we know so well accepts a string of text as an argument, and uses that information to populate the
resulting dialog.
There are two types of functions: those that come “out-of-the-box” (native JavaScript functions)
and those that you make up yourself (custom functions). Let’s look at each.
Native functions
There are hundreds of predefined functions built into JavaScript, including: alert(), confirm(), and
prompt() These functions trigger browser-level dialog boxes.
Date() : Returns the current date and time.
parseInt("123") : This function will, among other things, take a string data type
containing numbers and turn it into a number data type. The string is passed to the function
as an argument.
setTimeout(functionName, 5000) : Will execute a function after a delay. The function is
specified in the first argument, and the delay is specified in milliseconds in the second (in
the example, 5000 milliseconds equals 5 seconds). There are scores more beyond this, as
well.
JS Built-in Functions
Mostly Used Javascript Property for array and string
Length (returns the length of the string/array)
Example:
var a = [1,2,3,4,5];
console.log(a.length);
Mostly Used Javascript built-in functions for string operations
charAt() method: It returns the character at the specified index.
Example:
var a = [1,2,3,4,5];
console.log(a.charAt(2)); //displays “3”
indexOf() method: It returns the index within the calling String object.
toLowerCase() method: It returns the calling string value converted lower case.
toUpperCase() method: It returns the calling string value converted to uppercase.
slice() method: It extracts a session of a string and returns a new string.
split() method: It splits a string object into an array of strings by separating the
string into the substrings
Mostly used Javascript functions for array operations
push() method: Adds new elements to the end of an array, and returns the new array
pop() method:: Removes an item from the end of an array
shift() method:: Removes the first element of an array, and returns that element
unshift() method:: Adds new elements to the beginning of an array, and returns the
new array
isArray() method:: Returns true if the argument is an array, or false otherwise.
toString() method: Converts an array to a string, and returns the result
Custom functions
To create a custom function, we type the function keyword followed by a name for the function,
followed by opening and closing parentheses, followed by opening and closing curly brackets.
function name() {
// Our function code goes here.
}
Just as with variables and arrays, the function’s name can be anything you want, but all the same
naming syntax rules apply.
If we were to create a function that just alerts some text (which is a little redundant, I know), it
would look like this:
function foo() {
alert("Our function just ran!");
// This code won't run until we call the function 'foo()'
}
We can then call that function and execute the code inside it anywhere in our script by writing the
following:
foo(); // Alerts "Our function just ran!"
We can call this function any number of times throughout our code. It saves a lot of time and
redundant coding.
Arguments
Having a function that executes the exact same code throughout your script isn’t likely to be all
that useful. We can “pass arguments” (provide data) to native and custom functions in order to
apply a function’s logic to different sets of data at different times.
To hold a place for the arguments, add one or more comma-separated variables in the parentheses
at the time the function is defined. Then, when we call that function, anything we include between
the parentheses will be passed into that variable as the function executes. This might sound a little
confusing, but it’s not so bad once you see it in action.
For example, let’s say we wanted to create a very simple function that alerts the number of items
contained in an array. We’ve already learned that we can use .length to get the number of items in
an array, so we just need a way to pass the array to be measured into our function. We do that by
supplying the array to be measured as an argument. In order to do that, we specify a variable name
in the parentheses when we define our custom function. That variable will then be available inside
of the function and will contain whatever argument we pass when we call the function.
function alertArraySize(arr) {
alert(arr.length);
}
Now any array we specify between the parentheses when we call the function will be passed to the
function with the variable name arr. All we need to do is get its length.
var test = [1,2,3,4,5];
alertArraySize(test); // Alerts "5"
Returning a value
This part is particularly wild, and incredibly useful. It’s pretty common to use a function to
calculate something and then give you a value that you can use elsewhere in your script. We could
accomplish this using what we know now, through clever application of variables, but there’s a
much easier way.
The return keyword inside a function effectively turns that function into a variable with a dynamic
value! This one is a little easier to show than it is to tell, so bear with me while we consider this
example.
function addNumbers(a,b) {
return a + b;
}
We now have a function that accepts two arguments and adds them together. That wouldn’t be
much use if the result always lived inside that function, because we wouldn’t be able to use the
result anywhere else in our script.
Here we use the return keyword to pass the result out of the function. Now any reference you make
to that function gives you the result of the function—just like a variable would.
alert( addNumbers(2,5) ); // Alerts "7"
In a way, the addNumbers function is now a variable that contains a dynamic value: the value of
our calculation. If we didn’t return a value inside of our function, the preceding script would alert
“undefined”, just like a variable that we haven’t given a value.
The return keyword has one catch. As soon as JavaScript sees that it’s time to return a value, the
function ends. Consider the following:
function bar() {
return 3;
alert("We'll never see this alert.");
}
When you call this function using bar(), the alert on the second line never runs. The function ends
as soon as it sees it’s time to return a value.
Syntax: We start by using the key word "if", put the conditions within a bracket. Note that if is in
lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
if (condition) {
// write the code you want to be executed if the condition is true
}
Example:
var pass = 50;
var score = 17;
if (score >= pass) {
console.log("Hey you passed");
}
if (score <= pass) {
console.log("You failed");
}
The “else” statement
Definition: We use the “else” statement to specify a block of code to be executed when the
condition under the “if” statement is false.
Syntax:
if (condition) {
// write the code you want to be executed if the condition is true
} else {
// write the code you want to be executed if condition is false
}
Example:
var score = 82;
if (score >= pass) {
console.log("Hey you passed");
}else{
console.log("You failed");
}
break;
default:
// the code you want to be executed if expression matches value of the case
}
How it works:
The expression in a “switch statement” is evaluated only once with each case
In a “switch statement”, the comparison is between the expression and the values under
each case
If there is a match between the expression and the value of any of the cases, the code block
associated will be the one to be executed
If multiple cases match a case value, the first case is selected.
If there is no match while comparing the expression and the value of each case, the default
code will be executed
When JavaScript reaches a break keyword, it breaks out of the switch block. This will stop
the execution inside the switch block. Note: It is not necessary to break the last case in a
switch block. The block breaks (ends) there anyway
Default clause in switch statement works as the same as else clause in if else block. The
“default” keyword specifies the code to run if there is no match between the condition and
the expression.
The default statement doesn't have to come at the end. It may appear anywhere in the body
of the switch statement.
If no default label is found, the program continues to the statement(s) after the switch. If
default is not the last case in the switch block, remember to end the default case with a
break.
Example
var greetings;
var timeOfDay;
timeOfDay = "afternoon";
switch (timeOfDay) {
case "morning":
greetings = "Good morning";
break;
case "afternoon":
greetings = "Good afternoon";
break;
case "evening":
greetings = "Good evening";
break;
default:
greetings = "Hi there";
break;
}
console.log(greetings);
Looping Statements
JavaScript For Loop
Defnition: For loops are commonly used to count a certain number of iterations to repeat a block
of code. Meaning, we use for loop when we want to execute the code for a SPECIFIED amount of
time
Syntax:
for (initialization; condition; post/final-expression) {
// statements (code block to be executed)
}
As you can see it from the syntax above, the JavaScript for loop statement allows you to create a
loop with three optional expressions that are separated by semicolon (;).
The initialization expression: This expression is commonly used to create a counter
variable. A counter variable is a variable that keeps track of the number of times a specific
piece of code is executed. A counter variable basically counts the loop. All the variable
does is tell our loop where it should start counting from. This is like saying, “we are going
to start counting starting from whatever value we give it in here”. We usually provide 0 as
value for the initial counter. However, it can be a different number too.
The initialization expression is executed only once when the loop starts.
If you use the var keyword to declare the counter variable, the variable will have
either function or global scope. In other words, you can reference the counter
variable after the loop ends. However, if you use the let keyword to declare the
counter variable, the variable will have a blocked scope, which is only accessible
inside the loop. See the example below:
for (let counter = 1; counter < 5; counter++) {
console.log(counter); // prints numbers 1 to 4
}
console.log(counter); prints “ReferenceError: counter is
not defined” because we used let to define counter
Condition: This is the expression that is checked one time prior to every iteration. If the
condition evaluates to true; the loop’s statement is executed. If it evaluates to false, the
loop stops. The loop is terminated if the condition evaluates to false. See the example
below:
for (var counter = 1; counter < =10; counter++) {
console.log(counter);
}
In the above example, we want the code to be executed 10 times. What the condition
expression (counter < =10) does is check if we have already run the code 10 times. If we
haven't, it runs the code again
If you want to stop the loop before the condition expression evaluates to false,
use break statement. In the example below, even if the condition evaluates true
when j is 8 or 9, the code will not run because we used break when j is 7. Thus,
the loop terminates when j reaches 7.
for (var j = 1; j <= 10; j++) {
if (j === 7) {
break;
}
console.log(j); // prints numbers 1 to 6 and loop
stops
}
The condition is optional. If you omit it, the for-loop statement considers it as true.
If you omit the condition expression, you need to use a break statement to terminate
the loop.
for (let counter = 1;; counter ++) {
console.log(j);
if (j >= 10) {
break;
}
}
Post/final-expression: This expression is run after every single iteration. Generally, you
use the post-expression to update the counter variable (either to increment or decrement
the counter)
When the initialization expression, condition expression and final
expression parts come together, the meaning they give to the following for
loop will be:
for (var i = 0; j <= 10; i++) {
console.log(i); // prints numbers 0 to 10
}
Start counting your loop starting from 0. To keep track of how many times the code inside the for
loop block is executed, save that value on a variable called i. To start with, lets assign 0 to our
variable i. Then compare that i with 10, and if i is less than or equal 10, run the code. In the first
loop, i is 0, which is less than 10. So, the code executes. Once the code finishes executing, increase
the value of i by 1. In the second loop, i is 1. 1 is still less than 10, so, execute the code again. Once
the code finishes executing, increase the value of i by 1. In the third loop, i is 2. 2 is still less than
10, so, execute the code again. Repeat this process until i becomes greater than 10.
Example:
var someNumbers = [7, 58, 27];
var lengthOfArray = 3;
var loopNumber = 0;
var someMessage = "";
var i;
for (i = 0; i < 3; i++){
loopNumber = i + 1;
someMessage = "Loop " + loopNumber + ":" + someNumbers[i];
console.log(someMessage);
}
Javascript while loop
Defnition: The JavaScript while statement creates a loop that executes the code within the while
block as long as the test condition evaluates to true. After every single code execution, it comes
back and checks if the condition expression is still true. If the condition expression evaluates to
false, execution continues with the statement after the while loop.
Syntax:
while (expression) {
// statement (code block to be executed)
}
The while loop evaluates the expression before each iteration, therefore, the
while loop is known as a pretest loop. For this reason, it is possible that the
statement inside the while loop is never executed.
Example:
var f = 0;
while (f < 3) {
console.log(f); // prints the numbers 0 to 2
f++;
}
These are the steps involved in the above while loop example: First, outside of the loop, the f
variable is set to 0. Second, before the first iteration begins, the while statement checks if f is
less than 3 and executes the statements inside the loop body. Third, in each iteration, the loop
increments f by 1 and after 3 iterations, the condition f < 3 is no longer true, so, code executes 3
times the loop terminates.
Tip: A function that returns the sum of numbers between 1 and a given number
function addUp1(num) {
let sum = 0;
for (let i = 1; i <= num; i++) {
sum = sum + i;
}
return sum;
}
console.log(addUp1(600));// prints180300
For example, if you want a button on your website to change its color to green when a user clicks
on this button, you need to be able to select this specific button and write a logic that changes the
color of the selected element into green using JavaScript. DOM organizes our HTML document
in an object form so that JavaScript can manipulate (access and modify/update the any HTML
element). Therefore, DOM is the link between an HTML web page and JavaScript.
The DOM is a structure/standard/syntax that allow JavaScript to access, modify, and update the
structure of an HTML page. The DOM is a logical tree-like model/representation of our HTML.
DOM represents the HTML page using a series of objects. The main object is the document object,
which in turn houses other objects which also house their own objects, and so on.
A simple way to think of the DOM is in terms of the document. You saw documents diagrammed
in this way when you were learning about CSS selectors.
<html>
<head>
<title>Document title</title>
<meta charset="utf-8">
</head>
<body>
<div>
<h2>Subhead</h2>
Document node
Element nodes
Attribute nodes
Text nodes
Each element within the page is referred to as a node. If you think of the DOM as a tree, each node
is an individual branch that can contain further branches. But the DOM allows deeper access to
the content than CSS because it treats the actual content as a node as well. The next figure shows
the structure of the first p element. The element, its attributes, and its contents are all nodes in the
DOM’s node tree.
DOM Manipulation
Earlier we said that DOM represents the HTML page using a series of objects, the document object
being the main object. The document object in turn houses other objects which also house their
own objects, and so on.
So, when we say, “DOM manipulation”, it simply means changing the DOM (the HTML
document). This in turn means, changing the HTML elements that DOM converted into objects,
in response to a user’s action
The “document object” makes manipulation of the HTML document possible: The "document"
object in JavaScript is the door to the DOM structure. This is the name of the JavaScript object
that contains all the methods and properties to help us access and manipulate the DOM elements.
The "document object” allows us to access the root node of the DOM tree. You can access the
other child nodes of the DOM as properties of the “document object”.
There are three common methods provided by the document object that we can use to select one
specific element. Let’s look at them below.
2. querySelector() method: The querySelector method takes CSS selectors as its argument and
returns the first element that matches the passed selector. Meaning, the method can take ids, classes
and tag names as its argument.
document.querySelector("div"); // selects all elements with “div” tag, but returns first
div
Syntax: document.getElementsByClassName(classname)
getElementsByClassName(“red”)// retunds HTML collection with all elements having the “red”
class
var el = document.getElementsByClassName("red");
4. getElementsByTagName() method: The method takes a tag name and returns a collection of
all elements in the document with the specified tag name, as an HTMLCollection object.
Syntax: document.getElementsByTagName(tagname)
var el = document.getElementsByTagName("li");
5. Traversing between multiple elements: Traversing is the act of selecting an element from
another/neighboring element.
A. Traversing downwards:
console.log(document.getElementById("listOfFruits").firstElementChild);//
prints the first li element under the ul
B. Traversing upwards:
parentElement(): parentELement is a property that lets you select the parent element.
parentElement is great for selecting one level upwards
C. Traversing sideways:
console.log(document.getElementById("three").previousElement
Sibling)//prints the 2nd li
console.log(document.getElementById("two").nextElementSibling); // prints
the 3rd li
The HTML DOM allows JavaScript to change the content of HTML elements. Meaning, we can
add, update or remove the HTML tag, the text content in an HTML element, or the entire block of
HTML code from your page. These are the most common methods that allow us add, update or
remove contents in an HTML document.
<div id="bigId">
<div>Hello</div>
<ul id="listOfFruits">
</ul>
</div>
1. createElement() method: The createElement() method creates an Element Node with the
specified element name.
Syntax: document.createElement(nodename)
parent.appendChild(liElem);
console.log(parent); // shows that a new <li> is added as the last child of the
parent node (the <ul>)
2. appendChild() method: The appendChild() method appends a set of node objects as the
last child of a node. See the above example.
Syntax: node.appendChild(node)
3. prepend () method: The method inserts a set of node objects before the first child of the
Element. See the above example.
parent.prepend(liElem2);
console.log(parent);// shows that a new <li> is added as the first child of the
parent node (the <ul>)
4. textContent() method: The textContent property changes or returns the text content of the
specified node, and all its descendants. TextContent() returns all text contained by an
element and all its children.
Syntax: node.textContent
Let’s change the text content of our <div> that has "bigId" as its id
5. removeChild() method: The removeChild() method removes a specified child node of the
specified element. Note: Use the appendChild() or insertBefore() methods if you want to
insert the removed node back into the same document.
Syntax; removeChild(child);
6. hasAttribute() method: The hasAttribute() method returns a Boolean value (true or false)
indicating whether the specified element has the specified attribute or not.
Syntax: element.hasAttribute(attributename)
</form>
Let’s check if our <form> element has “name” and “id” attributes
7. getAttribute() method: The getAttribute() method returns the value of the attribute of an
element.
Syntax: element.getAttribute(attributename)
Let’s print the value of the “name” attribute for our first name <input>
attributename parameter specifies the name of the attribute whose value is to be set.
Even if you put upper case for the name, the attribute name is automatically
converted to all lower-case when setAttribute() is called
attributevalue parameter is the value to assign to the attribute
Let’s add a “value” attribute to our first name input. The value will be a placehoder for our
First Name input.
firstInputVal.setAttribute(" value ", " first name ");// placeholder input value
of “first name” added to our <input>
Syntax: element.removeAttribute(attributename)
Let’s remove the “type” attribute form the first name <input>
10. Changing CSS Values with the DOM “style” property: We use the style property to
manipulate the inline style of the HTML elements using JavaScript. The style property is
used to get as well as add the inline style of an element using different CSS properties. We
can set almost all the styles for the elements like colors, fonts, text alignments, margin,
borders, background images, sizes, and more.
The style property is extremely helpful to dynamically change the visual representation of
an HTML element using JavaScript. Note: the JavaScript syntax for setting CSS propertie
is slightly different than CSS (Ex: backgroundColor instead of background-color).
Syntax:
To return style properties: = element.style.property
To set/add style properties: = element.style.property = value
Example
Style background color property: The backgroundColor property sets or returns the
background color of an element.
Let’s change the background color of 2nd <li> into yellow and print the changed color
Event Handling
Events in JavaScript are what happens on the browser when a user browses/manipulates a any
website. Change in the state of any object is known as event, i.e., event describes the change in the
state of the source. HTML/browser events are "changes" that happen to HTML elements when a
user or the browser manipulates the website. When the page loads, it is called an event. When the
user clicks a button, presses any key or closes/resizes a window, these too are events.
Your job as a JavaScript developer is to write a script that responds to an event that happens on
the browser. This is what makes websites interactive. When one interacts with a web page (like
clicking a button), that interaction is registered as an event on the browser. In response to that
event, the script that is bound with that event changes something on the web page. Event in
JavaScript are also called HTML or browser events. One key concept to understand in here is that
you, as a web developer, will be responsible to prepare the scripts in response to potential events
that could happen on your website.
Event types
The browser triggers many events, and our JavaScript code reacts/gets executed in response to
these events. Below, please find some of the most common event types and event names:
UI/Window events: These events occur as the result of any interaction with the browser
window rather than the HTML page. The various UI events are as follows. In these events,
we attach the event listener to the window object, not the document object
Load event: The event fires when the browser finishes loading a page
Unload event: This event fires when This event fires before the users leave the
page, probably because user requested a new page
error event: This event fires when the browser encounters a JavaScript error or a
value that doesn’t exist
resize event: This event occurs when a user changes/resizes the current size of the
browser window
Scroll event: This event fires when the user scrolls up/down on the browser
window. It can relate to the entire page or a specific element on the page.
Key board events: These events fire when a user interacts with a keyboard
keydown event: This event fires when user first presses any key on the keyboard.
Note: If the user holds down the key, this event fires repeatedly.
keyup event: This event fires when a user releases any key on the keyboard.
keypress event: Just like keydown event, this event fires when a user presses any
key on the keyboard. However, the pressing of key results in printing a character
on the screen. The keypress event will not fire for enter, tab or arrow keys as
pressing them will not result in printing characters on the screen, but the keydown
event will fire if a user presses these keys.
Note: The keydown and keypress events fire before a character appears on the
screen, the keyup fires after it shows.
Mouse events: These events fire when the mouse moves, or the user clicks a button. All
the elements of the page support these events.
Click event: This event fires when the user presses on and releases the primary
mouse button (usually the left button).
Note 1: This event also fires if the user presses the “Enter” key on the keyboard
when an element has focus.
Note 2: For touchscreen devises, a tap on the screen acts like a single left-click
Note 3: We can add the above two events to any element, but it’s better to apply it
only on the items that are usually clicked (like button element)
dbclick event: This event fires when user quickly presses and releases a button twice
Note 1: For touchscreen devises, a double-tap on the screen acts like a double
leftclick.
Note 2: We can add the above two events to any element, but it’s better to apply it
only on the items that are usually clicked (like button element)
mouseover event: It fires when the user moves the cursor, which was outside an
element before, inside the element, in short, when a user moves the mouse over an
element.
mouseout event: This event fires when the user moves the cursor, which was inside
an element before, outside the element, in short, when users move the mouse from
an element
Form Events: These events are common while using forms on a webpage. We find the
submit event mostly in form of validation (Ex: if a user misses a required information or
enters an incorrect input, submit event fires to check the form values before the data is
sent/submitted to the server).
change event: This event occurs when the value of an element has been changed.
Example, the change event fires when the checked value in check box, or radio
button changes
submit event: This event fires when a user submits a form. The change occurs on
the <form> element when user submits a form using a button or a key.
cut event: This event fires when a user cuts a content from any HTML element.
Note 1: The cut event is mostly used on <input> elements with type="text"
Note 2: Although the cut event is supported by all HTML elements, it is not
possible to cut the content of a <p> element, unless we add the “contenteditable”
attribute and give it a value of "true".
paste event: This event fires when a user pastes content in an element
Note 1: The paste event is mostly used on <input> elements with type="text"
Note 2: Although the paste event is supported by all HTML elements, it is not
possible to cut the content of a <p> element, unless we add the “contenteditable”
attribute and give it a value of "true".
copy event: This event happens when a user copies the content of an element (ex:
copying content from a form field)
Tip: The copy event is mostly used on <input> elements with type="text".
select event: This event fires when a user selects some text in an element.
Focus and blur events: These events fire when the HTML elements you can interact with
gain/ lose focus. They are most commonly used in forms and especially helpful when you
want to do the following tasks: The tips are usually shown in the elements other than the
one the user is interacting with. To trigger form validation as a user moves from one control
to the next without waiting to submit the form.
Here are some of the focus and blur events:
Focus/focusin event: This event fires, when an element gains focus.
Blur/focusout event: This event fires, when an element loses focus
Event handlers/listeners
An event handler is also known as an event listener. An event handler/listener is a specific script
(JavaScript code) that gets executed when a particular event (such as clicking of a button) happens
on an HTML element. An event handler is a script/function that listens to the event and responds
accordingly to the event.
When a user interacts with any HTML element on a web page, there are three steps involved in
triggering a script associated with an event:
1. Selecting an element: The element is selected to bind it with the event handler (JavaScript
function) when an event occurs on it
2. Binding an event: This is to identify the specific event that will trigger the event handler to
execute.
3. Attach a script: This is to instruct the web browser which specific event handler to execute
when a specific event happens
Note: The script that you want to bind with an event needs to be written first
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. To
handle events using this method, all you need to do is to use an HTML attribute with the name of
the event handler function.
Example: Let’s try to change the color of our button’s text to red when the <button> is clicked
function changeButtonColor() {
myButton.style.color = "red";
Attaching the event handler function to when there is a click event on our <button> element:
This approach (using inline event handlers) is considered a bad practice for the following reasons:
The event handler code is mixed with the HTML code, which will make the code more
difficult to maintain, especially on a larger scale it can get quite messy. Look at this
example: how unclean it will be to have all these event handlers in our <button>
The approach won’t allow us bind more than one event handler for an event. Meaning, if
we use the inline event handling approach, we cannot assign a text color changer function
and a background color changer function for a single <button> click event.
2. Traditional/DOM Level 0 event handlers (as a method)
Each element has event handler properties (or onevent properties) such as onclick, ondblclick or
onfocus. Under this event handling approach, you just need to set/assign the event handler property
to a function (event handler function).
Example: Let’s try to change the text color of a <button> to red when a user clicks on the <button>
Method 1: It is fine to make the handler function a separate named function, like below:
Binding an event handler with the element selected using a named function
myButton.style.color = "red";
};
Attaching the event handler function with the event handler property (onclick)
myButton.onclick = changeToRed
myButton.onclick = function () {
myButton.style.color = "red";
};
Under traditional DOM event handling, we can only attach a single function to an event.
Under this event handling approach, we will add/remove the event handler as a listener for an
element using the addEventListener() method. This is the most favored way of handling events as
the approach allows adding (removing) of multiple event handlers for a single event using the
event listener methods.
DOM Level 2 Event Handlers provide two main methods to register/deregister event listeners:
addEventListene(): This is the recommended mechanism for adding event handlers in web pages.
Inside the addEventListener() function, we specify two parameters: the name of the event and
event handler function we want to run in response to the event.
Example 1: Let’s change the text color of a <button> to red when <button> is clicked
myButton.addEventListener("click", function () {
myButton.style.color = "red";
});
Example 2: We can use a named function to do the same thing as example 1 above
myButton.style.color = "red";
};
myButton.addEventListener("click", changeToRed);
removeEventListener (): The removeEventListener() removes an event listener that was added
via the addEventListener(). However, we need to pass the same parameters that were passed to the
addEventListener()
myButton.style.color = "red";
};
myButton.addEventListener("click", changeToRed);
myButton.removeEventListener("click", changeToRed);
Adding multiple listeners for a single event: Through DOM Level 2 event model, it is possible for
one event to trigger multiple event handler functions. Meaning, a specific object (ex:
Let’s add different event handler functions and change the text color of button to red, change the
button’s background to yellow and alert a message that says, "button clicked!!!"
myButton.addEventListener("click", function () {
myButton.style.color = "red";
});
myButton.addEventListener("click", function () {
alert("button clicked!!!");
});
myButton.addEventListener("click", function () {
myButton.style.backgroundColor = "yellow";
});
Reference Materials
JS reserved keywords
https://www.w3schools.com/js/js_reserved.asp
Operators Priority in JS
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Operators/Operator_Precede
nce
JS Problems on algorithmic thinking
https://edabit.com/
JS data types
https://cdn.ttgtmedia.com/rms/onlineimages/whatis-data_structure.png
DOM tree
https://miro.medium.com/max/1040/1*YSA8lCfCVPn3d6GWAVokrA.png
CSS using in JS
http://www.sitestepper.be/en/css-properties-to-javascript-properties-reference-list.htm
JS Events
https://www.w3schools.com/tags/ref_eventattributes.asp
_______________The End!_______________