Comments
// for one line comment
/* ... */ for multiple lines comment
Variable and Constant Definition
Variable
let variable_name;
Constant
const variable_name = value;
User Input
With window.prompt
let variable = window.prompt(message);
With HTML textbox
Create an HTML textbox.
Type Conversion
String number to number
let A = '112';
let B = Number(A);
// B = 112
A = "";
B = Number(A);
// B = 0;
1
String to number
let a = "hello";
let b = Number(a);
// b = NaN
String to boolean
let A = "hello";
let b = Boolean(A);
// b = true
A = "";
b = Boolean(A);
// b = false
Functions
Define a function
function functionName(arguments) { ... }
const functionName = function(arguments) { ... } // function expression
const functionName = (arguments) => { ... } // arrow function
const functionName = (arguments) => line_of_code_returned; // arrow function
// to ignore passed argument we name it _
function functionName(_, argument2, ...) { ... }
1 Conditions
1.1 IF ELSE
if(condition)
{
actions
}
else
{
actions
}
2
1.2 Ternary operator
// condition ? action when true : action when false
age > 10 ? alert("yes") : alert("No");
let message = age > 10 ? "adult" : "child";
1.3 switch case
switch(variable)
{
case value:
actions
break
...
default:
actions
}
2 Strings
2.1 .length
get the length of string
2.2 .charAt(index)
get character in spesific index
2.3 .indexOf(”string”)
get index of first occurance of string
2.4 .lastIndexOf(”string”)
get index of last occurance of string
2.5 .trim()
remove white space from begening and end of string
2.6 .repeat(n)
repeat the string n times
3
2.7 syattsWith(”str”) — endsWith(”str”)
check if string ends pr starts with str
2.8 includes(str)
check if string includes the str
2.9 replace(str, rep) — replaceAll(str, rep)
replace first ocurence or all str of styring by rep
2.10 padStart(n, str) — padEnd(n str)
if string is of lenght l, then we add n-l str(s) to the begining or ending of string
(the lenght of new string is n)
Arrays
Add value
2.10.1 At the end
array.push(value);
// or
array = [...array, value];
2.10.2 At the begening
array.unshift(value);
Remove a value
2.10.3 From the ending
array.pop();
2.10.4 From the begening
array.shift();
4
2.10.5 by index:
array.splice(index, number_of_elements_to_remove);
Map function
array.map(callback);
Filter function
array.filter(callback);
2.11 sort
we use it to sort array elements in alphabet lixicographic order (ex: 1,2,10 will
sorted as 1,10,2)
2.12 sort strings
2.13 Ascending
array.sort();
2.14 Descending
array.sort((a,b)=>{
return b.localeCompare(a);
});
2.15 sort numbers
2.16 Ascending
array.sort((a,b)=>a-b);
5
2.17 Descending
array.sort((a,b)=>b-a);
3 slice(start, end)
take a substring or subarray of string or array if start or end are undefined, that
means we slice to the start or th end (like [0:] in python) we can use negative
indexes
4 Spread operator
The spread operator (...) allows an iterable (array or object pr string) to be
expanded in places where zero or more arguments or elements are expected.
In Arrays
Syntax:
let arr = [...iterable];
Example: Concatenating Arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2];
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]
Example: Function Call
function sum(a, b, c) {
return a + b + c;
}
let numbers = [1, 2, 3];
console.log(sum(...numbers)); // Output: 6
In Objects
Syntax:
let obj = {...iterable};
Example: Merging Objects
6
let obj1 = {a: 1, b: 2};
let obj2 = {c: 3, d: 4};
let combined = {...obj1, ...obj2};
console.log(combined); // Output: {a: 1, b: 2, c: 3, d: 4}
Rest Parameters in javascript
Rest parameters allow a function to accept an indefinite number of arguments
as an array.
Syntax:
function functionName(...restParameter) {
// function body
}
Example:
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7)); // Output: 22
5 .forEach()
to iterate an array
a = [1,2,3,4]
a.forEach( (item)=>{
console.log(item);
});
// => 1,2,3,4
6 .filter()
to filter an array
7
a = [1,2,3,4]
a.filter( (item)=>{
return item%2==0;
});
// => [2, 4]
7 .map()
Applies function (callback) to each element of an array (it return new array)
a = [1,2,3,4]
a.map( (item)=>{
return item%2==0;
});
// [false, true, false, true]
8 .reduce()
Reduce the elements of an array to a single value
a = [1,2,3,4]
a.reduce( (accumulator, item)=>{
return accumulator +|-|*|/|... item;
});
// if we sum the array elements then => 10
9 Objects
A collection of related properties and/or methods
o = {
p1: <value1>
p2: <value2>
.
.
.
method1: function()
{
8
.....
}
method2()
{
....
}
}
to acces property:
o.p1;
o.method1();
10 this
It reference to the object where THIS is used
• Global Context: this refers to the global object.
console.log(this); // In a browser, this will log the window object
• Function Context: this refers to the object the method is called on.
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};
obj.greet(); // Logs: Alice
• Constructor Functions: this refers to the new instance of the object
created.
function Person(name) {
this.name = name;
}
const bob = new Person('Bob');
console.log(bob.name); // Logs: Bob
9
• Arrow Functions: this inherits from the parent scope at the time they
are defined.
const obj = {
name: 'Alice',
greet: function() {
const innerGreet = () => {
console.log(this.name);
};
innerGreet();
}
};
obj.greet(); // Logs: Alice
• Explicit Binding: this can be explicitly set using call, apply, and
bind.
function greet() {
console.log(this.name);
}
const obj = {
name: 'Alice'
};
greet.call(obj); // Logs: Alice
• Default Binding: In strict mode, this remains undefined if not set by
the call; in non-strict mode, it defaults to the global object.
function greet() {
'use strict';
console.log(this);
}
greet(); // Logs: undefined
11 class
10
class Product
{
constructor(name, price)
{
this.name = name;
this.price = price;
}
displayProduct()
{
console.log(name+' '+price);
}
}
11.1 Inheritance
we use keyword extends, we can inheit parameters and methods.S
class A
{
name = 'a';
}
class B extends A
{
new B().name;
// => a
11.2 Setters and Getters
class A
{
constructor(age)
{
this.age = age;
}
}
set age(newAge)
{
11
if(age>0)
this._age = newAge;
else
console.error("age must be positive integer");
}
get age()
{
return this._age;
}
the underscroll age is naming covention means that this propertie is private.
11.3 super keyword
It used to call constructor or acces the proprieties and methods of parent su-
perclass.
class A
{
constructor(name)
{
this.name = name
}
function init()
{
....
}
}
class B extends A
{
contructor(name)
{
super(name);
super.init();
}
}
new B().name;
// => a
12
12 Destructuring
extract values from arrays and objects then assign them to a variables
12.1 Arrays
const array = [1,2,3];
const [a,b,c] = array;
//a=1 b=2 c=3
//we can combineit with REST operator
const [a, ...vars] = array
//a=1 vars=[2,3]
we can used it to swap variables:
a=1;
b=2;
[b,a] = [a,b];
//a=2 b=1
12.2 Objects
we can destruct an object and set default values to each variable.
const person ={
name:"madjid",
age:26
}
const {name,age.job='<default value>'} = person;
//name="madjid" age=26 job=<default value>
we can also destruct object passed as fonction parameter
function f({name,age,job="no job"})
{
consol.log(name);
}
f(person);
13
13 setTimout and setInterval
const id = setTimout( ()=>{ ,,, } , <time in ms> );
// to remove timout
clearTimout(id);
14 Error handling
we use try / catch to handle errors (finally will always get executed after
try/catch, we used generaly to close file, connections or release resources)
try
{
....
}
catch(error)
{
//console.error(error);
...
}
finally
{
....
}
15 DOM
DOM means Document Object Model
15.1 element selectors
• document.getElementById() //ELEMENT or NULL
• document.getElementByClassName() // HTML collection
• document.getElementByTagName() //HTML collection
• document.querySelector() //ELEMNT or NULL
• doucument.querySelectorALL() //NODELIST
HTML collection don’t have built-in foreach method so to iterate it we must
transformed to an Array
14
array = Array.from(<html collection>)
15.2 DOM navigation
• .firstElementChild
• .lastElementChild
• .nextElementSibling
• .previousElementSibling
• .parentElement
• .children //HTML collection
EX:
const elemnt = document.getElementById('element');
const firstChild = element.firstElementChild;
15.3 Create an element
const newElement = document.createElemnt("h1");
15.4 Change element attributes
newElement.id = "id"
15.5 Add elemnt to the DOM
15.5.1 At the begening or ending
we use appendChild and prependChild
const elemnt = document.getElementById('element');
element.appendChild(newElement) //add to the end
15.5.2 After or befor a specific element
we use insertBefore and insertAfter
15
const elemnt = document.getElementById('element');
const parent = document.getElementById('parent');
parent.insertBefore(element, newElement);
15.6 Rmove elemnt from DOM
we must select the parent of that element than remove it with .removeChild
const elemnt = document.getElementById('element');
const parent = document.getElementById('parent');
parent.removeChild(element);
15.7 change styles of element
all style properties are in camel notation.
element.style.backgroundColor = "white"
16 classList
css class of element
16.1 add class
element.classList.add("<class>");
16.2 remove class
element.classList.remove("<class>")
16.3 toogle
Remove class if present, add it if not.
element.classList.toogle("<class>")
16
16.4 replace
to replace exisitng class
16.5 contains
check if classList contains a class.
17 Events
17.1 add event listener to elemnt
element.addEventListenner(<event>, (event)=>{...})
17.2 Mouse events
Mouse events are click, mouseover, mouseout
17.3 Key events
Key events are keyup, keydown
we use event.key to know wich key has pressed.
Target
It’s the node element of target which the event was dispatched (it can be the
child of the element that contains onClick).
CurrentTarget
It’s the node element of target which the event was dispatched that contains
the onClick.
18 Promises
They are objects that manage asu=yncronious opertions
new Promise((resolve, reject)=>{
// .... asyncronoise code
if(<true>)
resolve(<value>);
17
else
reject(<value>);
}).then((<resolved value>)=>{
... code
}).catch( <rejected value> => {
...code
});
EX
new Promise((resolve, reject)=>{
console.log("task 1");
const rt1 = task1();
resolve(rt1);
}).then((rt1)=>{
return new Promise((resolve)=>{
consoerrole.log('task2');
const rt2 = task2();
resolve(rt2);
});
}).then((rt2) => {
console.log('all tasks are completed');
})
19 async / await
async make a function like a promise
await makes async function wait for a promise.
it allows to write asyncrinous code as a syncrinous code
(everything after await placed in an event queue)
in case of rejected we must souround the awaits with try, catch
async function f()
{
const rt1 = await new Promise((resolve, reject)=>{
console.log("task 1");
const rt1 = task1();
resolve(rt1);
});
const rt2 = await new Promise((resolve)=>{
consoerrole.log('task2');
18
const rt2 = task2();
resolve(rt2);
});
console.log('all tasks are completed');
}
20 JSON
JSON (JavaScript Object Notation) is data-iterchange format, used for ex-
changing data from server and web application.
it can be an array or object
• JSON.stringify() : convert a JS object to JSON string.
• JSON.parse() : convert JSON string to a JS object.
21 fetch
fetch(<url>, [<options>]).then(
(response)=>{
retrun resoponse.json()
}
).then((data)=>{
//json data
})
19