0% found this document useful (0 votes)
5 views29 pages

JavaScript Notes

The document provides a comprehensive overview of JavaScript, covering its fundamental concepts such as variables, data types, operators, conditional structures, loops, functions, and modules. It emphasizes JavaScript's role in web programming, including DOM manipulation and event handling. Additionally, it introduces CommonJS and ES6 module systems for code organization and reuse in JavaScript applications.

Uploaded by

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

JavaScript Notes

The document provides a comprehensive overview of JavaScript, covering its fundamental concepts such as variables, data types, operators, conditional structures, loops, functions, and modules. It emphasizes JavaScript's role in web programming, including DOM manipulation and event handling. Additionally, it introduces CommonJS and ES6 module systems for code organization and reuse in JavaScript applications.

Uploaded by

qvnv2nwdq2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

1

KNOWLEDGE JAVA SCRIPT


1. The variables, operators and the Display with JS (console.log() function)
2. Introduce a JavaScript script inside a HTML page (inside and outside)
3. Make Conditional structures : if, else
4. The loops: For loop
5. Work with functions in JS
6. Work with Modules
7. JAVASCRIPT for Web programing
7.1. DOM manipulation
7.2. Event handling
2

• JavaScript is a scripting programming language primarily used in interactive web pages and as such
is an essential part of web applications. Along with HTML and CSS, JavaScript is at the heart of the
languages used by web developers. A large majority of websites use it, and the majority of web
browsers have a JavaScript engine to interpret it.
• JavaScript is also used for web servers with the use of (for example) Node.js or Deno.

• JavaScript was created in 1995 by Brendan Eich and integrated into the Netscape Navigator 2.0
web browser.
3

1. The variables, operators and the Display with JS


(console.log() function)

JavaScript Variables can be


declared in 4 ways:
•Automatically
•Using var
•Using let
•Using const
• The var keyword was used in all JavaScript
code from 1995 to 2015.
• The let and const keywords were added to
JavaScript in 2015.
• The var keyword should only be used in code
written for older browsers.
4

VARIABLE OR DATA TYPES

• Integer
• Float
• Boolean (false/true)
• String ( note: “string.length” gives the size of the string)

We can also have some data structures like :


 Arrays
 Dictionaries
 Stacks and queues
5
CONSOLE.LOG
THIS FUNCTION OR METHOD HELPS TO WRITE AN ELEMENT ON THE CONSOLE.

Example 1: Example 2:
let x = 2; let z = "Good morning"
console.log("Hello World !")
console.log(x) console.log("Hello World ! " + z)

Output: Output :
2 Hello World !
Hello World ! Good morning
• Using of the back quotations
Example 3
let a = 10
let b = 5
console.log(`${a} is greater than ${b}` )

Output:
10 is greater than 5
6
2. INTRODUCE A JAVASCRIPT SCRIPT INSIDE A HTML
PAGE (INSIDE AND OUTSIDE)

• Use the tag <script></script>


Inside : Outside :
In the same HTML file In a separate file with the extension .js

<script> <script type="text/javascript" src


Your JavaScript =“./JS_file.js” > </script>
instructions
</script>

Note: In the attribute src, the JS file


path should be well written. It is
possible to use the relative path as well
as the absolute path
7

HOW TO RUN JAVASCRIPT?


• Passing by the browser ( that is the way principally used in this course)
- Create a HTML file.
- Insert the JavaScript code by using the outside or the inside method via the
tag <script></script>
- Open the HTML file on the browser.
- Right click of the page displayed in the browser and select inspect, then go to
console tab.

• Using Node
- In the terminal just type : node JavaScript_file.js
8 Addition Operator a+b
Add two numbers or
concatenate the string

Difference between
Subtraction Operato a-b the two operators
r Comparison
Multiplication Opera a*b Multiply two number operators
tor
Find the quotient of Operat Descript Compari Returns
Division Operator a/b two operands
or ion ng
Find the remainder of
Modulus Operator a%b two operands == equal to x == 8 false

Raise the Left operator x == 5 true


Exponentiation Ope a**b to the power of the
x == "5" true
rator right operator

Return the operand


=== equal x === 5 true
and then increase by value
a++ x === false
Increment Operator one and
++a Increase operand by "5"
equal
one and then return
type
Return operand and
a--
!= not equal x != 8 true
then decrease by one
Decrement Operato
r --a Decrease operand by !== not equal x !== 5 false
one and then return
value or
Unary Plus(+) +a
Converts NaN to not equal
number type
Converts operand to
Unary Negation (-) -a
9

Logical
operators
Operator Description Example

&& and (x < 10 && y > 1)


is true

|| or (x == 5 || y == 5)
is false

! not !(x == y) is true


10

3. MAKE CONDITIONAL STRUCTURES : IF, ELSE

You can use conditional statements in your code to do this.


In JavaScript we have the following conditional statements:
•Use if to specify a block of code to be executed, if a specified condition is true
•Use else to specify a block of code to be executed, if the same condition is false if (condition1) {
•Use else if to specify a new condition to test, if the first condition is false // block of code to be executed
•Use switch to specify many alternative blocks of code to be executed if condition1 is true
• if (condition) { } else if (condition2) {
// block of code to be executed
// block of code to be executed if the condition1 is false and
if the condition is true condition2 is true
} else {
}
// block of code to be executed
if the condition1 is false and
condition2 is false
}
11

4. FOR LOOP
LOOPS CAN EXECUTE A BLOCK OF CODE SEVERAL TIMES. THEY ARE USED TO AVOID
REPETITION OF LINE OF CODES

for (initialization; condition ; incrementation) {


// code block to be executed
}

Initialization example : let i = 0


Condition example : i < 100
Incrementation example : i++
12

5- WORK WITH FUNCTIONS IN JS


Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is
similar to a procedure—a set of statements that performs a task or calculates a value, but for a
procedure to qualify as a function, it should take some input and return an output where there
is some obvious relationship between the input and the output.
function function_name(parameter1,
parameter2,…) {
// code to be executed
}
Arrow functions:
function_name = function(param1,param2,
…) {
// code to be executed
}

function_name = (param1,param2,…) => {


// code to be executed
}
13

SOME SPECIAL FUNCTIONS OR METHODS


• isNAN()
• map() for arrays
• Function “this”
14

5- WORK WITH MODULES

Prerequisite :

Install a local server like XAMPP of WAMP


Install node.js if possible
15

In most programming paradigms, we can find a module system that allows us to organize
our code in different self-organized parts or include code from other libraries. Modularization
(usage of modules) is a fundamental tool within software development to increase code
reuse, enable parallel development, and reduce testing effort. This helps you to split your
code in small parts that facilitate the development and the maintenance of your application.

As far as concerning JavaScript programing language, we will see two module system:
- CommonJS
- ES modules
16

COMMONJS

• How to use it?


o In the file where you want to use the module
CommonJS modules must be
loaded from a module repository, const name = require
such as npm. It works generally (‘module_path’);
with Node js platform. o in the module

exports.element_to_import_name =
element_to_import_name ;
17

COMMONJS EXAMPLE (COMPARE TWO


ELEMENTS)
• Module file:
• Other JavaScript file
mod_test.js test.js
function compare(a,b){
const mod_func =
if ( a>b ) {
require('./mod_test.js') ;
console.log(`${a} is greater than ${b}` );
}
else { let a = 5;
console.log(`${b}`+ " is greater than " +`${a}` );
let b = 6;
}
console.log(`a = ${a} and b = ${b}`)
}

exports.compare = compare; mod_func.compare(a,b)

To run it : node
test.js
18

ES6 MODULES (ES MEANS ECMASCRIPT)

• How to use it?


o In the file where you want to use the module:
The ECMAScript modules (in short ES modules) is a import {element_to_import} from
JavaScript modules format which is the official
‘./module_name.js'
standard format to package JavaScript code for
o in the module :
reuse. The ES modules format generally offers an

easier route to writing isomorphic JavaScript, which


export before the element that you want to import
can run in the browser or on a server. Or
At the end of the module: export{element_to_import};
19

ES6 MODULES EXAMPLE

• Module file • HTML FILE


<script type=“module">
mod_test.js
import {compare,add} from ‘./mod_test.js'
export function compare(a,b){
if ( a>b ) { let a = 15
console.log(`${a} is greater than ${b}` );
let b = 15.5
}
else { console.log(a)
console.log(`${b}`+ " is greater than " +`${a}` ); compare(a,b)
} console.log(add(a,b))
}

const add = (a,b) =>{ </script>


return a+b
}

export{add};

To run it : open the HTML file passing by your local


server
JAVASCRIPT FOR WEB PROGRAMING
20 7.1. DOM MANIPULATION

It is like a tree What is the DOM?


The DOM is a W3C (World Wide Web
Consortium) standard.
The DOM defines a standard for accessing
documents:
"The W3C Document Object Model (DOM) is a
platform and language-neutral interface that
allows programs and scripts to dynamically
access and update the content, structure, and
style of a document."
The W3C DOM standard is separated into 3
different parts:
Core DOM - standard model for all document
types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML
documents
21
Two important objects in JavaScript to know:

• window : It gives useful information about the whole browser window, like the
inner width, the position of the scroll. As an object it has methods (or
functions) like alert( ) and properties like inner width, scrollY…
Example : try these commands on your .js file
console.log(window);
console.log(window.innerWidth);
window.alert(‘text’);

• document: its allows to get access to the DOM html.


Example : try these commands on your .js file
console.log(document.documentURI);
console.log(document.getElementById(‘idName’));
let text document.getElementById(‘idName’);
console.log(text.)
console.log(text.innerHTML)
22
METHODS AND PROPERTIES
Method Description
Finding document.getElementById(id) Find an element by element id
HTML
elements document.getElementsByTagName Find elements by tag name
(name)
document.getElementsByClassNa Find elements by class name
me(name)
Property Description
element.innerHTML = new html
Change the inner HTML of an element
content
element.innerText = new text
Change the inner text of an element
content
Changing Change the attribute value of an HTML
element.attribute = new value
HTML element
elements element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(‘attribute’, Change the attribute value of an HTML
‘value’) element

element.getAttribute(‘attribute’) Return the value of the


attribute
23 QUERY SELECTORS

• They can be used in replacement of


the getElementBy… methods
• The elements can be identified by
using the same syntax as in a CSS
file that is using CSS selector
• How does it work?
o document.querySelector(‘.className’)
o document.querySelectorAll(‘.className
’) returns an array of all the elements
with the same className
o document.querySelector(‘#idName’)
o document.querySelector(‘tagName’)
24 ADDING AND DELETING HTML ELEMENTS

Method Description
document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream


25 APPLICATION EXERCISE

Modify a web page using a js file thanks to the DOM


manipulation:
• Modify a text
• Modify a HTML command line
• Select elements by their class name and display their
values. Modify the text
• Select elements by their tags and display their values.
Modify the text inside these elements
26

HOW TO CHANGE THE STYLE (CSS) OF HTML


ELEMENTS?
 Example

<html>
<body>
• document.getElementById(id)
<p id="p2">Hello World!</p>
.style.property = new style
<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.backgroundcolor
= “#aaa";
</script>

</body>
</html>
27

Note :
The property classList allows to obtain the class list inside an element :
By doing classList.add(‘className’) it is possible to add a
new class;
By doing classList.remove(‘className’) it is possible to
remove a class;
By doing classList.contains(‘className’) it is possible to
know if a class exists;
The method appendChild() allows to displace HTML elements.
28 7.2. Event handling
29

• How to react to HTML DOM


events
• How to add and delete HTML
elements

You might also like