JavaScript basics and Event model

Goals

Learn basic concepts of JavaScript, concepts such as variables, expressions, sentences and so on. Also learn about the relationship between web pages and JavaScript.

  • Understanding how to use the script element. Also understand the three ways of writing JavaScript programs.
  • Understanding constants, variables, and expressions.
  • Understanding sentences.
  • Understanding functions without arguments.
  • Understanding the mechanism by which programs written in JavaScript are executed.
  • Understanding events.
  • Understanding how to write event handlers.
  • Understand some fundamental functions such as alert().

 

Basics of JavaScript

Execution of the program

Like many programming languages, JavaScript programs are composed of sentences and declarations that are executed from the top to the bottom. A sentence is line of code where one changes the value stored in the memory, or controls the flow of the program. A declaration defines a function, which is essentially a chunk of commands waiting to be processed. In the declaration, only defining the function, neither actually changes the value stored in the memory nor does the calculation. It is only when the function is called that it actually changes or stores the value stored in the memory. More details will be explained later on in this lesson.

Before describing the process of actually changing the value stored in the memory, the concept of values themselves and expressions using them will be explained.

 

Data Types

In JavaScript, in order to store data, the following seven types of data (types) are specified. All values belong to one of these types.

Undefined Type
A type used when no value is assigned to a variable. Only an undefined value is specified as a value.
Null Type
As the value, only null representing an empty state is specified.
Boolean Type
A type for representing truth or falsehood. Two values, true and false, are specified as values.
String Type
A type for representing a string.
Symbol Types (Special Characters)
A type used for object properties and others. It is used to represent a special value that cannot make two or more same values.
Number Types
A type for representing a numeric value. It can express both integer and real number.
Object Types
An amalgam composed of a combination of the above six types.

Constants and Literals

In JavaScript, it is possible to handle the seven types mentioned above as data, and there is a way of writing to describe the value (constant) in each. This style of writing is called a literal. Here we introduce literals of each constant.

Undefined Type’s Value
For undefined type values only undefined is prescribed, and values can be represented as “undefined” as they are. However, undefined is not a literal.
Null Literal
As the value of the Null type, only null is specified, and the literal is also “null“. Care must be taken because initials must be lowercase.
Boolean Literal
The true and false values are described as “true” and “false“, respectively.
String Literal
It is described by enclosing a character string with single quotation mark (‘) or double quotation mark (“), but if you put a single quotation mark enclosed in another single quotation mark, or double quotation marks enclosed in double quotation marks, Prefix the character with a slash (\).
Example: 'Keio University', 'Keio University', '12345', 'I' m a student. ',' I \ 'm a student.'
Symbol Type’s Value
There is no literal to handle the value of Symbol type directly. By using the function Symbol () you can create a value of Symbol type.
Number Type’s Value
There are integer literals representing integers and floating point number literals representing real numbers.
In addition to the integer literal, there is a method of expressing it in decimal notation (beginning with a number with a non-zero head like 1 or 23), a method of expressing in binary notation (head starts with 0 b like 0 b 1 and 0 b 10111) , A method of expressing it in hexadecimal notation (the head starts with 0x as 0x1 or 0x17) and the like.
On the other hand, there are also methods for expressing floating point number literals using general expressions such as 3.14159, and expressing using e as in 6.022e23 (in this example, representing 6.022 × 1023).
Object Literal
It is a combination of multiple values and uses expressions such as {“key 1”: “value 1”, “key 2”, “value 2”, …}. In addition to string literals, you can use arbitrary literals for “value 1” and “value 2”.

Variables

A variable is one in which a place is prepared in the storage area of the computer and a name is given to the place. A variable can contain a value. Depending on the language, there are variables whose usage is limited, such as variables that can only contain numbers, variables that can only contain letters, but in JavaScript anything can be in the same variable.

変数の概念
変数の概念

The program describes the processing procedure when data is processed according to a certain algorithm.

It is like writing a recipe for cooking, and in the case of “stir-fried food”, you cut the ingredients and use oil to grease the frying pan. At  some point in time, if the ingredients are  cabbage / carrot / onion it is time to stir the vegetables, if the ingredients are green peppers / pork / bamboo shoots,  then it is time to make sauce.

Here, what can be done by something “ingredients” will be different. In other words, in the recipe you have to write “cut something, stir something, taste something”. This “something” is a variable. It is the same in addition. Write “c = a + b”, “a” is 3, “b” is 5, “c” is 8. In this way, values ​​are represented by symbols. Note that here, unlike “c = a + b” in mathematics, JavaScript implies substituting the result of “a + b” for the variable “c”.

Variable Declaration

In JavaScript, what is called a declaration statement is prepared to clarify that “this symbol is a variable”. To clearly declare variables in JavaScript, do as follows.

var varname;
var varname = initial value;

The first method is simply declaring that you prepare a variable and name it “varname”. Nothing happens explicitly. Even if you attempt to display the value using the debugger here, since the value is not defined, it becomes “undefined”. In the second method, a variable named “varname” is prepared and an initial value is assigned to it. The initial value part may be a constant such as a number, a character, a character string, or an expression that generates a calculation formula or an object.

It is also possible to declare and initialize variables on separate lines. For example, if you divide the second method above into two lines, it becomes as follows.

var varname;
varname = initial value;

Actually, in JavaScript, the program operates without explicitly declaring variables. However, since such usage often causes problems, it is better to make variable declarations.

Naming Variables

There are rules on how to name variables. When attaching a variable name, it is necessary to observe the following rules.

  • Allowed characters are alphanumeric characters, underscore (_), dollar sign ($)
  • The first character is non-numeric
  • Capital letters and lower case letters are distinguished
  • Reserved words cannot be used

A reserved word refers to a word already used for other purposes in the language. For JavaScript, reserved words are as follows.

break, case, catch, continue, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with

Also, it is better not to use the window object property as a variable name. For example, name is included as a window object property so it cannot be used.

When attaching a variable name, it makes it easier to understand the program by showing the meaning of the variable. For example, you may name the variable storing the total as “sum”, or name the variable nickname as “nickname”. However, one must be careful that the names are not too long.

There are various ways of assigning variables. For example, Camel Case, Hungarian Notation, Google JavaScript Style, etc. If you are watching examples of various sites, you notice that programs are written in the same way. Although it is not necessarily required to decide variable names and function names according to this style, it is helpful to refer to it as it helps to write a clean and easy-to-read program.

 

Scope of variable

If you do not declare variables as shown above, it may cause several problems. What is the problem? Many programming languages ​​have a concept called “scope”. This is to allow names to be used only in certain places in order to avoid confusion.

For example, variables with common names such as “date” and “sum” may already be used in many programs, and if you use these names too often, it can cause problems. Attempting to save to a variable of the same name as one that exists elsewhere can cause confusion. Therefore, the idea of ​​the scope is to limit the range in which the name becomes effective to only a specific part of the program.

The following program shows an example where such a confusion occurs. Here, alert () is a function for pop-up displaying a message. In this example, the value in the variable word is displayed.

var word = "Hello";

// hello 1
function hello1() {
var word = "Good Evening";
alert(word);
}

// hello 2
function hello2() {
alert(word);
}

// hello 3
function hello3() {
word= "Good Evening";
alert(word);
}

// hello 4
function hello4() {
{
var word = "Good Evening";
}
alert(word);
}
<button onclick="hello1()">hello1</button>
<button onclick="hello2()">hello2</button>
<button onclick="hello3()">hello3</button>
<button onclick="hello4()">hello4</button>

Actual movements are as follows. Let’s press the button. What is going on? Since the movement also changes according to the order in which buttons are pressed, try to grasp the movement by making full use of the browser’s reload functions. It might help to use a debugger.





When you press the hello 1 button, “Good evening” is displayed. This is indicated by alert () on line 6. The display content is the value of the variable word declared in the fifth line immediately above.

Initially, when you press the hello 2 button, “Hello” is displayed. This is an alert issued in the sentence on the 11th line. The value is initialized in the first row. Notice that the value assigned in the assignment statement on line 5 is not displayed here. Why is the assignment statement on line 5 irrelevant? According to the rule “program runs basically from top to bottom”, there is an assignment statement on line 5 before alert () on line 11, so the value of word should be “good evening”. However, the fourth to the seventh lines are function declarations. The part that is a declaration will not be executed until it is actually called from another function. Therefore, the value of the variable word is never changed.

However, with this explanation, once you press the hello 2 button after pressing the hello 1 button, you should see “Good evening”. However, in fact, even if you press the hello 2 button after pressing the hello 1 button, “Hello” is displayed. Actually, in this program, the word variable declared in the first line and the word variable declared in the fifth line are different things. This concept is what is known as scope.

JavaScript has two types of scope called global scope and local scope. Scope defines the range that variables and functions can be referred to, and in the case of global scope it can be referenced from anywhere in the program. On the other hand, in the case of the local scope, it is limited to within the function, and can only be referenced in the function.

In the above example, the word variable in the first line is defined as a global variable (global scope variable), and the fifth line word variable is defined as a local variable (variable that can be referred to only from the lec 01 _ 01 _hello 2 function). Therefore, from the lec01_01_hello2 function, you can access the word variable declared in the first line, but you cannot access the word variable in lec01_01_hello1. Conversely, referring to the word variable from lec 01 _ 01 _hello 1, the local variable is referenced and the global variable can not be accessed.

Declaring local variables is possible by declaring them using “var” in the function. When declared outside the function, it becomes a global variable like the declaration of the first line. What’s confusing is that if you do not declare with “var” in the function, that variable will be treated as a global variable. Extreme caution is required when using global variables. In the example above, press the hello 3 button and then press the hello 2 button.
“Good evening” is displayed. This is an example that affects the lec 01 _ 01 _hello 2 () function because it rewrites the contents of the word variable which is a global variable in the lec 01 _ 01 _hello 3 () function. If you use global variables, you should be careful not to confuse them with other variables naming variables.

This program gives an easy name “word”, but if you use such an easy name unexpectedly you see from other places, when you use it in combination with another program there may be a clash between the names used.

Hello 4 button is a trap that is often a mistake made by a person who has learned another language such as C language. JavaScript has only global scope and function local scope.
Therefore, even if you create a new block like the lec01_01_hello4 () function, it will be a local variable in the function, so you need to be careful. Those who learn programming for the first time, please be aware that there are programming languages ​​that can explicitly create different scopes by creating new blocks like this.

Expressions

We now come to the concept of “expressions” in a programming language. In terms of mathematical expression, we think of something like y = 2x + 3, but the concept of expressions in programming is somewhat different. An expression in programming is “to evaluate (calculate) and generate a value”. For example, “1” is also an expression and “hello, world” is also an expression. The former generates a value of 1 as a value, while the latter generates a character string “hello, world” as a value.

The expression “evaluate” the expression does not mean what it does in mathematics. In programing lingo, expressions do not necessarily perform arithmetic operations. For example, as we have seen, there are expressions that generate character strings and even values such as true and false. They can answer yes (true, true) or no (false, false) on a condition such as a “variable n is smaller than 3”.

Some functions, when called, do not generate values. Therefore, when we say “to evaluate” we need to say it without implying that we are “doing calculations”. An evaluation refers to obtaining expressions by executing expressions and functions using variables and constants.

An expression is made up of operators and operands. Operators are symbols for manipulating values ​​such as + and -. Also, the operands are objects that are manipulated by operators. For example, in “1 + 2”, 1 and 2 are operands and + is an operator. The result of this expression is 3.

Many programming languages, not just JavaScript, have many operators. These can be categorized by the number of operands that are present in the expression.
For example, the + operator takes one operand on each of its right and left.This is called a binary operator. There are also one-term or unary and three-term or ternary operators.
For example, the symbol used in “-3” representing a negative number is a unary operator.

Arithmetic Operations

First, let’s look at arithmetic operations as basic and understandable expressions.
Arithmetic operations include, the following operators.

Operator Meaning Example
+ Adds left and right values 1+2、1024+2048
Subtracts the right value from the left value 5-3、2048-1024
* Multiplies the left and right values 1*2、1024*2048
/ Divide left value by right value 6/3、2024/128
% Find the remainder when dividing left value by right value 100%30、29%2
++ Increment (add 1 to the value). The added value is set to the variable specified by the operand. ++i、j++
−− Decrement (Subtract value by 1). The added value is set to the variable specified by the operand. −−i、j−−

For the four operators “+”, “-“, “*” and “/”, it is an ordinary four-arithmetic operation, so you do not need to explain it. “%” may not be used much in everyday life, but it is an operation that returns the remainder. For example, if it is 100/30, the remainder is 10, so the expression 100% 30 returns 10. Also, in the JavaScript “%” operation, decimals are passed on to the remainder. For example, the result of 100.5% 30 is 10.5.

“++” and “-” may be more confusing. This is an operator that affects the values ​​in variables, and writing “++ i” will increment the value in i by 1 and return that value. For example, if i is 5, writing “++ i” will return 6, and the value of i itself is replaced with 6.

What’s more confusing is that the values are different when you write “++ i” and “i ++”.
When “++ i” is described, the value is increased by 1 before returning the value. However, when writing “i ++”, the value in the variable is incremented by 1 after the value is returned.

When the value of i is 5, writing “++ i” will return both the value to be returned and the contents of i to 6, but if you write “i ++”, the value returned is 5, but the value of i is 6.
By describing an expression such as “j = i ++” and confirming the values ​​of i and j, the behavior can be understood.

String operations

Strings also have operators.
For example:

Operator Meaning Example
+ Concatenation. It concatenates the left and right values to generate one character string. "hello, " + "world""My name is" + firstname

There are things to be careful when computing character strings. For example, “5 + 4 +” 3 “” is a case where a character string and a number are mixed in the same expression.
The “+” operator is used for both concatenation and arithmetic operation.

In the case of “5 + 4 +” 3 “”, since the operation is evaluated from the left side, it is expressed as “(5 + 4) +” 3 “” in parentheses.
For this reason, “5 + 4” is executed first to become “9”, which is converted to “9” “of the character string so as to be connected with the character string” 3 “”,  eventually to “93” “.

As you can see, numeric type objects are automatically converted into characters at the time the character string appears, and it becomes a character string calculation, so care must be taken.

Assignment operator

An assignment operator is slightly different from the operator described so far. Actually, you may have used assignment operators many times so far. An assignment statement is basically one that puts a value in a variable. Actually, in JavaScript, ‘=’ is used for value substitution and is also treated as a kind of operator.

Other assignment operators are described below.

 

Operator Meaning Example
= Substitution. Assigns the value on the right to the variable on the left. a = 1、a = b、a = 3 + 4
+= Adds the value on the right to the variable on the left. a += 1、a += b、a += 3 + 4
-= Subtracts the value on the right from the variable on the left. a -= 1、a -= b、a -= 3 + 4
*= Multiplies the value on the right by the variable on the left and substitutes the result on the left side. a *= 1、a *= b、a *= 3 + 4
/= The right variable divides the left variable and assigns the result to the left side. a /= 1、a /= b、a /= 3 + 4
%= Divides the variable on the left with the value on the right and assign the remainder to the variable on the left. a %= 1、a %= b、a %= 3 + 4

When assignment operators are used, attention must be paid that the left side of the assignment operator is always a variable.

Operator precedence

In mathematics, multiplication and division are stronger than addition and subtraction, and the answer of “1 + 2 * 3” is not 9 but 7. Javascript also has the concept of strength and precedence.
The rules for precedence are shown n below.

Strength of Precedence Operator
Strong ( )
++、−−、−
*、/、%
+、−
Weak =、+=、-=、*=、/=、%=

For example, “a% = 3 + 4” is obtained by substituting a remainder obtained by dividing a by 7, substituting a obtained by dividing a by 3 into a, adding 4 to it, and adding 4 to the value of the expression It does not become.

As you can see from the above, it is “bracket ()” that has the strongest bond.
If you want to change the order of the join, you can enclose the part you wish to enhance coupling in parentheses.
Even if you do not necessarily want to strengthen the connection, making parentheses easier to understand misleading expressions is effective for preventing program mistakes

Statements and declaration

A JavaScript program consists of “statement” and “declaration”. We will briefly explain what a “statement” and “declaration” are.

Statements

A “Statement” is the basic unit of processing and represents some procedure.
It may also be used to control the flow of procedures in a program.

In JavaScript, there are many kinds of statements.  An expression statement (one in which expressions are treated as single statements, in many cases with assignment operators), a control statements (accurately classified into if statements, switch-case statements, etc.), and a return statement are all the fundamental types of statements in JavaScript. Combining these statements makes it possible to describe a series of procedures.

Declaration

A “Declaration” is a procedure that makes things visible from other parts of the program, and nothing happens when that part is executed.

It is effective only when it is instructed to actually be executed from other parts of the program. This is equivalent to a function declaration.

Incorporating a JavaScript program in the Website

script elements and JavaScript

Of course, in order to connect HTML (Web page) and JavaScript programs, some mechanism is necessary. For this purpose, HTML has the “script element”. The script element is an element used when inserting a program into HTML. In fact there are two ways of writing it as shown below.

Let’s write a program directly in the script element.

...
<script type="text/javascript"><br />
  var a=1;<br />
  var b=2;<br />
  alert(a + "+" + b + " = " + 3);<br />
</script>
...
How to write the path to the program file in the attribute of the script element

...
<script type="text/javascript" src="example.js"></script>
...

The former method is easy to use when the program is short, the latter method is easy to use when the program size is large to some extent.

Executing JavaScript

Basically, when loading HTML, the Web browser processes each statement in order from the top to bottom. At this time, if there is a script element in processing, the JavaScript program is executed at that timing.

However, when a function is declared within JavaScript, it is only executed once it is called. For programs outside the function declaration, they are executed when they are read.

Also, when manipulating HTML elements from JavaScript, it is necessary to note that elements of HTML must be created at the time the JavaScript program is executed.

Here, you may wonder where the script element is located. Generally, either of the following two methods are adopted. One way is to put the script element in the head element and the other is to put it at the end of the body element.

Event Model

One of the cooperation between HTML and JavaScript is event handling. Here, an event generated by a Web page and its handling method will be described.

HTML elements and events

A page expressed in HTML generates an event to the Web browser the moment it is displayed.
Events include those caused by user operations such as click (onclick) and double click (ondblclick) on elements such as buttons, as well as those occurring at the end of page loading, moving to another page, and the like. The types of events generated by the Web browser are shown below.

Examples of major events are shown below.

Type Event Events Explained
Page Events onload When a page has fully loaded
onunload When moving to another page, or when the page is closed
onresize When the size of the page has changed
onscroll When a user scrolls through the page
Mouse Events onclick When the user clicks the mouse
ondblclick When the user double clicks the mouse
onmousedown When the moue is pressed down
onmouseup When the mouse is released
onmouseover When the mouse hovers over a region or element
onmouseout When the mouse hovers out of a region or element
Keyboard Events onkeydown When a keyboard key is pressed down
onkeypress When a keyboard key is pressed
onkeyup When a keyboard key is released
Form Events onchange When there is a change in the form elements
onsubmit When the submit button is clicked
onreset When the reset button is clicked
Focus Events onfocus When an element or region is in focus
onblur When an element or region is out of focus

Invoking a function by an event

In HTML + JavaScript, JavaScript programs are often activated by events. A program associated with such an event is called an event handler. In many cases, the JavaScript event handler is defined as a function, and the program is executed by calling the function.

When the button is clicked, an HTML and JavaScript program displaying an alert is shown below

 

HTML
...
<button onclick="message();">Click me!</button>
...
JavaScript
function message() {
alert("The button has been pressed");
}

The following buttons can be realized by the above HTML and program.


In this JavaScript program, the first line to the third line declares a function named “message”. The contents of the function is only from line 1 to 2, and is only displaying an alert. Also, in the HTML, we call the “message () function” when “onclick” event occurs.
That is, it defines an event handler for “onclick” event.

Please note that the event handler described in HTML is the JavaScript program itself.
You can write JavaScript programs in the ‘message ();’ part only. Therefore, it is possible to call “alert () function directly.


Such an example is shown below. This description method also operates in the same way as above, but if complicated pr
ocessing is performed when an event occurs, it is easier to read the program by calling it after declaring the function.

...
<button onclick="alert(&quot;The button was pressed&quot;);">Click me!</button>
...

Practice Exercise 2-

Write a program (function) in the script element and create a program to display “Hello” with an alert when the button is clicked.


Practice Exercise 2-

Write a program to an external file and read it with the script element. When you press the button, create a program to display with “Hello” as an alert.

Practice Exercise 2-

Create a program that makes a variable “0”, “increase by 1”, “decrease by 1”, “times 2”, “1/2”, and when each button is pressed, it performs its operation and displays the result as an alert. Set the initial value of the variable to 0.