Web Technologies

JavaScript

Claudia Chiriță . 2026/2027

JavaScript

  • developed by Brendan Eich in 1995, at Netscape, under the names Mocha and LiveScript
  • made a standard in 1997 by ECMA association (European Computer Manufacturer's Association) under the name of ECMAScript
  • current version: ECMAScript 2027

JavaScript - WHAT?

  • lightweight scripting language for web pages
  • combines several programming paradigms: imperative, functional, object-oriented, prototype-based, and event-based programming

JavaScript - WHAT?

  • interpreted language (the script is run directly, without in advance compilation)
  • the code runs in browser (client side)
  • single-thread, dynamic

JavaScript - RTM

JavaScript The Definitive Guide, David Flanagan

Understanding ECMAScript 6, Nicholas C. Zakas

JavaScript + HTML

  • a web page is represented in the memory as a tree of elements (objects)
    Document Object Model – DOM
  • JavaScript can interact with the HTML document via the DOM

JavaScript + HTML

  • HTML element --- > JavaScript object

    ...

    ob = document.getElementById("identif")
  • attribute of an HTML element --- > property of the JavaScript object

    ...

    ob.id, ob.className ob.src

JavaScript + HTML

  • style attribute: CSS properties ---> style property -> style object –> CSS styling properties
    <h1 style="color:pink; text-align:center;">...</h1>
    ob.style.color, ob.style.textAlign

JavaScript @ HTML

JavaScript code can be placed inline, in the head, using the tag <script>
<head>
<script type="text/javascript">
/* JavaScript code */
</script>
</head>

JavaScript @ HTML

JavaScript code can be placed in an external file, imported to the HTML document [recommended]

additional attributes, only for external scripts:
  • defer - delays the execution of the code until the complete load of the HTML document
  • async allows loading the code asynchronously to the document

JavaScript - HOW?

JS is case sensitive and uses the Unicode char set

  • identifiers
    • denote variables, keywords, functions, labels
    • consist of: digits, letters, _, $;
    • first character: letter, _, $
  • ;   separator
  • { }   block of instructions
  • /* multiline 
    comment
    */
    // single line comment

JavaScript - WHERE?

JavaScript debugger in browser

https://jsfiddle.net/

https://codepen.io/

Dialog: ALERT & PROMPT

a browser tab is represented by a window object (interface Window)

alert(message); // displays an alert box which
                // contains a message and an OK button
prompt(text, default-text); // displays a dialog box 
                            // that requires the user 
                            // to introduce information

Dialog: ALERT & PROMPT

Dialog: ALERT & PROMPT

Core JavaScript

DATA TYPES

Core JavaScript

INSTRUCTIONS

Core JavaScript

FUNCTIONS

function name(param1, param2, ...)
	{ 
	  function body
	}

TYPE CONVERSION

  • JavaScript is dynamically typed
  • specifying data types is not necessary, like in other programming languages
  • data types are converted automatically, when needed, during code execution
x = 23; //number
y = "abc"; //string
z = true; //boolean
var a; //undefined
cat = {name:"Tigger", color:black}; //object

VARIABLES - Declaration

  • declared variables
    • inside functions are local to those functions
    • outside any function are called global variables
    • in a domain (scope) are accessible in the child functions
  • variables must always be declared before usage; JavaScript allows assigning values to an undeclared variable, creating a global undeclared variable - ERROR in strict mode

VARIABLES - Initialization

  • we can assign an initial value at declaration
  • if a variable is declared without initialization, it gets assigned the value undefined

VARIABLES - Declaration - VAR

  • declared explicitly using the keyword var
    var x = 42; 
  • we can declare variables either globally, or locally, in a function

VARIABLES - Declaration - VAR

VARIABLES - Declaration - LET

  • declared explicitly using the keyword let
    let x = 42; 
  • declares a local variable visible only in the block, instruction or expression in which it is used

VARIABLES - Declaration - LET

VARIABLES - Declaration - LET

VARIABLES - Declaration - CONST

  • we can declare block-scoped constants using the keyword const
    const x = 42; 
  • initialized at declaration
  • cannot be modified during the execution of the program through re-assignment; cannot be redeclared

VARIABLES - TYPEOF

  • variables have dynamic types: can be declared
    (and receive values) with any data type
  • the type of variables is not explicitly specified,
    but can be checked with
    typeof(x); 
  • the type of an undeclared variable is undefined

VARIABLES - TYPEOF

SCOPE - Visibility domain

  • the (scope) of variables:
    part of the program where variables are declared
  • global scope, function scope (local), block scope
  • variables declared by a parent function are visible in its descendents
// global scope 
function fA (){
   //scope A
   function fB () {
      // scope B 
   }
}

SCOPE - Visibility domain

SCOPE - Hoisting

  • we can refer to variables declared with var anywhere in their scope, even before their declaration
  • before execution, JavaScript code is "rearranged" s.t. all variable declarations (but not assignments) are moved (hoisted) at the beginning of the scope

SCOPE - Hoisting

var x = 5; //global
function hoist() { if (x == 5) { var x = 10; }
                  alert(x); }
hoist(); // will print undefined
alert(x); // will print 5
~
var x = 5; //global
function hoist() { var x; // local variable
                  if (x == 5) { // undefined 
                    var x = 10; }
                  alert(x); }
hoist(); // will print undefined
alert(x); // will print 5

Number Type

  • binary representation on 64 bits; integers and float
    var i = 4;
    var r = 42.2;
  • specific arithmetic operators : + - * / % ++ --
  • automated type conversion:
    x = "2" * 7; // 14
    y = "2" + 7; // "27"
    z = parseInt("2") + 7; // 9
    t = "2" * "7"; // 14
    u = 2 + 3 + "4"; // "54"
    z = "2" + 3 + 4; // "234"
    

Number Type

built-in object Math

Math.PI //=> 3.14
Math.pow(2,3) // => 8
Math.round(4.7) // => 5
Math.random() // between 0 and 1
Math.sqrt(-1) // => NaN

Boolean type

any value can be converted explicitly using the predefined object Boolean

var name = Boolean(value);
true === Boolean("truuue") // => true
false === Boolean("") // => true
  • logical operators for primitive types:
    > < <= >= && || ! == === != !==
  • we can use other data types in a logical context:
    • for false: 0, "" , NaN, null, undefined
    • for true: any other value

String Type

string of characters written between ' ' or " "

var s = "Tigger Lilly";
var t = 'Tigger Lilly';
var fname = s.slice (0, s.indexOf(" ")); // 'Tigger'
var lname = s.slice(s.lastIndexOf(" ")+1,s.length); // 'Lilly'
properties and methods:
length, charAt(), indexOf(), lastIndexOf(), replace(), 
split(), toLowerCase(), concat()

String Type

  • concatenation: "number" + "1", "number" + 1
  • special characters: \’ \” \n \t \v \b \\
  • accessing a character: s[position], s.charAt(position)
    var x = "abcde";
    alert(x[0]);
    x[0] = 'v';
    alert(x[0]); // => a

undefined & null types

  • variables who haven't yet received a value have the undefined type
    var x
    x == undefined // true
    typeof(x) // undefined
    
  • null: absence of a value (intentional)
    var x = null
    typeof(x) // object !
    null == undefined // true
    null === undefined // false
     

object type

  • an object is a collection of pairs property-value
  • if the value is a function, then the property is called method
  • var ob = {prop1: val1, prop2: val2, ... , propn: valn};
  • accessing properties:
    ob.prop1; // val1
    ob["prop1"]; // val1
    

object type

var student = { name: "Tigger",
                mark1: 9,
                mark2: 10,
                grade: function(){
                          return (this.mark1 + this.mark2)/2;
                       }
                }
student.name    \\ "Tigger"
student.mark1   \\ 9
student.mark2   \\ 10
student.grade() \\ 9.5
student.grade   \\ function
    

object type

  • all data of primitive type are passed by value
  • data of object type are passed by reference
var a = {name: "Tigger"} // object
var b = a; // a and b refer the same memory area
b.name = b.name + " Lilly"; // both b and a are modified
alert(a.name); // "Tigger Lilly"
var s = "Tigger"; // string
var t = s; // t copies the value of s
t = t + " Lilly" ; // only t is modified
alert(s) // => "Tigger"
    

Creating objects

  • through object literal
  • properties, methods, together with their values are enumerated between curly brackets
  • a single object is created
var cat = {name:"Tigger", color:"black", age:14}

Creating objects

  • through the global object
  • the new Object() constructor is called and then the properties and methods are added
  • a single object is created
var cat = new Object(); 
cat.name = "Tigger";
cat.color = "neagră";
cat.age = 14;

Creating objects

  • through an object constructor
  • we define a function constructor(param) which will then be called with new constructor(param) for every object to be created
function cat(n, c, v) { 
  this.name = n;
  this.color = c;
  this.age = v;
}

var c1 = new cat("Tigger", "black", 14);
var c2 = new cat("Fluff", "white", 2);

Built-in objects

global properties: return a simple value

Built-in objects

global methods: called globally, not for an object

  • isNaN() - determines if the value is an invalid number
  • parseInt() - convertes a string to an integer
  • parseFloat() - convertes a string to a float
  • Number() - convertes an object to a number
  • String() - convertes an object to a string

Predefined objects

Predefined objects

Predefined objects - Array

var v = new Array();
v[0] = "a"; v[1]= "b";

var v = new Array("a","b");

var v = ["hi", 2, [5,7]];
v = [6,4,7,3];
v.length; // 4
v.push(10); // => v = [6,4,7,3,10]
v.pop(); // => v = [6,4,7,3]
v.shift(); // => v = [4,7,3]
v.unshift(10); // => v = [10,4,7,3]
v.sort(); // => v = [3,4,6,7]

Predefined objects - Array

var s = "today is Monday";
var a = s.split(" "); // a = ["today","is","Monday"]
a.reverse(); // a = ["Monday","is","today"]
var s = a.join(‘/’); // s = "Monday/is/today"

Functions

function name(arg1, arg2, ..., argn) {
  instructions;
  [ return value; ] // optional
}

a JavaScript function can be called with a variable number of parameters

function sum(a,b) {
  return a+b;
}
sum(2,3); // 5
sum(); // NaN
sum(2); // NaN
sum(3,4,1,5,6,7) // 7

Functions - arguments

any function can access the object "arguments" (similar to an array) that contains the values of the arguments with which the function was called

function fun() {
return arguments.length;
}

fun(2,"sss", 5); // 3

Functions - arguments

function func(a, b, c) {
  console.log(arguments[0]); // expected output: 1
  console.log(arguments[1]); // expected output: 2
  console.log(arguments[2]); // expected output: 3
}

func(1, 2, 3);

Functions - arguments

Anonymous Functions

function expressions

function (arg1, ..., argn) {
    instructions;
}
const fun = function () {
    return arguments.length;
}

arrow functions

var f = (x) => x+1;

Array - map()

array.map(function(currentValue, index, arr), thisValue)
  • creates a new array by calling a function (given as parameter) for each element of the array
  • does not change the initial array
  • index, arr, thisValue are optional

Array - map()

function f(x) {
   return x+1;
}
var array = [1,2,3,4];
var array1 = array.map(f);
console.log(array1); // [2,3,4,5]
function g(x) {
   return x * this.a;
}
var o1 = {a:2}, o2 = {a:3};
var array = [1,2,3,4];
var array1 = array.map(g,o1); // [2,4,6,8]
var array2 = array.map(g,o2); // [3,6,9,12]

Array - forEach()

array.forEach(function(currentValue, index, arr), thisValue)
  • calls a function given as parameter for each element of an array
  • index, arr, thisValue are optional

Array - forEach()

array.forEach(function(currentValue, index, arr), thisValue)
function f(x, i) {
  alert(i + " : " + x);
}

var array = ['monday', 'tuesday', 'wednesday', 'thursday'];
array.forEach(f);

var d = [1, 2, 3, 4];
d.forEach(function(v, i, a) {a[i] = v + 1;});
console.log(d); //[2,3,4,5];

Array - filter()

array.filter(function(currentValue, index, arr), thisValue)
  • creates a new array with the elements that satisfy the condition implemented by the function given as a parameter
  • does not change the initial array
  • index, arr, thisValue are optional

Array - filter()

function check(word) {
   return word.length < 6;
}

var animals = ["cat", "tapir", "platypus", "red panda"];
var smol = animals.filter(check);
console.log(smol); // ["cat", "tapir"]

Array - reduce()

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • executes a reduction function (given as parameter) for each element of the array, producing a single output value
  • does not change the initial array
  • currentIndex, arr, initialValue are optional

Array - reduce()

function sum(total,val) {
   return total+val;
}

var array = [1,2,3,4];
var s = array.reduce(sum);
console.log(s); // 10;
     

Array

var cats = [{name:"Tigger",age:7},{name:"Whiskers",age:6},
            {name:"Fluff",age:3},{name:"Kit",age:2},
            {name:"Tom",age:6},{name:"Berlioz",age:4}];
var copy = cats.slice();
var oldCats = copy.filter((x) => (x.age >= 6))
.map((x) => (x.name+" is "+x.age+" years old"))
.forEach((x) => {alert(x)});

Classes?

              .     .
             (>\---/<)
             ,'     `.
            /  q   p  \
           (  >(_Y_)<  )
            >-' `-' `-<-.
           /  _.== ,=.,- \       questions?
          /,    )`  '(    )
         ; `._.'      `--<
        :     \        |  )
        \      )       ;_/ 
         `._ _/_  ___.'-\\\
            `--\\\