flowchart LR A(var1) --> C(25) B(var2) --> D(25)
JS defines several primitive types:
typeof is a type operator:
JS does not distinguish between integers and others. In R for instance, numeric contains integers and double.
List of arithmetic operators in JS:
+-*/% (modulo).++ (incrementation).-- (decrementation).+ adds two numbers, while it concatenates two strings:
typeof plop?typeof '1'?In JS, a variable is defined by:
Most of the time, camelCase is the preferred choice.
A valid variable name:
typeof!const:
Define a variable and edit it later:
What is the difference with let?
var i = 1;
{
var i = 2; // this will modify i globally, not locally
}
console.log(`i is ${i}`); // i is 2.With let:
Arithmetic operators still apply.
Assignement operators:
=+=: a += b is equivalent to a = a + b.Comparison operators:
===: check value AND type.==: check value. Don’t do this.!==: not equal value and type.>, >=, <, <=.AND or &&.OR or ||.Prefer === over == since 5 == '5' is true.
if and else:
Ternary operator:
If loads of conditions, switch:
JS is an object-oriented programming language. An object is defined by:
this refers to the object itself.
Why can we change me while it is declared with const? We can’t reassign me but we can alter its content. The memory location remains the same.
Read object properties with .:
We can define new properties/methods or modify them:
me.geek = true;
me.age = 33; // time flies.
Object.defineProperty(me, 'printAge', {
value: function() {
console.log(`I am ${this.name}`);
},
writable: false
})Human readable format:
An array is a structure to store information with different type. They’re similar to list in R:
Array may be nested:
const nested = [1, ['a', [1, 2, 3]], 'plop'];
console.log(nested);
console.log(nested[0]);
// To get deeply nested element
// we may chain index
nested[1][1] // Access [1, 2, 3]Be careful! In JS, indexing starts from 0, not 1 like in R.
JS provides methods specific to arrays, below a sample:
| method | description |
|---|---|
| length | Returns the number of elements |
| push | Add element at the end. |
Content is duplicated for simple type (boolean, string, number):
flowchart LR A(var1) --> C(25) B(var2) --> D(25)
What will happen to var1 if we do var2 = 3?
For more complex types:
What will happen to fruits if we do superFruits[0] = 'peach'?
flowchart LR fruits --> container(banana) superFruits --> container(banana)
How to prevent this? Use spread operator:
ES6 version:
// ES6 syntax
const nested = [1, ['a', [1, 2, 3]], 'plop'];
for (let el of nested) {
console.log(el);
}Classic version (more verbose and error prone):
With an array, we can use forEach:
Q: how many times i will be printed?
for key in object:
Otherwise, we can leverage Object.entries:
Similar methods exist like Object.keys or Object.values.
Wrap a succession of instructions to accomplish a given task.
const a = 1;
const fun = (parm1, parm2) => {
console.log(a);
let p = 3;
// The Math object contains the max method
return Math.max(parm1, parm2);
}
let res = fun(1, 2);
console.log(res); // prints a and 2
console.log(p);The old way:
One can play with JSFiddle.
A button in the DOM:
Get the element:
Other selector methods exist like getElementByClassName, querySelector, querySelectorAll, …
You may add a new CSS rule to test:
Add a new class:
btn.classList = 'class1 class2';
btn.classList.add('class3'); // keep othe classes.
btn.classList.remove('class2');
console.log(btn.classList);Change text:
Consider this <button id="mybutton">Go!</button> button. Within JSFiddle, add some JS code to change the button content to My super button.
Combine createElement and append:
Add an event listener:
Consider this <button id="mybutton">Go!</button> button. Add it an event listener that would change the button text to You clicked me! once clicked.
jQuery is a famous JS library providing a user-friendly interface to manipulate the DOM.
Wrap your code in (ensure the DOM is ready):
jQuery is less verbose than JS:
Consider the following button
Write a script that shows how much time we clicked on the button. Fill in the blanks:
How to reuse a function in different scripts?
Old way:
// utils scripts
const findMax = (parm1, parm2) => {
return Math.max(parm1, parm2);
}
module.exports = {
findMax : findMax
}Then, within the main.js script:
ES6 way:
As ES6 is not fully supported by all web browsers, we use a transpiler like Babel to convert it to standard JS.
JS bundlers for modules: webpack, esbuild, …
Pre-requisite: have node installed (for npm).
npm install --save-exact --save-dev esbuild.utils.js and add it:main.js and add it:package.json to add a build instruction:{
"scripts": {
"build": "esbuild main.js --bundle --minify --sourcemap=external --outfile=out.min.js"
},
"devDependencies": {
"esbuild": "0.19.6"
}
}npm run build and node out.js to test the new script. Notice that you can replace build by any predefined instruction.