🚢

Javascript

CatégorieCours

Cours de Julie Chaumard

To Do
ChaptersHomeworksExercisesWeeksDates
Javascript316/06/2025
17/06/2025
💚

Book - Chapter 8 - P.322

  • Connolly, R. and Hoar, R. (2018). Fundamentals of Web Development (2nd ed.). Pearson.

What is JavaScript and What Can It Do?

JavaScript was introduced by Netscape in their Navigator browser back in 1996.

Larry Ullman, in his Modern Java Script: Develop and Design (Peachpit Press, 2012), has an especially succinct definition of JavaScript: it is an object-oriented, dynamically typed scripting language. We can add as well that it is primarily a client-side scripting language.

JavaScript is object oriented in that almost everything in the language is an object. For instance, variables are objects in that they have properties and methods. Unlike more familiar object-oriented languages such as Java, C#, and C++, functions in JavaScript are also objects.

JavaScript is dynamically typed (also called weakly typed) in that variables can be easily (or implicitly) converted from one data type to another. In a programming language such as Java, variables are statically typed, in that the data type of a variable is declared by the programmer and enforced by the compiler. With JavaScript, the type of data can hold is assigned at run-time and can change during run-time as well.

Typescript

TypeScript is a programming language developed by Microsoft in 2012 by the same engineer that created Turbo Pascal et C# (he was about 55 in 2012). TypeScript adds features that JavaScript does not natively support.

TypeScript = JavaScript + Static Typing + Tools to better structure your code

TypeScript helps developers:

How Does It Work?

  1. You write code in .ts files (TypeScript files)
  1. This code is compiled (or “transpiled”) into standard JavaScript with “Typescript” executed in the Node.js platform
  1. The generated JavaScript is what actually runs in the browser or in Node.js

Example of a Difference

In JavaScript

function addition(a, b) {
return a + b;
}

→ If you run addition("3", 4), it returns "34" with no error!

In TypeScript

function addition(a: number, b: number): number {
return a + b;
}

→ If you run addition("3", 4), you get a compilation error: "3" is not a number.

Web 2.0 and AJAX

Asynchronous JavaScript with XML (AJAX) is a term used to describe a paradigm that allows a web browser to send messages back to the server without interrupting the flow of what's being shown in the browser. This makes use of a browser's multithreaded design and lets one thread handle the browser and interactions while other threads wait for responses to asynchronous requests.

Figure 10.12 annotates a UML sequence diagram where the white activity bars illustrate where computation is taking place. Between the request being sent and the response being received, the system can continue to process other requests from the client, so it does not appear to be waiting in a loading state.

Where JS is used ?

Thanks in part to Google, Mozilla, and Microsoft releasing V8, SpiderMonkey, and Chakra (their respective JavaScript engines) as open-source projects which can be embedded into any C++ application, JavaScript has migrated into other non-browser applications. It can be used as the language within server-side runtime environment such as Node.js. Some newer non-relational database systems such as MongoDB use JavaScript as their query language. Complex desktop applications such as Adobe Creative Suite or OpenOffice.org use JavaScript as their end-user scripting language. A wide variety of hardware devices such as the Oculus Rift headset and the Arduino and Raspberry Pi microcontrollers make use of an embedded JavaScript engine. Indeed, JavaScript appears poised to be the main language for the emerging Internet of Things.

Part of the reason for JavaScript's emergence as one of, or perhaps even, the most important programming language in software development, is the vast programming ecosystem that has developed around JavaScript in the past decade. This ecosystem of JavaScript libraries has made many previously tricky and tiresome JavaScript tasks much easier.

These libraries of JavaScript functions and objects are generally referred to as JavaScript frameworks. Some of these frameworks extend the JavaScript language; others provide functions and objects to simplify the creation of complex user interfaces. jQuery, in particular, has an extremely large user base, used on over half of the top 100,000 websites. There are thousands of jQuery plug-ins, which allow a developer to easily add functionality such as image carousels, floating tool tips, modal dialogs, sortable tables, interactive charts, and many other functions.

The past several years have witnessed a veritable deluge of new JavaScript frameworks. JavaScript user interface frameworks such as React and jQuery UI have become quite popular among developers. MVC Frameworks such as AngularJS, Backbone, and Ember have gained a lot of interest from developers wanting to move more data processing and handling from server-side scripts to HTML pages using software engineering best practices.

Where Does JavaScript Go?

JavaScript can be linked to an HTML page in a number of ways. Just as CSS styles can be inline, embedded, or external, JavaScript can be included in a number of ways. Just as with CSS these can be combined, but external is the preferred method for simplifying the markup page and ease of maintenance.

Running JavaScript scripts in your browser requires downloading the JavaScript code to the browser and then running it. Pages with lots of scripts could potentially run slowly, resulting in a degraded experience while users wait for the page to load. Different browsers manage the downloading and loading of scripts in different ways, which are important things to realize when you decide how to link your scripts.

Inline

<a href="JavaScript:OpenWindow();">more info</a> 
<input type=“button” onClick="alert(‘Are you sure?’);" />

Embedded

<script type=“text/javascript”> 
   /* A JavaScript Comment */ 
   alert(“Hello World!”); 
</script>

External

<body> 
   <script type=“text/javascript” src=“greeting.js”></script> 
</body>

Some high traffic sites prefer using embedded styles and JavaScript scripts to reduce the number of GET requests they must respond to from each client. Sites like the main page for Google search, embed styles and JavaScript in the HTML to speed up performance by reducing the need for extra HTTP requests. In these cases performance improves because the size of the embedded styles and JavaScript are quite modest.

For most sites and pages, external JavaScript (and CSS) will in fact provide the best performance because for frequently visited sites, the external files will more than likely be cached locally by the user's browser if those external files are referenced by multiple pages in the site.

Thus, if users for a site tend to view multiple pages on that site with each visit, and many of the site's pages reuse the same scripts and style sheets, then the site will likely benefit from cached external files.

JS Syntax

Variables and Data Types

💡

Variables are containers for storing values.

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Variable names

RuleExample
Can start with $, _, or a Unicode letter$var, _index, π, 名前
Cannot start with a number2name
Can contain letters, numbers, and certain symbolsdata2025, _temp$, résumé
Names are case sensitivey and Y are different variables

Types

Data TypeDescription
BooleanTrue or false value
NumberRepresents some type of number. Its internal format is a double precision 64-bit floating point value.
StringRepresents a sequence of characters delimited by either the single or double quote characters.
NullHas only one value: null.
UndefinedHas only one value: undefined. This value is assigned to variables that are not initialized. Notice that undefined is different from null.
SymbolNew to ES2015, a symbol represents a unique value that can be used as a key value.

Declaration

The var keyword was used in all JavaScript code from 1995 to 2015 and should only be used in code written for older browsers.

The let and const keywords were added to JavaScript in 2015.

When to Use var, let, or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.

Assign

The Assignment Operator

In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.

let var1;
const var2;
const pi = 3.14;

let x = 5;
let y = 6;

let z = x + y;

console.log("the result of z is : ",z);
alert("the result of z is : " + z);
console.log(`Hello again ${x} for me`);

x = x + 5


let person = "John Doe";
let answer = 'Yes I am!';

The "equal to" operator is written like == or === in JavaScript.

Add the JS in the HTML

💡

Open the project exercie

Add this html elements

<article>
    <h1>JavaScript Variables</h1>
    <p>Create a variable, assign a value to it, and display it:</p>
    <p id="demo"></p>
</article>

Create a JS file and put it into the asset/js folder

Add the link to the JS file just before the en of the body tag to ensure html is loaded before the JS.

<script src="assets/js/exercise_1.js"></script>
  </body>

Your first JS

Alert and console

Execute the Javascript code after the load of the html page. Because as Javascript act on HTML elements, you need them before.

ElementMeaning
documentRepresents the entire HTML page
addEventListener("DOMContentLoaded", …)Adds an event listener to wait until the DOM is ready
"DOMContentLoaded"The event triggered when all HTML is loaded, but before images/videos
function () { … }The function to be executed once the DOM is ready
document.addEventListener("DOMContentLoaded", function () {
    start()
});

function start() {
    alert("hello guys");
    console.log("Hello again");
}

In your Javascript file add a variable and display it on the page

ElementMeaning
documentRepresents the entire HTML page
getElementById("demo")Selects the element with the ID "demo"
innerHTMLRefers to the content (HTML) inside the selected element
document.addEventListener("DOMContentLoaded", function () {
    start()
});
function start() {
    alert("hello guys");
    console.log("Hello again");

    let carName = "Volvo";
    document.getElementById("demo").innerHTML = carName;
}
🎲

Exercice 1
Use the variables we have seen to display it on the web page, on the console and on an alert
let x = 5;
let y = 6;
x = x + 5;
let z = x + y;
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions.

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

In JavaScript we have the following conditional statements:

if (condition) {
  //  block of code to be executed if the condition is true
}

if (condition 1) {
  //  block of code to be executed if the condition is true
} else if (condition 2){
	//  block of code to be executed if the condition is true
} else {
	//  block of code to be executed if the condition is false
}

Say Hello

ElementMeaning
new Date()Creates a new Date object representing the current date/time
.getHours()Returns the current hour (0–23) from the Date object
if (new Date().getHours() < 18) {
    document.getElementById("sayhello").innerHTML = "Good day!";
} else {
    document.getElementById("sayhello").innerHTML = "Good evening!";
}
🎲

Exercise 2
Add the Say hello Function in a new p element and after the page is loaded

Execute when clicking on a button

HTML

<p id="sayHello"></p>
<button onclick="sayHello()">Click me</button>

JS

function sayHello() {
    console.log("current time is :", new Date().getHours())
    if (new Date().getHours() < 18) {
        document.getElementById("sayHello").innerHTML = "Good day!";
    } else {
        document.getElementById("sayHello").innerHTML = "Good evening!";
    }
}

For loop

Experimenting with variable scope (local scope)

let i = 10;

for (let i = 0; i < 5; i++) {
  console.log("In loop:", i);
}

console.log("Outside loop:", i); // display 10 because the i is declare in the loop too with let

Do a loop with a array

A common recommendation for improving the efficiency of your JavaScript loops is to avoid doing an object lookup or calculation on each iteration. That means to put it in a variable before : let cars_nb = cars.length;

const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
let text = "";
let cars_nb = cars.length;
for (let i = 0; i < cars_nb; i++) {
	text += cars[i] + "<br>";
}
document.getElementById("cars").innerHTML = text;
🎲

Create a button to call the function “list the car models”

Create a function with the cars array.

  1. When you click on the button it display the content of the car array in the console.
  1. Add a new car model in the array (cars.push("Renault");) and check in the console the content of the array with the new model
  1. Do a loop to display the content of the array in the console car by car or element by element of the array

The break statement "jumps out" of a loop.

let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;

The continue statement breaks one iteration (in the loop)

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;

Arrays

Array examples

const years =  [1855, 1648, 1420];

//Read the second value
years[1]




// remember that JavaScript statements can be 
// spread across multiple lines for readability 
const countries = [“Canada”, “France”, 
                 “Germany”, “Nigeria”, 
                 “Thailand”, “United States”];
 countries[O]              
                 
// arrays can also be multi-dimensional … notice the commas! 
const month = [ 
        [“Mon”,“Tue”,“Wed”,“Thu”,“Fri”],
        [“Mon”,“Tue”,“Wed”,“Thu”,“Fri”], 
        [“Mon”,“Tue”,“Wed”,“Thu”,“Fri”], 
        [“Mon”,“Tue”,“Wed”,“Thu”,“Fri”] 
    ];
  month[O][1]
  
    
// JavaScript arrays can contain different data types 
const mess =  [53, “Canada”, true, 1420];

Read the content

// outputs 1855 and then 1420 
console.log(years[0]); 
console.log(years[2]); 
// outputs Canada and then United States 
console.log(countries[0]); 
console.log(countries[5]); 
// outputs Thu 
console.log(month[0][3]); 
// arrays are built-in objects and have a length property defined 
// index will be set to 6 
var index = countries.length; 
// outputs United States again (remember array indexes start at 0) 
console.log(countries[index-1]); 
// iterating through an array 
for (var i = 0; i < years.length; i += 1) { 
     console.log(years[i]); 
}

Add an item to the end of an existing array

countries.push("Australia");

Object

In JavaScript, objects are a collection of named values (which are called properties in JavaScript). Almost everything within JavaScript is an object (or can be treated as an object). Unlike languages such as C++ or Java, objects in JavaScript are not created from classes.

const years =  [1855, 1648, 1420];
years.lenght

let name = "Shomer" {"s","h",...}
name.lenght

Declaration

const objName = {
    name1: value1, 
    name2: value2, 
    // …
    nameN: valueN 
};

OR

const obj2 = {};

Reference

To reference this object's properties, we can use either dot-notation or square bracket notation.

objName.name1 
objName["name1"]

countries[0][capitale]
countries[0].capitale

Objects nested

const order = { 
  salesDate : “May 5, 2016”, 
  product: {  
  type: “laptop”, 
  price: 500.00, 
  brand: “Acer”  
  }, 
  customer: { 
  name: “Sue Smith”, 
  address: “123 Somewhere St”, 
  city: “Calgary” 
  } 
};

alert(order.salesDate); 
alert(order.product.type); 
alert(order.customer.name);


countries[0].flag.png

JSON

Many web applications receive JSON from other sources, like other programs or websites, and parse the JSON into JS objects. This ability to interact with other web-based programs or sites is generally referred to as web services.

There is a variant of object literal notation called JavaScript Object Notation or JSON which is used as a language-independent data interchange format analogous in use to XML. The main difference between JSON and object literal notation is that property names are enclosed in quotes.

const text =  '{ "name1" : "value1",
              "name2" : "value2",
              "name3" : "value3"
           }';

Notice that this variable is set equal to a string literal which contains an object definition in JSON format (but is still just a string). To turn this string into an actual JavaScript object requires using the built-in JSON object.

// this turns the JSON string into an object
var anObj = JSON.parse(text); 
// displays “value1”
console.log(anObj.name1);

Functions

Functions are the building block for modular code in JavaScript. They are defined by using the reserved word function and then the function name and (optional) parameters. Since JavaScript is dynamically typed, functions do not require a return type, nor do the parameters require type specifications.

Function declaration

function subtotal(price,quantity) {  
   return price * quantity; 
} 

Such a declared function can be called or invoked by using the () operator.

var result = subtotal(10,2); 

The most important and unique features of JavaScript functions: that functions are objects. This means that functions can be stored in a variable or passed as a parameter to another function.

// defines a function using a function expression  
var sub = function subtotal(price,quantity) {  
  return price * quantity; 
}; 
// invokes the function  
var result = sub(10,2); 

(sub.lenght)

Function expressions

We will find that using function expressions is very common in JavaScript. In the example, the function name is more or less irrelevant since we invoked the function via the object variable name. As a consequence, it is conventional to leave out the function name in function expressions. Such functions are called anonymous functions and, as we will discover, they are a typical part of real-world JavaScript programming.

// defines a function using an anonymous function expression  
var calculateSubtotal = function (price,quantity) { 
 return price * quantity;  
}; 
// invokes the function 
var result = calculateSubtotal(10,2);

The object nature of functions can also be seen in one of the more easy-to-make mistakes with using functions.

What do you think the output will be in the last two lines of code?


The first alert will invoke the frenchHello function and thus display the returned “bonjour” string. But what about the second alert? It is missing the parentheses, so instead of invoking the function, JavaScript will simply display the content of the frenchHello object. That is, it will display: “function () { return “bonjour”; };”.

// defines a function expression

var frenchHello = function () { return “bonjour”; };

// outputs bonjour

alert(frenchHello());

// what does this output? Notice the missing parentheses

alert(frenchHello);

While the sample functions shown so far all return a value, your functions can simply perform actions and not return any value.

Defining a function without a return value


What would happen if you invoked this function as if it had a return value? For instance, in the following code, what would be the value of the variable temp after the function call?

// define a function with no return value

function outputLink(url, label) {
document.write('<a href=“' + url + '”>');
document.write(label);
document.write('</a>');

}

// invoke the function

outputLink('[http://www.mozilla.com](http://www.mozilla.com/)', 'Mozilla');
var temp = outputLink('http://www.mozilla.com', 'Mozilla');
alert(temp);


The answer? It would have the value
undefined. We could add a conditional test for undefined using the undefined keyword.

if (temp !== undefined) alert(temp);

Return vs. side effects

The function below contains no return, so it returns nothing (which means undefined by default), but it modifies the HTML page — that’s what we call a side effect.

function sayHello() {
    console.log("current time is :", new Date().getHours());

    if (new Date().getHours() < 18) {
        document.getElementById("sayHello").innerHTML = "Good day!";
    } else {
        document.getElementById("sayHello").innerHTML = "Good evening!";
    }
}

A side effect is when a function changes something outside of itself, such as:

That’s the side effect: the function doesn’t return anything, but it alters the page content.

Try … Catch

💚

Agence digitale Parisweb.art
Tout savoir sur Julie, notre directrice de projets digitaux :
https://www.linkedin.com/in/juliechaumard/