JavaScript functions
A function is an event-driven or reusable block of code that executes when it is invoked.
JavaScript function syntax
A function is a block of code wrapped in curly braces, preceded by a keyword function:
When the function is called, the code inside the function is executed. A function can be called directly at the time of an event, and can be called at any location.
function functionname () {Here is the code to execute}
Calling a function with parameters
When you call a function, you can pass a value to it, which is called a parameter. These parameters can be used in functions. separated by commas (,).
function MyFunction (Argument1,argument2) {Here is the code to execute}
function with return value
Sometimes, we want the function to return the value to the place where it was called. This can be achieved by using the return statement.
When you use the return statement, the function stops execution and returns the specified value.
Local JavaScript variables
A variable declared inside a JavaScript function (using VAR) is a local variable that can only be accessed inside the function. (The scope of the variable is local).
As soon as the function is complete, the local variable is deleted.
Global JavaScript variables
Variables declared outside of a function are global variables, and all scripts and functions on a Web page can access it.
The lifetime of a JavaScript variable
The lifetime of JavaScript variables begins at the time they are declared.
Local variables are deleted after the function is run. Global variables are deleted after the page is closed.
Assigning a value to an undeclared JavaScript variable
If you assign a value to a variable that has not been declared, the variable is automatically declared as a global variable.
Carname= "Volvo"; [A global variable is declared carname, even if it executes within a function.] ]
************************************
JavaScript is case sensitive. The keyword function must be lowercase and must be called with the same casing as the function name.
Variables and parameters must appear in a consistent order. The first variable is the given value of the first parameter passed, and so on.
The function is flexible, and you can call the function with different parameters, giving you a different message:
<Script>functionmyFunction (name,job) {alert ("Welcome" +name+ ", the" +job);}</Script><Buttononclick= "MyFunction (' Harry Potter ', ' Wizard ')">Click here</Button><Buttononclick= "myFunction (' Bob ', ' Builder ')">Click here</Button>
Depending on the button you clicked, the example above would suggest "Welcome Harry Potter, the wizard" or "Welcome Bob, the Builder".
After the return statement, the entire JavaScript does not stop executing, just the function. JavaScript will continue to execute code from where the function is called.
You can also use the return statement when you just want to exit the function, and the return value is optional.
You can use local variables with the same name in different functions, because only the function that declares the variable can recognize the variable.
************************************
JavaScript operators
operator = is used to assign a value.
operator + is used to add values.
JavaScript arithmetic operators
Arithmetic operators are used to perform arithmetic operations between variables and/or values.
JavaScript Assignment operators
Assignment operators are used to assign values to JavaScript variables.
The + operator for strings
The + operator is used to add a literal value or a string variable (to join together).
adding arithmetic to strings and numbers
If you add a number to a string, the result becomes a string.
************************************
Given y=5, these arithmetic operators are explained in the following table:
Operator describes example results
+ Plus x=y+2x=7
-Minus X=y-2x=3
* by x=y*2x=10
/except x=y/2x=2.5
% for remainder (reserved integers) x=y%2x=1
+ + Cumulative X=++yx=6
--Descending x=--yx=4
Given x=10 and y=5, the following table explains the assignment operator:
The operator example is equivalent to the result
=x=y x=5
+=x+=yx=x+yx=15
-=x-=yx=x-yx=5
*=x*=yx=x*yx=50
/=x/=yx=x/yx=2
%=x%=yx=x%yx=0
Txt1= "What a very";
Txt2= "Nice Day";
TXT3=TXT1+TXT2;
After executing the above statement, the variable TXT3 contains the value "What a Verynice Day".
************************************
JavaScript comparison and logical operators
Comparison and logical operators are used to test for true or false.
Comparison operators
Comparison operators are used in logical statements to determine whether a variable or value is equal.
You can use comparison operators to compare values in conditional statements and then take action based on the results.
[If (age<18) document.write ("Too Young");]
logical operators
Logical operators are used to determine the logic between variables or values.
Conditional operators
JavaScript also includes conditional operators that assign values to variables based on certain conditions.
************************************
Given x=5, the following table explains the comparison operators:
Operator Description Examples
= = equals x==8 to False
= = = Congruent (value and type) x===5 to true;x=== "5" is false
! = does not equal x!=8 to True
> Greater than X>8 to False
< less than X<8 is true
>= greater than or equal to x>=8 false
<= less than or equal to X<=8 is true
Given X=6 and y=3, the following table explains the logical operators:
Operator Description Examples
&&and (x < && y > 1) True
|| or (x==5 | | y==5) is false
!not! (x==y) is true
Conditional operators
Greeting= (visitor== "PRES")? " Dear president ":" Dear ";
If the value in the variable visitor is "PRES", assign a value of "Dear president" to the variable greeting, otherwise assign a value of "Dear".
************************************
JavaScript If ... Else statement
Conditional statements are used to perform different actions based on different conditions.
Conditional statements
Often when writing code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.
In JavaScript, we can use the following conditional statements:
1.if Statement-Use this statement to execute code only if the specified condition is true
2.if...else Statement-executes code when the condition is true and executes other code when the condition is false
3.if...else If....else Statement-Use this statement to select one of several code blocks to execute
4.switch Statement-Use this statement to select one of several code blocks to execute
If statement
The statement executes code only if the specified condition is true.
If...else statements
Use the If....else statement to execute an if code when the condition is true, and to execute the else code when the condition is false.
If...else if...else Statements
Use the If....else if...else statement to select one of several code blocks to execute.
************************************
Please use the lowercase if. Using uppercase letters (IF) generates JAVASCRIPT errors!
if (condition) {code executed when the condition is true}
else{code to execute when the condition is not true}
if (condition 1) {code executed when condition 1 is true}
else if (condition 2) {code executed when condition 2 is true}
else{code executed when condition 1 and condition 2 are not true}
************************************
JavaScript Switch Statement
The switch statement is used to perform different actions based on different conditions. Use the switch statement to select one of several code blocks to execute.
Default keyword
Use the default keyword to specify what to do when a match does not exist
************************************
Switch (n)
{Case 1: Execute code block 1;break;
Case 2: Execute code block 2;break;
Default:n code to execute when different from Case 1 and 2}
How it works: first set an expression n (usually a variable). The value of the subsequent expression is compared to the value of each case in the structure. If there is a match, the code block associated with the case is executed. Use break to prevent your code from automatically running down a case.
If there is no break after the code block, he will execute until the end, and all subsequent case will be executed.
************************************
JavaScript for Loop
A loop can execute a code block for a specified number of times.
JavaScript Loops
If you want to run the same code over and over again, and the values are different each time, it is convenient to use loops.
Different types of loops
JavaScript supports different types of loops:
1.for-Loop code block for a certain number of times
2.for/in-Looping through the properties of an object
3.while-Loops the specified block of code when the specified condition is true
4.do/while-also loops the specified block of code when the specified condition is true
For loop
A For loop is a tool that you will often use when you want to create loops.
for (statement 1; Statement 2; Statement 3)
{The code block being executed}
[Statement 1 executes before the Loop (code block) starts; Statement 2 defines the condition that runs the Loop (code block); Statement 3 executes after the Loop (code block) has been executed]
Statement 1
Typically we use statement 1 to initialize the variable (var i=0) used in the loop. Statement 1 is optional, that is, you do not use statement 1.
Statement 2
Typically statement 2 is used to evaluate the condition of the initial variable. If statement 2 returns True, the loop starts again, and if False is returned, the loop ends.
Statement 3
Usually statement 3 increases the value of the initial variable. Statement 3 is also optional.
For/in Cycle
JavaScript for/in statement loops through the properties of an object
************************************
You can initialize any (or more) of the values in statement 1. You can also omit statement 1 (such as when a value has been set before the loop starts).
When statement 2 is omitted, a break must be provided within the loop. Otherwise, the loop cannot be stopped. This may cause the browser to crash.
Statement 3 has several uses. The increment can be arbitrary. Statement 3 can also be omitted (for example, when there is a corresponding code inside the loop).
var person={fname: "John", lname: "Doe", age:25};
for (x in person)
{txt=txt + person[x];}
Will output: BILLGATES56
************************************
JavaScript while loop
Loops can execute code all the time, as long as the specified condition is true.
While loop
The while loop executes a code block when the specified condition is true.
Do/while Cycle
The Do/while loop is a variant of the while loop. The loop executes a block of code once, before checking whether the condition is true, and then repeating the loop if the condition is true.
The loop executes at least once, even if the condition is false, and the hidden code block executes before the condition is tested.
************************************
If you forget to increase the value of the variable used in the condition, the loop never ends. This may cause the browser to crash.
************************************
JavaScript Break and Continue statements
The break statement is used to jump out of a loop. The Continue is used to skip an iteration in the loop.
Break statement
The break statement can be used to jump out of a loop. After the break statement jumps out of the loop, the code after the loop continues to execute (if any)
Continue statements
The continue statement interrupts the iteration in the loop, if the specified condition occurs, and then resumes the next iteration in the loop.
JavaScript tags
As you saw in the switch statement chapter, you can tag JavaScript statements.
To mark a JavaScript statement, precede the statement with a colon: Label: statement
************************************
The break and continue statements are just statements that can jump out of a block of code.
Continue statements (with or without label references) can only be used in loops.
The break statement (without a label reference) can only be used in loops or switch.
With a label reference, the break statement can be used to jump out of any JAVASCRIPT code block:
************************************
JavaScript errors-Throw, Try, and Catch
The TRY statement tests the code block for errors. The catch statement handles the error. The throw statement creates a custom error.
Mistakes are bound to happen.
When the JavaScript engine executes JavaScript code, various errors occur:
1. It may be a grammatical error, usually a coding error or typos caused by a programmer.
2. Possible spelling errors or missing features in the language (possibly due to browser differences).
3. Errors may be caused by error output from the server or user.
4. This may be due to many other unpredictable factors.
JavaScript throws an error
When an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message-----JavaScript throws an error.
JavaScript Testing and capturing
The Try statement allows us to define a block of code that performs error testing at execution time. The catch statement allows us to define a block of code that executes when a try block of code has an error.
The JavaScript statement try and catch are paired occurrences.
Throw statement
The throw statement allows us to create custom errors. The correct technical term is: Create or throw an exception (exception).
If you use throw with try and catch, you can control the flow and generate custom error messages.
************************************
An exception can be a JavaScript string, a number, a logical value, or an object.
************************************
JavaScript Form Validation
JavaScript can be used to validate these input data in an HTML form before the data is sent to the server.
JavaScript Form Validation
JavaScript can be used to validate these input data in an HTML form before the data is sent to the server.
These typical forms of data that are validated by JavaScript are:
1. Has the user filled in the required fields in the form?
2. Is the email address entered by the user legal?
3. Has the user entered a valid date?
4. Does the user enter text in the Data field (numeric field)?
Required (or required) items
The following function is used to check whether the user has filled out the required (or required) items in the form. If the required or required option is empty, the warning box pops up, and the return value of the function is false, otherwise the return value of the function is true (meaning there is no problem with the data):
function validate_required (field,alerttxt) {with (field) {if (value==null| | value== "") {alert (alerttxt); return False}else {return true}}}
E-mail verification
The following function checks whether the input data conforms to the basic syntax of an e-mail address.
This means that the data entered must contain the @ symbol and the dot (.). At the same time, @ cannot be the first character of the email address and must have at least one dot after @:
function Validate_email (field,alerttxt) { with (field) {apos=value.indexof ("@") dotpos=v Alue.lastindexof ("." ) if (apos<1| | Dotpos-apos<2) {alert (alerttxt);
return false; }else {returntrue}}}
************************************
************************************
Knowledge Summary for JavaScript Basics--[2]