0% found this document useful (0 votes)
7 views79 pages

JavaScript Fundamentals and Syntax Guide

The document provides an overview of JavaScript, covering its role in web development, syntax, control structures, functions, and data types. It highlights the differences between JavaScript and Java, explains how JavaScript executes in browsers, and discusses variable scope and types. Additionally, it addresses best practices for using JavaScript, including the use of frameworks and libraries.

Uploaded by

thanh08062004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views79 pages

JavaScript Fundamentals and Syntax Guide

The document provides an overview of JavaScript, covering its role in web development, syntax, control structures, functions, and data types. It highlights the differences between JavaScript and Java, explains how JavaScript executes in browsers, and discusses variable scope and types. Additionally, it addresses best practices for using JavaScript, including the use of frameworks and libraries.

Uploaded by

thanh08062004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

1
Content

1. Introduction
2. JavaScript syntax
3. Control structure and function
4. Array and object
5. Basic DOM and Events

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

2
1. Introduction

3
JavaScript Fundamentals

• With HTML and CSS, could websites become interactive?


• Front-end
• HTML = Structure
• CSS = Design
• JavaScript = Interaction

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

4
Role of JavaScript
• Client slide (Frontend)
• Role: event handling, validation, animations, etc.
• Framework/Libarary: React, Vue, Angular
• Server slide (Backend)
• Role: hande requests, databases, API, etc.
• Framework/Environment: [Link], Express
• Full stack: one language for both Client and Server

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

5
Questions

• Why has JavaScript become one of


the world’s most widely used
programming languages?

• Run everywhere
• Browser: Chrome (V8), Firefox
(SpiderMonkey), Safari
(JavaScriptCore)
• Server: [Link], Deno
• Mobile: React Native, Ionic
• Desktop: Electron
• AI/Data: [Link],
WebGPU
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

6
Questions

• What is the difference between framework and library?


• Library = You call it, e.g., React
• Framework = It calls you, e.g., Vue, Angular

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

7
What is JavaScript?
• Dynamic, prototype-based, and single-threaded
language.
• Supports object-oriented and event-driven paradigms.
• Modern JavaScript is considered an interpreted
language, but is actually executed using Just-In-Time
Compilation (JIT) techniques

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

8
JavaScript vs Java

Feature Java JavaScript


Large, robust Lightweight, simple
Role
applications scripting language
Typing Static, Strong Dynamic, Weak
Interpreted/Just-in-time
Compiled by JVM
Execution complied by JS Engine
Multi-threads
Single thead
Runtime JVM Browser or [Link]
Object model Class-based Prototype-based
Platform Cross-platform Cross-platform

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

9
JavaScript vs Java

• Why do two languages (Java, JavaScript) with similar


names have such opposite design philosophies?

Feature Java JavaScript


1995, Sun
Year 1995, Netscape
Microsystemts
Large, robust Lightweight, simple
Role
applications scripting language
Mocha -> LiveScript ->
Initial Name Oak
JavaScript

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

10
How JavaScript executes in the browser?
• Can JavaScript run multiple tasks at once?
• No
• However it can handle multiple tasks concurrently

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

11
Embedding JavaScript in HTML

• Inline: <button onclick="alert('Hi')">


• Internal: <script> ... </script>
• External: <script src="[Link]"></script>
• Prefer: external JS for scalability
• Place scripts at the end of <body>

Why does placing the


script tag at the bottom?

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

12
2. JavaScript syntax

13
Variable and Scope

• var: function scope/global (old, avoid using)


• let: block scope, can update value
• const: block scope, cannot update value

Why is it considered a bad practice to use var in JavaScript?


TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

14
Variable and Scope

Feature var let / const


Old JS (before ES6,
✅ ❌
2015)
Safe in block-scope ❌ ✅
⚠ Yes (but in
✅ (initialized as
Hoisting Temporal Dead
undefined)
Zone)

Re-declaration ✅ (Allowed) ❌

Global Object ✅ (adds to



Binding window)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

15
Variable and Scope
• Block-scope

• Hoisting: var decalaration is moved to the top of the scope; let and
const: are putted in a Temporal Dead Zone (TDZ) -> safer

• Re-declaration

• Global Object Binding: a var variable is binded to the window object

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

16
Primitive Data Types
• Primitive Data Types
• string
• number
• boolean
• null
• undefined
• symbol
• bigint (ES2020)
• Primitive values are copied by value, not by reference.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

17
Reference Types (Objects, Arrays)

• Reference types are stored as pointers to


memory objects.
• When we assign one variable to another, they
are copied by reference. Changes via one
variable affect the other.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

18
Equality Operator (== vs ===)

• Loose equality
• == compares values only
• allow type coercion: conversion of values from one
data type to another (e.g., string to number)
• Strict equality
• === compares both value and type, no coercion.
• Always prefer === for predictable logic

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

19
Automatic Semicolon Insertion (ASI)
• JavaScript engine automatically inserts semicolons (;) to
fix syntax errors during parsing.

• ASI doesn’t always work as expected — especially with


return statements, array literals, or function calls.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

20
Template Literals and Expression Interpolation

• Template literals use backticks (`) instead of


quotes to represent multi-line strings

• Expression interpolation use ${...} syntax to simplify


string concatenation and dynamic content generation.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

21
Console and Debugging

• The console is part of every JavaScript runtime


• [Link](): general information
• [Link](): object information in table form
• [Link](): object, DOM element in tree form
• Chrome DevTools (F12 → Console tab)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

22
Dynamic Typing in JavaScript

• Variables can hold any type and change type at


runtime.
• No need to declare a variable’s type — JS infers it
automatically.
• Pros: Flexible, fast prototyping
• Cons: Harder to debug type errors; runtime crashes

• TypeScript adds static typing on top of JS to catch errors


(need to install TypeScript Compiler - TSC)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

23
3. Control Statement and Function

24
Control Structure

• Condition: if, else if, else, switch


• Loop: for, while, do…while
• Jump: break, continue, return

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

25
Control Structure

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

26
Control Structure

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

27
Operators

<script type="text/javascript">
const distanceToSun = 93.3e6 * 5280 * 12;
let thickness = .002;
Operators let foldCount = 0;
while (thickness < distanceToSun) {
+, -, *, /, %, ++, --, … thickness *= 2;
foldCount++;
==, !=, <, >, <=, >=
}
&&, ||, !,===,!== [Link]("Number of folds = "
+foldCount);
</script>

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

28
Ternary Operator

• condition ? expressionIfTrue : expressionIfFalse;

• When does using the ternary operator improve clarity


and when does it hurt readability?
• Good: condition is simple & expressions are short
• Not good: condition or expressions are complex

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

29
for...of and for...in

Loop Type Iterates Over Works Best With


for…of Values Arrays, strings, collections
for…in Keys/property names Objects (key–value pairs)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

30
Function: Declaration and Expression

• A function is a reusable block of code designed to


perform a specific task.
• Two main ways to define a function
Type Syntax Hoisting Use Case
function name() { named reusable
Declaration ✅ Fully hoisted
... } functions
const name = passing as
Expression ❌ Not hoisted
function() {... }; arguments

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

31
Functions as Data

• In JavaScript, functions are objects (First-class functions)


• Assign a function to a variable
• Return a function from another function
• Pass a function as an argument to another function (callback)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

32
Arrow Function

• A concise way to write anonymous functions.


• Syntax uses the => (arrow) symbol.
• They are often used for: short callbacks, array methods,
inline event handlers

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

33
Closure

• A closure: is a function that “remembers” variables from


the scope where it was created — even after that scope
has finished executing.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

34
Closure

• Closure can maintain a private, persistent state that is


protected from external code.
• counterA and counterB are separate closures

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

35
Programming Mindset: Flexibility over Safety

• JavaScript gives you freedom — but freedom


without discipline is chaos
• The compiler won’t stop you from doing risky things.
• Mistakes often show up only at runtime, not compile
time.
• Approaches
• Typing: validate inputs and use TypeScript
• ASI: syntax conventions
• Implicit conversion: understand coercion rules

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

36
4. Array and Object

37
Array

• Dynamic size:
• JavaScript arrays can grow (add elements) or shrink
(remove elements) at runtime.
• Users don’t need to predefine their length as in C
• Untyped / Heterogeneous:
• A JavaScript array can hold different data types in
the same structure.
• Example: numbers, strings, objects, even functions
— all in one array.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

38
Basic Array Operations

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

39
Array Iteration

• forEach(): runs a function on each element


• map(): creates a new array with tranformed values
• filter(): creates a new array with a condition
• reduce(): reduces an array to one value (e.g, sum)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

40
Objects

• An object contains list of properties.


• A property is a “key:value” pair, where key is a string
and value can be anything.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology
Objects

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology
Objects

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology
Copy Object

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology
Garbage collection

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology
Garbage collection

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology
Garbage collection

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology
String Object

• JavaScript supports both primitive strings and String objects.

• JavaScript allow primitive strings to call methods. JavaScript


temporarily wraps a primitive string in a String object (Auto-
Boxing or Temporary object)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

48
Class

• A template for creating objects

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

49
JSON
• JSON (JavaScript Object Notation) is a lightweight
format for data exchange.
• Send data to server: convert a JavaScript object →
string format

• Receive data from server: convert that string → object.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

50
5. Basic DOM and Event

51
DOM

• DOM (Document Object Model) is a tree-like


representation of an HTML document.
• Every HTML element is a node in the DOM tree.
• It allows JavaScript to access, traverse, and manipulate
the structure, content, and style of a webpage.

=> DOM is the bride between HTML and JavaScript

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

52
DOM Tree and Node Types
• Each HTML tag, piece of text, or attribute is a node in the tree.

Node Type Description Example


Document Node Root of the DOM tree document

Element Node HTML tags <h1>, <p>, <div>

Text Node Text content "Hello"

Attribute Node Attributes of elements id="title"

Comment Node
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
HTML comments
School of Information and Communication Technology <!-- note -->
53
Searching: [Link](id)

• If an element has the id attribute, we can get the element


using [Link](id)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

54
Searching: getElementsBy*

• [Link](tag)
e.g., [Link]("td");

• [Link](className)
e.g., [Link]("example");

• [Link](name)
e.g., <input name="animal" type="checkbox" value="Cats">
[Link]("animal");

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

55
Searching: querySelectorAll

• The most versatile method:


[Link](css)
• Any CSS selector can be
used

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

56
Searching: querySelectorAll

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

57
Searching: querySelector

• [Link](css) returns the first element


for the given CSS selector

• The result is the same


as [Link](css)[0]
• The latter is looking for all elements and picking one
• [Link] just looks for one. So it’s faster and
also shorter to write.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

58
Searching: Summary

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

59
The “nodeType” property

• The nodeType property provides one more,


“old-fashioned” way to get the “type” of a DOM
node.
• It has a numeric value:
• [Link] == 1 for element nodes,
• [Link] == 3 for text nodes,
• [Link] == 8 for comment nodes,
• [Link] == 9 for the document object

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

60
“nodeType” property example

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

61
innerHTML: the contents

• The innerHTML property allows to get the HTML inside


the element as a string.
• We can also modify it. So it’s one of the most powerful
ways to change the page.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

62
outerHTML: full HTML of the element

• The outerHTML property contains the full


HTML of the element.
• That’s like innerHTML plus the element itself.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

63
nodeValue/data: text node content

• The innerHTML property is only valid for element nodes.


• Other node types, such as text nodes, have their
counterpart: nodeValue and data properties.
• These two are almost the same for practical use.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

64
Walking the DOM

• Child nodes (or children):


elements that are direct
children

• Descendants – all
elements that are nested
in the given one,
including children, their
children and so on.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

65
Children: childNodes

• The childNodes collection lists all child nodes,


including text nodes.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

66
Children: firstChild, lastChild

• Properties firstChild and lastChild give fast


access to the first and last children
• If there exist child nodes, then the following is
always true:

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

67
Modifying the document

• DOM modification is the key to creating “live” pages.


• To create DOM nodes, there are two methods:

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

68
Insertion methods

• [Link](...nodes or strings) – append


nodes or strings at the end of node,
• [Link](...nodes or strings) – insert nodes
or strings at the beginning of node,
• [Link](...nodes or strings) – insert nodes
or strings before node,
• [Link](...nodes or strings) – insert nodes or
strings after node,
• [Link](...nodes or strings) –
replace node with the given nodes or strings.

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

69
Insertion methods

• Here’s a visual picture of what the methods do:

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

70
Event – The Reaction Mechanism of the Web

• An event is an action or occurrence that


happens in the browser — to which JavaScript
can react.
• User clicks a button
• User types in an input box
• Page loads or scrolls
• Common Event types
• Mouse: click, dbclick, mouseover, mouseout
• Keyboard: keydown, keyup, keypress
• Form: submit, change, focus
• Window/Document: load, resize, scroll

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

71
Node properties: hierarchy

Every node in the DOM can listen for events (EventListener)


TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

72
EventTarget
Method Purpose / Description
Register a function that will be called
addEventListener()
whenever the specified event occurs
Remove a previously added event listener
removeEventListener()
so it no longer responds to the event.
dispatchEvent() Manually triggers an event on the target

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

73
Attaching Event Handler

• Inline (HTML level)

• DOM property

• addEventListener (prefered)

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

74
Event Object

• Browser automatically creates an event object when an


event happens
• Named e or event that contains all details about that
specific event.

Properties

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

75
DOM and JavaScript

Aspect Document Object Model JavaScript


A tree-like object model A programming language
Nature created by the browser to used to control logic, handle
represent HTML document. data, and manipulate DOM.
Standardization W3C / WHATWG. ECMA (ECMAScript).
Objects: document, window, Data types (number,
Node, Event, etc. string...),
Components
Methods: getElementById(), Control structures
createElement(), etc. functions, classes, etc.
Automatically created by the
Written by developers and
Created By browser when loading an
executed by the JS engine
HTML page.
Access & modify web page Control logic & interact with
Aspect
content DOM

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

76
DOM and JavaScript

• DOM + JavaScript = Dynamic UI


• JavaScript can change HTML, CSS, and
behavior in realtime

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

77
Exercises

• Ex1. Define factorial fuction


• Ex2. Given an array of objects (e.g., a list of
students with name and score), use the array
methods (map, filter, reduce) to calculate the
average score.
• Ex3. Create a button and a text paragraph. Add an
Event Listener to the button so that every time it is
clicked, a text is shown/hiden by changing its CSS
class.
• Ex4. Create an input field and a button. When the
button is clicked, take the text from the input,
create a new <li> element and append it to an
unordered list (<ul>).

TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG


School of Information and Communication Technology

78
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology

79

You might also like