JS 1: variables, functions, parameters, array methods, data types, Math operations and HTML implementation

Var, const, and functions.

Javascript is an Object-Oriented language based on Prototypes (not on classes )

var, const, and let are keywords used to store data:

let was introduced in 2015 and declares a block-scoped, local variable.

//The assign operator = stores the value, we repeat the assign to edit it
let uno = 'coming'
uno = 'The javascript is ' + uno

console.log(uno)        //"The javascript is coming"

//multiple assigns
let primo= 1, secondo= 2, terzo= 3;

//ALSO, we can only use _ or - on let names

We can create multi-line strings using ' ' and /n.

let poetry = `
Nel mezzo del cammin di nostra vita \n
mi ritrovai per una selva oscura, \n `

console.log( poetry )        //Nel mezzo del cammin di nostra vita
                             //mi ritrovai per una selva oscura,
Code Blocks and function/block scope in variables

JavaScript blocks are code sections enclosed in curly brackets {}, and functions are a type of block that can be invoked.

  • The let variable is block-scoped, it's only accessible within the block it's declared in.

  • The var variable is function-scoped, if declared in a block that's not a function, it becomes part of the global object, making it accessible anywhere.

//Variables accessible outside blocks
if (true) {
  var x = 10;
}
console.log(x); //10

if (true) {
  let y = 20;
}
console.log(y); //ReferenceError: y is not defined

Functions are blocks of code used to perform tasks when invoked:

you can use the function keyword and a reference name to create a function:

function sum(){
  return console.log(12 + 15)
}

//A function executes only when calling its reference with ()
sum()        //27

return will stop execution and return values, there are no implicit returns in javascript.

In Javascript, all functions are object methods, be it from constructor or global object.

Parameters are values that are passed to the function and can be used locally in the function:

//we can use multiple values for the function operations
function lot(num1, num2){
  var oltre = num1+num2;
  return console.log(oltre);
}

lot(5, 8);  //13
lot(1, 4);  //5
lot(4, 8);  //12

//parameters will be assigned based on their position, so num1=5 and num2=8
//parameters are LOCAL to the function, defined inside of it.

Arguments are the actual values passed when invoking the function:

//Invoking the lot(num1,num2) function 

lot(5, 8);    //assigning the num1, num2 Parameters the 5,8 Arguments

Functions too can be used as parameters, check Function composition to know more.

We Interpolate variables into HTML elements using Ternary Operators:

We use template strings (template iterals) to interpolate variables and expressions into a string, including Ternary Operators

//we can use `` or the +
let greetingStart = "Hallo "
let name = "dude"

const greeting = `${greetingStart}, my name is ${name}`;
let ecco = greetingStart + ", My name is " + name

console.log(greeting) / console.log(ecco)     //Hallo , My name is dude
//The backslash \ to escape special syntaxis
console.log(`${name} with the \{} and the \$`)  //"dude with the {} and the $"

//and for ternary logic we put the function between the ${}
const grade = 95;
`You have ${grade > 90 ? 'passed' : 'failed'} the exam.`;  //You have passed the exam
How to enable the backtick on the keyboard

Depending on your language your keyboard might not have the backtick (` `).

Download the developer's keyboard, and change the keyboard layout by pressing: windowsIcon + spacebar, use space to change the layout.

It will become avaiable using Alt Gr + '

The console is where we run scripts and commands.

Math Operations, Booleans, and Arrays methods.

Most Math operations work the same in Javascript +, -, *, and / following the Pendas priority system, we use == for comparisons (while = is to assign variables values).

//We can also define pow with:
3 ** 2 == 9 == true
Math.pow(3,2) == 9

//and we can get the modulus (the rest after division)
10 % 3 == 1 ( 3*3 +1 )

//we can also use shorthand on operations
3 += 5 (result 8)
20 %= 3 (will be 2)

We can also perform Math.___() operations, Math is a Global Built-In Object for Mathematics:

//round() will round up the number based on the decimal
//ceil() and floor() round up and down without checking the decimal
Math.round(12.3) == 12 
Math.floor(12.3) == 12 
Math.ceil(12.3) == 13 

//It can returns the P greek
function degToRad(degrees) {
  return degrees * (Math.PI / 180);
};

function radToDeg(rad) {
  return rad / (Math.PI / 180);
};

//we can type long numbers using _
//1000000 = 1_000_000

The NaN (not a number) operations are as such:

//we have the operator isNaN() in case, and NaN isn't === o !== to itself
NaN === NaN;        // false
Number.NaN === NaN; // false
isNaN(NaN);         // true
isNaN(Number.NaN);  // true
Number.isNaN(NaN);  // true

function valueIsNaN(v) { return v !== v; }
valueIsNaN(1);          // false
valueIsNaN(NaN);        // true
valueIsNaN(Number.NaN); // true

Arrays are objects variables that can hold more than one value and one typeof() data:

var list = [1, 2, 3]

//elements can be edited by their index(starting from 0)
list[1] = "new" //[1, "new", 3]
list.length == 2 

//strings are considered arrays of letters and so
"welcomed"[3] == "c" / "welcomed".length == 8

We can check its built-in methods and properties in its [[prototype]] property, like concat() or .length:

Methods on the other hand are actions on objects, and they need () because they are function:

Array push(), pop(), shift(), unshift(),fill() and splice() methods guide

We can use methods on strings, and we can chain them:

//trim() removes start and end empty spaces
"  its m i n us ".toUpperCase().trim()    //"ITS M I N US"

For arrays, we can use push(), pop(), shift() and unshift():

let row = [12]
//push adds at the end of the array, and returns array.length
row.push(13) //row== [12,13] // console.log(row.push(13))== 2

//pop will cut and return ONLY the last element
row.pop() // row == [12] // console.log(row.pop())== 13

//shift will cut and return the first element of the array
row.shift() // row== [13] // console.log(row.shift())== 12

//unshift() will ADD at the start of the array 
row.unshift(10, 11) //row== [10,11,12,13] //console.(row.unshift(10, 11))== 4

Similar to splice() the fill() method uses array indexes to overwrite the array.

[1, 2, 3, 4].fill(0, 2, 4)  //[1, 2, 0, 0]
[1, 2, 3, 4].fill(5, 1) //[1, 5, 5, 5]
[1, 2, 3, 4].fill(6) //[6, 6, 6, 6]

We use .splice( [starting array index ], cut elements number, elements added ) to substitute multiple array elements, remember that the starting index is included in the splice.

let longi = [1,2,3,4,5]
longi.splice(3, 1, "indeed") // longi== [1,2,3,"indeed",5]
//console.log(longi.splice(3, 1, "indeed"))== [4] //the cut elements

longi.splice(1, 2, "we change", "two") // longi== [1,2,"we change","two",5]

//we can add elements if we cut 0 elements
longi.splice(2, 0, "new") // longi==[1,2,"new",3,4,5]

//we can cut elements if we don't add any
longi.splice(3, 2) // longi== [1,2,3]

//OR we can include elements starting from an index using only 1 argument
longi.splice(1) // longi= [1]
console.log(longi.splice(1)) == [2,3,4,5]

//we can use it for Capital letters
let oltre = "minimal"
oltre[0].toUpperCase() + oltre.splice(1) == Minimal

Other methods like .includes() and .startsWith() will return true/false:

//We can't use Regex expressions here (/guess/i)
longi.includes(1) == true
"siamo".startsWith("S") == False

We can use typeof to check data type.

typeof longi == arrays

Pop() and Shift() can both store values and return methods:

//we are gonna change its 6,7 with 1,10, while also removing them
let deck= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

deck.splice(deck.length/2, 0, deck.pop(), deck.shift());
deck == [2, 3, 4, 5, 6, 10, 1, 7, 8, 9] 

//we don't cut any elemennt with splice(),we use return .pop() and shift()

On arrays, we can .sort() and .reverse() the array elements order, and also use .from() to make strings into arrays:

//for strings the order is alphabetical
let ginn = ["ar","ac", "kr", "qu", "ab", "ri"]
ginn.sort()            //['ab', 'ac', 'ar', 'kr', 'qu', 'ri']
ginn.reverse()         //['ri', 'qu', 'kr', 'ar', 'ac', 'ab']

//numbers use typo code, an extra function needed
let numeronia = [4,6,8,2,4,1]
numeronia.sort( (x,y)=> x - y)        //[ 1, 2, 4, 4, 6, 8 ]
numeronia.sort( (x,y)=> y - x)        //[ 8, 6, 4, 4, 2, 1 ]

//strings aren't arrays, so we use .from()
Array.from("welcomed")    //['w', 'e', 'l','c','o','m','e','d']
Array.from("welcomed".toUpperCase() ).map( (x)=> "this is the letter " + x )    
//['this the letter W',...]

Any function passed as an argument, inside a method, it's a callback function:

//for example the anonymous functions inside .map()

const numbers = [1, 2, 3];
const numbersDoubled = numbers.map(function (number) {
  return number * 2;
});

Booleans are a type of data and we obtain it after logical operators:

true && true == true  //logical AND returns true if BOTH
true || !true == true //logical OR, returns true if one of is true
2 !== 3    //is 2 NOT equal to 3? True
2 == "2"   // True, we check equality on value
2 === "2"  //False, it check strict equality on both value and typeof
"a" == "A" //False, equality checks caps
 
== being the equality operator
// && will be executed first
 
//and in functions
let studentCount = 12;
let mentorCount = 10;
var moreStudentsThanMentors = studentCount > mentorCount;
console.log("The awnser is", moreStudentsThanMentors);     //The awnser is true
 
//we can set boolean values without =="True"
if (htmlLevel > 5){
  cssAndHtmlAbove5 = true;
}

Booleans, Strings, and Numbers are the most known primitives, contrary to objects, which are aggregations of properties, primitives are just values, they have no property:

//new String is a constructor, that's why its result is an object

typeof "abc";                 //"string"
typeof String("abc");         //"string"
typeof new String("abc");     //"object"

Data conversion and type helpers

We can use the built-in helpers Boolean(), String() Number() to check/convert to respective data types:

//Boolean will differentiate between truly/falsy values

Boolean("0")        //True, a 1-digit string is truly
Boolean(0)          //False, True for any other integer
Boolean("")         //False for any empty array
Boolean(" ")        //True, space digit is not empty arrays

//Number() will return an integer from a string when possible

Number("123.34")    //123.34, for Numbers in string use . for decimals
Number("")          //0, for empty arrays
Number(" 12.3  ")   //12.3 only the starters and ending spaces will be ignored
Number(null)        //0, is from null
Number(undefined)   //NaN

//String() will return the string result of its content 

String(1==1)        //"true" string will be returned
String(1!==1)       //"false" string will be returned
String(null)        //"null" string returned
String(undefined)   //"undefined" string returned

//String() on arrays will return a string of elements .join() by ,

String(["siamo", null, undefined, "audd"])    
//siamo,,,audd , the null and undefine will be empty
String({name: "uno"})                         
//[object, Object] will be returned

We can also have data coercion where values are converter automatically :

//For example during the if statement

function errorMessage(input) {
  if (!input) {                //will automatically work as !Boolean(input)
    return 'Required field'
  }
}

Js in HTML implementation

To link our external .js file to the HTML page we use:

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

//we can trigger functions on events
<a href="#" onClick="alert('text!');">Alert button</a> 

//or reference the function in the .js file
<input type="button" value="uno" onclick="add()"/> 

function add(){
  alert("welcomed")
}

We use createElement(), createTextNode() and appendChild() to potray JS content into HTML :

//we want to add additional <li> content on button click
<ul id="myList">
  <li>Coffee</li>
  <li>Tea</li>
</ul>

<button onclick="myFunction()">Append</button>

function myFunction() {
  oll = "terzo"
  const node = document.createElement("li");
  const textnode = document.createTextNode(oll);
  node.appendChild(textnode);
  document.getElementById("myList").appendChild(node);
}

//We create <li> HTML tag
//We insert the js variable as text with createTextNode(oll)
//We append the text to the <li> created element
//We use an id html element to append everything into

How to use variables and arrays in the DOM:

<button onclick="myFunction()">Append</button>

var popp = "new element n."
var counter = 0

function myFunction() {
  counter++
  const node = document.createElement("li");
  const textnode = document.createTextNode(popp + counter);
  node.appendChild(textnode);
  document.getElementById("myList").appendChild(node);
}

JS in DOM with arrays and event

Check this exercise:

JS on DOM

We use Math.floor() to get random 2-integers numbers:

//by multiplying the random (0 to 0.9) by 100 we get 2-digits numbers
var oul = Math.floor( Math.random()*100 ) ;

We use an external array to store the random numbers, while also resetting the innerHTML:

//we use .length as an index to always update the array with the latest element
var filone = []

function rando() {
  filone[filone.length] = oul;
    
  var textnode = document.createTextNode(oul);
  document.getElementById("primo").appendChild(textnode);
}

var propt = document.getElementById("primo")
propt.innerHTML = ""

We also wanted the numbers and the sum to happen separately:

//we sum the last random generated numbers, in case none we get NaN
function summin(){
  var erm = filone[filone.length-1] + filona[filona.length-1];

  const terzo = document.createTextNode(erm);
  document.getElementById("terzi").appendChild(terzo);
}

To show the arrays with the stored values we:

var riga = document.createTextNode("[ " + filone + " ]");
document.getElementById("colla1").appendChild(riga);

Last updated

Was this helpful?