A Note of JavaScript Learning
1. Introduction
2. Where to
The script Tag
- In HTML, JavaScript code must be inserted between
<script>
and</scipt>
tags. - Old JavaScript examples may use a type attribute:
<script type="text/javascript">
.
The type attribute is not required. JavaScript is the default scripting language in HTML.
head or body ?
- You can place any number of scripts in an HTML document.
- Placing scripts at the bottom of the
<body>
element improves the display speed, because script interpretation slows down the display.
External JavaScript
-
JavaScript files have the file extension .js.
-
To use an external script, put the name of the script file in the
src
(source) attribute of a<script>
tag: -
Ex:
<script src = "myscript.js"></script>
-
External scripts cannot contain
<script>
tags.
3. Output
Here are several ways to display:
- Writing into an HTML element, using
innerHTML
. - Writing into the HTML output using
document.write()
. - Writing into an alert box, using
window.alert()
. - Writing into the browser console, using
console.log()
.
Using innerHTML
- By using
document.getElementById(id)
to access an element.
Using document.write()
- Using document.write() after an HTML document is loaded, will delete all existing HTML.
- The document.write() method should only be used for testing.
Using window.alert()
Using console.log()
- Use this method to display data for debugging purpose.
Statements
Statements
-
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
Semicolons
- Use semicolons to separate.
- On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.
White Space
- Unnecessary.
- A good practice is to put spaces around operators (
=
+
-
*
/
).
Line Length and Line Breaks
-
For best readability, programmers often like to avoid code lines longer than 80 characters.
-
If a JavaScript statement does not fit on one line, the best place to break it is after an operator.
-
Ex:
document.getElementById("demo").innerHTML = "Hello Dolly!";
-
Code Blocks
-
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together(like a function).
Keywords
04. Syntax
- JavaScript syntax is the set of rules, how JavaScript programs are constructed.
Values
-
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
Literals
- Numbers
- String
- Double or single quotes are allowed.
Variables
- Use
var
keyword to declare variables.
Operators
- JavaScript uses arithmetic operators (
+
-
*
/
) to compute values. - JavaScript uses an assignment operator (
=
) to assign values to variables.
Expressions
- An expression is a combination of values, variables, and operators, which computes to a value.
- The computation is called an evaluation.
- For example, 5 * 10 evaluates to 50.
Comments
- Code after double slashes
//
or between/*
and*/
is treated as a comment. - Comments are ignored, and will not be executed.
Identifiers
- In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).
- Subsequent characters may be letters, digits, underscores, or dollar signs.
Case Sensitive
05. Comments
- This part can be ignored, which is the same as many languages.
06. Variables
One Statement, Many Variablves
-
Start the statement with
var
and separate the variables by comma. -
A declaration can span multiple lines:
Ex:
var person = "John Doe", carName = "Volvo", price = 200;
Value = undefined
- A variable declared without a value will have the value
undefined
.
Re-Declaring JavaScript Variables
-
If you re-declare a JavaScript variable, it will not lose its value.
The variable
carName
will still have the value "Volvo" after the execution of these statements:
Arithmetic
-
If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
**Ex1: **
var x = "5"+2+3
the result is 523.
Ex2:
var x = 2+3+"5"
the result is 55.
06. Operators
- It's like C++ and Python.
- The result will be a string if adding string in it.
Comparison Operators
Operator | Description |
---|---|
== | equal to |
=== | equal value and equal type |
!= | not equal |
!== | not equal value or not equal type |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
? | ternary operator |
Logical Operators
Operator | Description |
---|---|
&& | logical and |
|| | logical or |
! | logical not |
Type operators
Operator | Description |
---|---|
typeof | Returns the type of a variable |
instanceof | Returns true if an object is an instance of an object type |
Bitwise Operators
-
Addition:
>>>
: Zero fill right shift.
07. Data Types
Dynamic
- JavaScript has dynamic types. This means that the same variable can be used to hold different data types.
Null
-
In JavaScript, the data of
null
is an object. -
Empty an object by setting it to
null/undefined
. -
undefined
andnull
are equal in value but different in type.null === undefined //false null == undefined //true
Complex Data
-
The
typeof
operator can return one of two complex types:- `function``
- ``object`
-
The
typeof
operator returns "object" for objects, arrays, and null. -
The
typeof
operator does not return "object" for functions.
08. Functions
Syntax
- A JavaScript function is defined with the
function
keyword, followed by a name, followed by parentheses (). - Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
- The parentheses may include parameter names separated by commas:
(*parameter1, parameter2, ...*) - The code to be executed, by the function, is placed inside curly brackets: {}
Invocation
- When an event occurs (when a user clicks a button)
- When it is invoked (called) from JavaScript code
- Automatically (self invoked)
Return
- The function will stop when reaches a
return
.
The () Operator Invokes the Function
- Using the example above,
toCelsius
refers to the function object, andtoCelsius()
refers to the function result. - Accessing a function without () will return the **function definition **instead of the function result.
Local Variables
- Functions use local variables which will be deleted when the function is completed.
09. Objects
- JavaScript objects are containers for named values called properties or methods.
Definition
Ex:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Accessing Object Properties
-
There are two ways to access properties.
1st.
objectName.propertyName
2nd.
objectName["propertyName"]
Method
- A method is a function stored as a property.
"this"
- Like C++ but not a pointer.
new?
- When a JavaScript variable is declared with the keyword "
new
", the variable is created as an object. - Avoid
String
,Number
, andBoolean
objects. They complicate your code and slow down execution speed.
10. Events
<element event="some JavaScript">
-
Using
this
:<button onclick="this.innerHTML = Data()"> The time is? </button>
-
Calling a function:
<button onclick="displayData()"> The time is? </button>
Common HTML Events
Event | Description |
---|---|
onchange | An HTML element has been changed |
onclick | The user clicks an HTML element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user pushes a keyboard key |
onload | The browser has finished loading the page |
11. Strings
Length
- Use
length
to get the length of the string.
backslash
Code | Result | Description |
---|---|---|
' | ' | Single quote |
" | " | Double quote |
\ | \ | Backslash |
- You can also break up a code line within a text string with a single backslash. But this is not good, and use
+
is acceptable.
new?
- Note the difference between
(x==y)
and(x===y)
.
Comparing two JavaScript objects will always returnfalse
.
11. String Methods
Find Sub String
-
The
indexOf()
method returns the index of (the position of) thefirst
occurrence of a specified text in a string. -
The
lastIndexOf()
method returns the index of the last occurrence of a specified text in a string. -
Both
indexOf()
, andlastIndexOf()
return -1 if the text is not found. -
Both methods accept a second parameter as the starting position for the search:
var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate", 15);
-
The
lastIndexOf()
methods searches backwards (from the end to the beginning), meaning: if the second parameter is15
, the search starts at position 15, and searches to the beginning of the string. -
indexOf()
andsearch()
are different.