JS is a cross-platform, object-oriented scripting language used to control webpage behavior and make pages interactive.
Ways to Import JS
There are two main ways: internal and external scripts.
Internal Scripts
Define JS code directly within an HTML page.
- JS code must be placed between
<script></script>tags. - You can place any number of
<script>tags anywhere in the HTML document. - Usually, scripts are placed at the bottom of the
<body>element to improve page load speed.
| |
External Scripts
Define JS code in an external .js file, then import it into the HTML page.
- External JS files contain only JS code, without
<script>tags.
| |
JS file content:
| |
JS Basic Syntax
JS is case-sensitive. Semicolons at the end of lines are optional. There are two types of comments:
| |
Curly braces denote code blocks.
| |
Output Statements
You can output data to alert boxes, the HTML page, or the console.
| |
Variables
JS is a weakly typed language. Variables can hold values of different types. Variable names should follow these rules:
- Characters can be letters, digits, underscores, or dollar signs.
- Cannot start with a digit.
- CamelCase is recommended.
There are three keywords for defining variables: var, let, and const.
var
Short for “variable”. Variables declared with var are global (or function-scoped) and can be re-declared.
| |
let
Introduced in ECMAScript 6. Variables declared with let are block-scoped and cannot be re-declared within the same scope.
| |
const
Used to declare read-only constants. Once declared, the value cannot be changed.
| |
Data Types
JS has primitive types and reference types (objects).
There are five primitive types:
- number: Numbers (integers, decimals, NaN (Not a Number))
- string: Strings, single or double quotes are both fine
- boolean: true and false
- null: Empty object reference
- undefined: Default value when a declared variable isn’t initialized
Use the typeof operator to check the data type.
| |
You might wonder why
typeof nullreturns “object”. This is a legacy bug from the original JavaScript implementation that was kept for backward compatibility. Now,nullis considered a placeholder for an object, explaining the contradiction, though technically it is still a primitive.Reference: https://www.w3school.com.cn/js/pro_js_primitivetypes.asp
Operators
- Arithmetic: +, -, *, /, %, ++, –
- Assignment: =, +=, -=, *=, /=, %=
- Comparison: >, <, >=, <=, !=, ==, ===
- Logical: &&, ||, !
- Ternary: condition ? true : false
==vs===
==performs type conversion before comparing.===(strict equality) does not; both type and value must match to be true.
| |
Type Conversion
Use parseInt() to convert strings to numbers.
Conversion starts from the first character and stops at the first non-numeric character. If the first character is non-numeric, it returns NaN.
| |
Boolean conversion:
- Number: 0 and NaN are false, others are true.
- String: Empty strings are false, others are true.
- Null and undefined: Both are false.
| |
Flow Control
- if…else if…else
- switch
- for
- while
- do…while
Reference: https://www.w3school.com.cn/jsref/jsref_statements.asp
Functions
Functions are blocks of code designed to perform specific tasks.
There are two ways to define them. Standard syntax:
| |
Key points:
- Parameters don’t need types.
- Return values don’t need defined types; just use
return.
| |
Alternative syntax (Anonymous function / Expression):
| |
Example:
| |
In JS, you can call a function with any number of arguments, but it only accepts the number of parameters defined in the signature.
Objects
Includes basic objects, Browser Object Model (BOM), and Document Object Model (DOM).
Array
Definition method 1:
| |
Definition method 2 (Literal):
| |
Access and assignment:
| |
Arrays are dynamic in size and can store any data type.
| |
Properties
The length property returns the number of elements. Use it to iterate.
| |
Methods
| Method | Description |
|---|---|
| forEach() | Iterates through each defined element and calls a callback function |
| push() | Adds new elements to the end and returns the new length |
| splice() | Removes elements from an array |
forEach iteration:
| |
Simplify with arrow functions:
| |
push:
| |
splice:
| |
Difference between iterations
A for loop iterates through all indices, including undefined holes. forEach only iterates over elements that actually have values.
| |
String
Two ways to create:
| |
Properties and Methods
| Property/Method | Description |
|---|---|
| length | String length |
| charAt() | Returns character at specified index |
| indexOf() | Searches for a substring |
| trim() | Removes whitespace from both ends |
| substring() | Extracts characters between two specified indices |
| |
Custom Objects
Definition format:
| |
Example:
| |
Method shorthand:
| |
JSON
JavaScript Object Notation. JSON is text written in JavaScript object notation. Because of its simple syntax and clear structure, it’s widely used for data transfer across networks.
Definition:
| |
JSON value types:
- Numbers (int or float)
- Strings (in double quotes)
- Booleans (true or false)
- Arrays (in square brackets)
- Objects (in curly braces)
- null
Convert object to JSON string:
| |
Convert JSON string to object:
| |
BOM
Browser Object Model. Allows JS to “talk” to the browser. JS encapsulates browser components into objects.
- Window: Browser window object
- Navigator: Browser info object
- Screen: Screen info object
- History: Browser history object
- Location: URL bar object
Window
The browser window object can be used directly; the window. prefix is optional.
Properties:
| Property | Description |
|---|---|
| history | Read-only reference to History |
| location | Location object for the window |
| navigator | Read-only reference to Navigator |
Methods:
| Method | Description |
|---|---|
| alert() | Shows an alert box with a message and OK button |
| confirm() | Shows a dialog with message, OK, and Cancel |
| setInterval() | Calls a function repeatedly at specific intervals |
| setTimeout() | Calls a function once after a specific delay |
| |
Location
Address bar object, accessed via window.location (or just location).
The href property can set or return the full URL.
| |
DOM
Document Object Model. Encapsulates parts of the markup language into objects.
DOM is a W3C standard for accessing HTML and XML documents, split into three parts:
- Core DOM - Standard model for all document types
- Document: Entire document
- Element: Element objects
- Attribute: Attribute objects
- Text: Text content
- Comment: Comment objects
- XML DOM - Standard model for XML
- HTML DOM - Standard model for HTML
- Image:
<img> - Button:
<input type='button'>
Via DOM, JS can manipulate HTML:
- Change content
- Change styles (CSS)
- React to events
- Add/Remove elements
HTML Element objects are retrieved via the document object (which comes from window).
Retrival functions:
- By
id: Returns a single Element.
| |
- By tag name: Returns an array of Elements.
| |
- By
nameattribute: Returns an array of Elements.
| |
- By
classattribute: Returns an array of Elements.
| |
HTML Example for above:
| |
Once you have the element, you can modify it. Check the HTML Object reference on W3School for more.
Example: Changing text of the first <a> tag:
| |
Event Listening
Events are things that happen to HTML elements, like clicks, mouse movement, or key presses. JS can execute code when these events are detected.
Event Binding
Method 1: Binding via event attributes in HTML tags.
| |
Method 2: Binding via DOM element properties.
| |
Common Events
| Event Name | Description |
|---|---|
| onclick | Mouse click |
| onblur | Element loses focus |
| onfocus | Element gains focus |
| onload | Page or image finished loading |
| onsubmit | Form submission |
| onkeydown | Key is pressed |
| onmouseover | Mouse moves over an element |
| onmouseout | Mouse moves out of an element |