Skip to content

Instantly share code, notes, and snippets.

@josanua
Last active April 9, 2024 07:33
Show Gist options
  • Save josanua/60b2cd61b619bfdb93a872bcb8934221 to your computer and use it in GitHub Desktop.
Save josanua/60b2cd61b619bfdb93a872bcb8934221 to your computer and use it in GitHub Desktop.
JS Helper
// Books to read
https://exploringjs.com/impatient-js/
// Defines that JavaScript code should be executed in "strict mode".
'use strict';
// Need to study, in order:
https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript
https://www.digitalocean.com/community/tutorials/understanding-syntax-and-code-structure-in-javascript
/* ---- About ES6 Syntax (2015) ---- */
https://www.taniarascia.com/es6-syntax-and-feature-overview/
/* ---- Debugging ---- */
debugger;
/* ---- work with time, work date, work with date ---- */
new Date().toLocaleDateString()
// show time at the moment in seconds
console.log(Math.floor(Date.now() / 1000));
/* ---- Include scripts, external scripts ---- */
<script>JS Script</script>
// Include from files
// Absolute path
<script src = "/path/to/script.js"></script>
// Relative path, External References
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>
// If src is set, the script content is ignored.
<script src="file.js">
alert(1); // the content is ignored, because src is set
</script>
// ! Placing scripts at the bottom of the <body> element improves the display speed, because script interpretation slows down the display.
// scripts loading methods, loading optimization
https://www.w3schools.com/tags/att_script_defer.asp
https://www.oreilly.com/library/view/high-performance-javascript/9781449382308/ch01.html
// Cool light explication of
https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
defer - // Any <script> element marked with defer will not execute until after the DOM has been completely loaded, this holds true for inline scripts as well as for external script files.
// With defer, visitors’ browsers will still download the scripts while parsing the HTML, but they will wait to parse the script until after the HTML parsing has been completed.
async - // A script tag with async may be run as soon as it is loaded.
// Async does not pause HTML parsing to fetch the script (as the default behavior would), it does pause the HTML parser to execute the script once it’s been fetched.
// check ready state
readyState // - property
"uninitialized" // - The default state
"loading" // - Download has begun
"loaded" // - Download has completed
"interactive" // - Download has completed
"complete" // - All data is ready to be used
// Check if Document is loaded, jquery loaded
document.addEventListener("DOMContentLoaded", function(event) {
console.log('Dom Loaded');
// if need jquery
jQuery(document).ready(function ($) {
console.log('jQuery Loaded');
});
});
/* --- JavaScript Output --- */
// Writing into an HTML element, using innerHTML.
// Writing into the HTML output using document.write().
// Writing into an alert box, using window.alert().
// Writing into the browser console, using console.log().
/* --- JavaScript Syntax --- */
// Fixed values are called literals. Variable values are called variables.
// An expression is a combination of values, variables, and operators, which computes to a value.
/* --- work Code structure --- */
/* - Statements - */
// Statements are syntax constructs and commands that perform actions.
alert('Hello');
/* - Semicolons - */
// A semicolon may be omitted in most cases when a line break exists
This would also work:
alert('Hello')
alert('World')
// In most cases, a newline implies a semicolon. But “in most cases” does not mean “always”!
/* - Comments - */
// This comment occupies a line of its own
/* An example with two messages.
This is a multiline comment.
*/
// Nested comments are not supported!
/* --- Reserved words --- */
https://www.w3schools.com/js/js_reserved.asp
/* --- work Variables, work vars, Scope, and Hoisting in JavaScript, var scope, var hoisting --- */
https://javascript.info/variables
https://www.w3schools.com/js/js_let.asp
https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript
// A variable is a named container used for storing values.
// Variable names are case-sensitive
let – is a modern variable declaration. ( Using a let variable before it is declared will result in a ReferenceError. )
var – is an old-school variable declaration.
const – is like let, but the value of the variable can’t be changed.
// Difference between var, let, and const.
Keyword Scope Hoisting Can Be Reassigned Can Be Redeclared
var Function scope Yes Yes Yes
let Block scope No Yes No
const Block scope No No No
// Which of the three you should use in your own programs?
// A commonly accepted practice is to use const as much as possible, and let in the case of loops and reassignment.
// check if a global var exists, check global var
if (typeof x != 'undefined') {}
// better
if (window.x){} // from global window object
if (window.x !== undefined) // analog typeof x
//-- Vars scopes, variable scope --//
// Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global:
Global variables - are those declared outside of a block
Local variables - are those declared inside of a block
Global - visible by everything
Function - visible within a function (and its sub-functions and blocks)
Block - visible within a block (and its sub-blocks)
Module - visible within a module
// let, const and var are all hoisted!!!
// In a browser, global functions and variables declared with var (not let/const!) become the property of the global object:
var - Identifiers declared using var have function scope.
let and const - Identifiers declared using let and const have block scope.
/*
- Variable naming
There are two limitations on variable names in JavaScript:
1. The name must contain only letters, digits, or the symbols $ and _.
2. The first character must not be a digit.
*/
// Examples
// example of one line declaration
"use strict";
let user = 'Jon', age = 25, message = 'Hello';
var user = 'Jon', age = 25, message = 'Hello';
let user = 'Jon';
let age = 25;
let message = 'Hello';
let user = 'John',
age = 25,
message = 'Hello';
// A variable declared without a value will have the value = undefined.
// Check if a global var exists, check global var
if (typeof x != 'undefined') {}
// better
if (window.x){} // from global window object
if (window.x !== undefined) // analog typeof x
/* - Constants - */
// constants are named using capital letters and underscores.
const COLOR_RED = "#F00"; // constants that are known prior to execution
// constants that are calculated in run-time
const pageLoadTime = /* time taken by a webpage to load constants that are calculated in run-time */
/* - Global window object, work window object - */
// get site links, get links
window.location.origin - home link
window.location.href - current page link
// see
window.varName
/*** --- work Data types --- ***/
https://developer.mozilla.org/ru/docs/Web/JavaScript/Data_structures
// There are 8 basic data types in JavaScript. 7 of them are primitives (contain only one value)
// - Primitive
// In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties.
// There are 7 primitive data types:
number - // for numbers of any kind: integer or floating - point, integers are limited by ±2(53).
string - // for strings. A string may have one or more characters, there’s no separate single - character type.
bigint - // is for integer numbers of arbitrary length. ( A BigInt is created by appending - n - to the end of an integer literal. But supported in Safari / IE / Edge. )
boolean - // for true / false.
null - // for unknown values – a standalone type that has a single value null.
undefined - // for unassigned values – a standalone type that has a single value undefined.
symbol - // for unique identifiers.
object - // for more complex data structures.
/*
object
- Array's
- functions()
- objects
- regular expressions
- errors
*/
/* typeof check data type
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/typeof
The typeof operator allows us to see which type is stored in a variable.
Two forms, Returns a string with the name of the type.
For null returns "object" – this is an error in the language, it’s not actually an object.
*/
typeof x or typeof(x)
// The typeof operator returns "object" for objects, arrays, and null. The typeof operator returns "object" for arrays because in JavaScript arrays are objects.
/* - strings - */
https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
// In JavaScript, there are 3 types of quotes.
/*
1. Double quotes: "Hello".
2. Single quotes: 'Hello'.
3. Backticks: `Hello`.
- Backticks are “extended functionality” quotes. They allow us to embed variables and expressions into a string by wrapping them in ${…}
*/
let str = "Hello";
let str2 = 'Single quotes are ok too';
let phrase = `can embed another ${str}`;
/* - null - */
// In JavaScript, null is not a “reference to a non - existing object” or a “null pointer” like in some other languages.
// It’s just a special value which represents “nothing”, “empty” or “value unknown”.
/* - undefined - */
/*
The special value undefined also stands apart. It makes a type of its own, just like null.
The meaning of undefined is “value is not assigned”.
If a variable is declared, but not assigned, then its value is undefined:
*/
let x = 123;
x = undefined;
alert(x); // "undefined"
// ! use null to assign an “empty” or “unknown” value to a variable, and we use undefined for checks like seeing if a variable has been assigned.
// For null returns "object" – this is an error in the language, it’s not actually an object.
/* - Objects and Symbols - */
// The object type is special. Objects are used to store collections of data and more complex entities.
/* --- work numbers --- */
isNaN(num) // returns true if the variable does NOT contain a valid number
// generate random numbers
https://www.joshwcomeau.com/snippets/javascript/random/
Math.floor(Math.random() * (max - min)) + min;
/* --- work map and Set, map(), map method--- */
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
https://learn.javascript.ru/map-set
// Map objects are collections of key - value pairs
// Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.
// The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
// You shouldn't be using map if:
// - you're not using the array it returns; and/or
// - you're not returning a value from the callback.
map();
const map1 = new Map();
// simple example
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
// Methods and properties are:
new Map() – creates the map.
map.set(key, value) – stores the value by the key.
map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
map.has(key) – returns true if the key exists, false otherwise.
map.delete(key) – removes the value by the key.
map.clear() – removes everything from the map.
map.size – returns the current element count.
/*** --- work strings --- ***/
// Refference
https:learn.javascript.ru/string
https:www.w3schools.com/jsref/jsref_obj_string.asp
https:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
// string methods
const str = 'test';
str.length (4)
str[0] (t);
// clear from whitespace, replace string value
str.trim();
replace(/ /g,"-") //replace white space with "-"
str.toLowerCase()
str.toUpperCase()
str.slice(); // Extracts a part of a string and returns a new string
str.substring(); // Extracts the characters from a string, between two specified indices
str.substr() // Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
const test = "12.2px";
parseInt(test); // return 12 - function parses a string and returns an integer.
// Poisk pod stroki
https: //www.w3schools.com/jsref/jsref_indexof.asp
str.indexOf()
/* - string interpolation - */
// quotes
let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;
// interpolation
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
let category = 'toys';
// put var in ${} in backtick (` `)
console.log(`https://someurl.com/${category}/5`) // result https://someurl.com/toys/5
// for object
$ {
objectname.propertyName
}
// make calculations
$ {
one + two
}
// Convert string to number
Number()
/* --- work Interaction: alert, prompt, confirm --- */
https: //javascript.info/alert-prompt-confirm
alert() - shows a message
prompt() - shows a message asking the user to input text.It returns the text or, if Cancel button or Esc is clicked, null. In IE: always supply a default
confirm() - shows a message and waits for the user to press“ OK” or“ Cancel”.It returns true for OK and false for Cancel / Esc.
// The function prompt accepts two arguments:
result = prompt(title, [default]);
/* --- work Operators --- */
https: //www.w3schools.com/js/js_operators.asp
* An operand - is what operators are applied to. Example 5 * 2 there are two operands: the left operand is 5 and the right operand is 2.
Sometimes, people call these“ arguments” instead of “operands”.
* An operator is unary if it has a single operand.For example, the unary negation - reverses the sign of a number: x = -x;
* An operator is binary if it has two operands.The same minus exists in binary form as well: y - x
+ Addition
- Subtraction
* Multiplication
** Exponentiation(ES2016)
/ Division
% Modulus(Division Remainder)
++ Increment
-- Decrement
// restul la impartire %
a % b
// ridicarea la putere **, rise to power, Exponentiation
2 ** 3 // 8 (2 * 2 * 2)
/* - work String concatenation, binary + - */
// Usually, the plus operator + sums numbers. But, if the binary + is applied to strings, it merges (concatenates) them.
// if one of the operands is a string, the other one is converted to a string too.
alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"
// left to right, the numbers will be added before being converted to a string:
alert(2 + 2 + '1' ); // "41" and not "221"
/* - Numeric conversion, unary + - */
// If the operand is not a number, the unary plus converts it into a number.
// No effect on numbers
let x = 1;
alert( +x ); // 1
let y = -2;
alert( +y ); // -2
// Converts non-numbers
alert( +true ); // 1
alert( +"" ); // 0
// It actually does the same thing as Number(...), but is shorter.
/* - Operator precedence - */
// If an expression has more than one operator, the execution order is defined by their precedence, or, in other words, the default priority order of operators.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
/* - Operator Exponentiation ** - */
// a ** b is a multiplied by itself b times.
alert( 2 ** 4 ); // 16 (2 * 2 * 2 * 2)
// The operator works for non-integer numbers as well.
alert( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root, that's maths)
alert( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
/* - work Increment/decrement - */
// Increment/decrement can only be applied to variables. Trying to use it on a value like 5++ will give an error.
// Increment ++ increases a variable by 1:
// Decrement -- decreases a variable by 1:
// When the operator goes after the variable, it is in “postfix form” : counter++.
// The “prefix form” is when the operator goes before the variable: ++counter.
let counter = 1;
let a = ++counter; // 2
let b = counter++; // 1
// If we’d like to increase a value and immediately use the result of the operator, we need the prefix form:
let counter = 0;
alert( ++counter ); // 1
// If we’d like to increment a value but use its previous value, we need the postfix form:
let counter = 0;
alert( counter++ ); // 0
/* - Modify-in-place - */
let n = 2;
n = n + 5;
n = n * 2;
n += 5; // now n = 7 (same as n = n + 5)
n *= 2; // now n = 14 (same as n = n * 2)
n *= 3 + 5; // 16 (right part evaluated first, same as n *= 8)
/* --- Comparisons --- */
https: //learn.javascript.ru/comparison
true – means“ yes”, “correct” or“ the truth”
false – means“ no”, “wrong” or“ not the truth”
Boolean() - function to detect value
Strict equality A regular equality check == has a problem. It cannot differentiate 0 from false:
== - It cannot differentiate 0 from false
(0 == false) // true
('' == false) // true
(0 === false); // false, because the types are different
!== - strict non-equality
/*
Comparison operators return a boolean value.
Strings are compared letter - by - letter in the“ dictionary” order.
When values of different types are compared, they get converted to numbers(with the exclusion of a strict equality check).
The values null and undefined equal == each other and do not equal any other value.
Be careful when using comparisons like > or < with variables that can occasionally be null / undefined.Checking
for null / undefined separately is a good idea.
*/
/*** --- work objects, work object --- ***/
/* In JavaScript, objects are king. If you understand objects, you understand JavaScript. */
// www.w3schools.com/js/js_objects.asp
// https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics
// create empty object
let objectName = new Object(); // "object constructor" syntax
let objectName = {}; // "object literal" syntax
// create an object with data
// An object like this is referred to as an object literal — we've literally written out the object contents as we've come to create it.
let objectName = {
name: "John", // key/value
lastName: "Doe",
age: 30,
"likes birds": true // object property name which is consist of many words must be in "" quotes
fullName: function () { // object method
return this.name + " " + this.age;
},
// or with arrow func
fullName: () => {
return this.name + " " + this.age;
},
// or with simpler syntax without (function) word
introduceSelf() {
console.log(`Hi! I'm ${this.name[0]}.`);
},
};
// An object like this is referred to as an object literal — we've literally written out the object contents as we've come to create it.
// --> object properties, properties of an object
https://www.w3schools.com/js/js_object_properties.asp
// Values pairs in JavaScript objects are called properties:
// You can access object properties in two ways
objectName.propertyName
objectName["propertyName"]
// or add data to them
objectName.propertyName = 'data';
objectName["propertyName"] = 'data';
// access an object method
objectName.methodName()
// check if value exists, object check
objectName.newKeyName === undefined;
// check with 'in' operator
'newKeyName' in objectName;
// --> work with objects, work objects <-- //
//- delete object property
// !!! The delete operator should not be used on predefined JavaScript object properties
delete objectName.propertyName // The delete keyword deletes both the value of the property and the property itself.
//- loops through the properties of an object.
for (let variable in object) {
// code to be executed
}
for (key in objectName) {}
// отфильтровывает свойства, которые принадлежат не самому объекту, а его прототипу.
for(prop in object) {
if (!object.hasOwnProperty(prop)) continue
//...
}
// Более элегантный вариант записи:
for(prop in object) if (object.hasOwnProperty(prop)) {
//...
}
// --> another examples
const options = {
name: 'test',
width: 1024,
height: 1024,
colors: {
border: 'black',
bg: 'red'
},
makeTest: function(){
console.log("Method Test");
}
}
options.makeTest();
Object.keys(options) will return array
// take object length
Object.keys(options).length;
console.log(Object.keys(options).length); return array length
console.log(options["colors"]["border"]);
// run trough object with objects
// for loop to go trough object values
for (let key in options) {
if( typeof(options[key]) === 'object' ) {
for (let i in options[key]) {
console.log(`Property ${i} have value ${options[key][i]}`);
}
} else {
console.log(`Property ${key} have value ${options[key]}`);
}
}
// Use of Object.keys, object.keys(), object keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
// array-like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array-like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']
// find object keys quantity
console.log(Object.keys(objectName).length);
// object keys, iterate object keys with map
const obiect = { 'one': 100, 'two': 200 };
{
Object.keys(obiect).map(
item => item + ' ' + obiect[item]
)
}
// we have and object keys value
Object.values(obj)
//--> get object length, length of object
Object.keys(objName).length;
Object.values(objName).length;
//--> create map from object
let obj = {
name: "John",
age: 30
};
let map = new Map(Object.entries(obj));
//--> filter array with objects (nested objects), objects with objects <--//
// If data is an object containing a property named items,
// and items is an object with numeric keys and nested objects,
// you can filter it without converting it to an array.
// Here's how you can filter out objects with status: 0:
const data = {
items: {
0: { id: 1, name: 'Item 1', status: 1 },
1: { id: 2, name: 'Item 2', status: 0 },
2: { id: 3, name: 'Item 3', status: 1 },
3: { id: 4, name: 'Item 4', status: 0 }
}
};
// Initialize an empty object to store filtered items
const filteredItems = {};
// Iterate over the keys of the items object
for (const key in data.items) {
// Check if the status is not 0
if (data.items[key].status !== 0) {
// Add the item to the filtered items
filteredItems[key] = data.items[key];
}
}
console.log(filteredItems);
// Object.entries()
// The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// clonarea obiectelor, object clones
let user = {
name: "John",
age: 30
let clone = {}; // новый пустой объект
};
// copiem toate propietatile dintr-un obiect in altul
for (let key in user) {
clone[key] = user[key];
}
// functie custom pentru copierea (clonarea) obiectului, dar este superficiala (primul nivel)!
function copy(mainObj) {
let objCopy = {};
let key;
for (key in mainObj) {
objCopy[key] = mainObj[key];
}
return objCopy;
}
// concatenarea obiectelor, la fel superficiale dar independente, cloning objects
Object.assign(obj1, obj2);
let clone = Object.assign({}, object);
//--> Spread Operator, ...
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
// cloning object with spread operator
const video = ['youtube', 'videmo', 'rutube'],
blogs = ['wordpress', 'livejournal', 'blogger'],
internet = [...video, ...blogs, 'vk', 'face'];
console.log(internet);
const q = {
one: 1,
two: 2
}
const newObj = {...q};
//--> work object Destructuring assignment, destructurization
https://javascript.info/destructuring-assignment
// Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
// The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
Object.entries()
//--> Array destructuring, array destruct
// simple example
let arr = ["John", "Smith"]
let [firstName, surname] = arr;
console.log(firstName); // John
console.log(surname); // Smith
let [item1 = default, item2, ...rest] = array;
// destructuring looks great with split();
// split() method divides a String into an ordered list of substrings,
let [firstName, surname] = "John Smith".split('');
// Ignore elements using commas
// Unwanted elements of the array can also be thrown away via an extra comma
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
console.log( title ); // Consul
// The rest ‘…’
let [name1, name2, ...titles] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
// now titles = ["Consul", "of the Roman Republic"]
// for object the same instance
let user = {};
[user.name, user.surname] = "John Smith".split('');
// Default values
let [firstName, surname] = [];
firstName // undefined
surname // undefined
//--> Object destructuring
let {var1, var2} = {var1:…, var2:…}
// with default examples
let {prop : varName = default, ...rest} = object
// example
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title, width, height} = options;
// changed the order in let {...}
let {height, width, title} = { title: "Menu", height: 200, width: 100 }
// If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w
let options = {
title: "Menu",
width: 100,
height: 200
};
// { sourceProperty: targetVariable }
let {width: w, height: h, title} = options;
// The order does not matter. This works too:
// changed the order in let {...}
let {height, width, title} = { title: "Menu", height: 200, width: 100 }
//-> Object properties configuration, getter & setter
// https://javascript.info/property-accessors
// https://javascript.info/property-descriptors
Property flags and descriptors
Property getters and setters
// Swap variables trick
[guest, admin] = [admin, guest]; // change values with places
/* ---- work Constructor, Constructor function, operator "new" ---- */
// That’s the main purpose of constructors – to implement reusable object creation code.
https://javascript.info/constructor-new
// Constructor functions technically are regular functions. There are two conventions though:
// 1. They are named with capital letter first.
// 2. They should be executed only with "new" operator.
// Example
function User(name) {
this.name = name;
this.isAdmin = false;
}
let user = new User("Jack");
// Methods in constructor
function User(name) {
this.name = name;
this.sayHi = function() {
alert( "My name is: " + this.name );
};
}
let john = new User("John");
john.sayHi(); // My name is: John
/*** --- work Conditional operators: if, '?', functions, loops, cicluri --- ***/
// ternary operator
(condition) ? true : false;
/* --- work loop for, work for loop --- */
for - loops through a block of code a number of times
for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
while – Проверяет условие перед каждой итерацией.
do..while – Проверяет условие после каждой итерации.
for (;;) – Проверяет условие перед каждой итерацией, есть возможность задать дополнительные настройки.
/* --- work Loops: while and for --- */
// for looping array or object
for (variable of iterable) {
// code block to be executed
}
while (condition) {
// code block to be executed
}
do {
// code block to be executed
}
while (condition);
break; // "jumps out" of a loop.
continue; // "jumps over" one iteration in the loop.
/*** --- work logical operators, logic --- ***/
https://learn.javascript.ru/logical-operators
|| (OR)
ИЛИ «||» находит первое истинное значение
( true || true ); // true
( false || true ); // true
( true || false ); // true
( false || false ); // false
&& (AND)
И «&&» находит первое ложное значение
Когда все значения верны, возвращается последнее
( true && true ); // true
( false && true ); // false
( true && false ); // false
( false && false ); // false
! (NOT)
/* --- work The "switch" statement, work switch --- */
https://www.w3schools.com/js/js_switch.asp
// Use the switch statement to select one of many code blocks to be executed.
// Switch cases use strict comparison (===) !!!
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
// The switch expression is evaluated once.
// The value of the expression is compared with the values of each case.
// If there is a match, the associated block of code is executed.
// If there is no match, the default code block is executed.
/* --- work Functions, functions declaration, function declaration --- */
https: //learn.javascript.ru/function-basics
https: //www.w3schools.com/js/js_function_definition.asp
// Some basic rules
// JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined.
// despre variabile
// variabilele globale pot fi utilizate de functii daca ele nu sunt rescrise in functie
// de dorit ca var. globale sa fie utilizate la minimum si numai in caz de necesitatea de a transmite aceleasi date in cod, in acest caz e mai bine cu const. eu cred.
//--> Types of Function Declarations
/* - work Function declarations - */
function functionName(parameters) {
// code to be executed
}
// function expression - (ea se executa cind codul ajunge la ea)
let foo = function() {
// code to be executed
}
foo(); // nu se executa inainte de declarare (asociere)
/* - work Arrow functions, arrow functions - */
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
// arrow function
() => {} // don't have context of 'this'
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
// or multi-line syntax with { ... }, need return here:
let sum = (a, b) => {
return a + b;
}
// without arguments
let sayHi = () => alert("Hello");
// with a single argument
let double = n => n * 2;
//-> The Function() Constructor
var myFunction = new Function("a", "b", "return a * b");
//-> Self-Invoking Functions
(function () {
var x = "Hello!!"; // I will invoke myself
})();
// Arguments .length property returns the number of arguments received when the function was invoked
function myFunction(a, b) {
return arguments.length;
}
// JavaScript functions can be used in expressions:
var x = myFunction(4, 3) * 2;
/* - Return - */
// daca dorim sa returnam o expresie lunga
// return (
// some + long + expression
// + or +
// whatever * f(a) + f(b)
// )
// Daca functia nu returneaza valoare atunci v-a returna undefined:
// idei denumiri functii
"get…" – returneaza valoare,
"calc…" – calculeaza ceva,
"create…" – creaza ceva,
"check…" – verifica ceva.
showMessage(..) // показывает сообщение
getAge(..) // возвращает возраст (в каком либо значении)
calcSum(..) // вычисляет сумму и возвращает результат
createForm(..) // создаёт форму (и обычно возвращает её)
checkPermission(..) // проверяет доступ, возвращая true/false
//-> JavaScript Closures, Scope, work scope
// In a web page, global variables belong to the window object.
// All functions have access to the global scope.
// JavaScript supports nested functions. Nested functions have access to the scope "above" them.
// JavaScript has 3 types of scope:
// Block scope
// Function scope
// Global scope
//---> Block Scope
{
let x = 2;
}
// x can NOT be used here
// Variables created without a declaration keyword (var, let, or const) are always global, even if they are created inside a function.
function myFunction() {
a = 4;
}
// x CAN be used here
{
var x = 2;
}
// x CAN be used here
//---> Function Scope:
// JavaScript has function scope: Each function creates a new scope.
// They can only be accessed from within the function.
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
function sum(a) {
return function(b) {
return a + b; // берёт "a" из внешнего лексического окружения
};
}
console.log(sum(1)(2)) ;
// -> Callback, callbacks, work callback,
// A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
// A callback function is executed after the current function is 100% finished
// https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
// https://javascript.info/callbacks
// example (The above example is a synchronous callback, as it is executed immediately)
function firstFunc(callback) {
callback();
}
function secondFunc() {
console.log('executed');
}
firstFunc(secondFunc); // When you pass a function as an argument, remember not to use parenthesis.
/* --- work this context, work with this context --- */
// 1. In ordinary function this will be: this = window object but if will be applyed use strict - undefined
// 2. Context this in object will be object itself
// 3. This in class and constructors it's a new object item
// 4. Add context with hands this: call, apply, bind
/* --- work promise, work promises --- */
https://learn.javascript.ru/promise-basics
https://www.w3schools.com/Js/js_promise.asp
// "I Promise a Result!"
let promise = new Promise(function(resolve, reject) {
// "Producing Code" (May take some time) - then the promise is created this funtcion will be automatically executed.
});
// resolve and reject params are callbacks
// Some explanation
// "Producing code" is code that can take some time
// "Consuming code" is code that must wait for the result
// A Promise is a JavaScript object that links producing and consuming code
/* --- work JavaScript specials --- */
/* --- Events --- */
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
// UI events list
https://developer.mozilla.org/en-US/docs/Web/API/UI_Events
DOMContentLoaded - DOM content loaded
addEventListener() - https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
// Property
target
currentTarget
// basic example
// store a reference to the element
document.getElementById("myButton").addEventListener("click", function () {
alert("Button was clicked!");
});
// steps
// 1 register event on necesarry element
const btn = document.querySelector('button');
// 2. adding event handlers
btn.addEventListener('click', () => {
// do something
// console.log(this)
});
// 3. you can remove it
btn.removeEventListener('click', changeBackground);
// detect clicked element, detect element
document.addEventListener('click',(e) =>
{
// Get element class(es)
// let elementClass = e.target.className;
let elementClass = e.target;
console.log(elementClass);
}
);
// add event only on dedicated elements, on all elements with the same class or
document.querySelectorAll('.identificator-name-type').forEach(occurence => {
occurence.addEventListener('click', (e) => {
console.log(e.target);
});
});
// another simple example
element.forEarch(btn => {
btn.addEventListener('click', doSomethingFunction)
})
// prevent default, event prevent
const link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault();
})
/* --- work array --- */
https://www.w3schools.com/js/js_arrays.asp
https://www.w3schools.com/jsref/jsref_obj_array.asp
// spargalka, helper file
https://drive.google.com/file/d/17D4THU5-UJtzihybKVjSDHeX67pz3xLR/view
Array();
// declare new empty array
let arr = new Array();
let arr = [];
// add values to array
arr[] = 'value';
// determines whether the passed value is an Array, check if array type, check array, array type
Array.isArray(obj) // return boolean
// get length of array
arr.length
// Concatenate array's
arr.concat() // The concat() method is used to join two or more arrays.
array1.concat(array2, array3, ..., arrayX)
// concat items in new map data
arr.map(item => item)
arr.map(item => item + ", ")
// Splice ARRAY with checked elements, remove elements from array.
// The splice() method adds/removes items to/from an array, and returns the removed item(s).
arrayName.splice($.inArray(valueName, arrayName), 1);
// order type
// Methods pop/push, shift/unshift
push // add element to the end of
shift // удаляет элемент в начале, сдвигая очередь, так что второй элемент становится первым.
// Методы, работающие с началом массива, медленно.
shift // Удаляет из массива первый элемент и возвращает его
unshift // Добавляет элемент в начало массива:
// Методы, работающие с концом массива:
// stack type, выполняются быстро
push // добавляет элемент в конец. array.push(...) = array[array.length] = 'value';
pop // Удаляет последний элемент из массива и возвращает его.
// Методы push и unshift могут добавлять сразу несколько элементов:
array.push("value1", "value2");
array.unshift("value1", "value2");
//--> Duplicate array, copy array
const oldArray = ['a', 'b', 'c'];
const newArray = oldArray.slice();
// https://www.w3schools.com/jsref/jsref_slice_array.asp
array.slice(start, end)
// --> traversing array
// traversing methods
arr.forEach
arr.map
arr.every / arr.some
arr.filter
arr.reduce
// foreach array, traversing array
// Перебор элементов, array elements
for (let i = 0; i < arr.length; i++) {
alert(arr[i]);
}
// Но для массивов возможен и другой вариант цикла, for..of:
// get array elements, not for objects, it's for array, pseudo-array, string, map
for (let value of arr) {
console.log(value);
}
// gasirea mijlocului si modificarea valorii
// varianta mea
for ( let i = 0; i < array.length; i++){
if (i == Math.floor(array.length / 2)){
array[i] = newValue;
}
}
// varianta data ca idee
array[Math.floor((array.length - 1) / 2)] = newValue;
// method to work with array, in foreach can't use break or continue
arr.forEach(function(item, i, arr){
console.log(`${i}: ${item} in to array ${arr}`);
})
// Iterations methods, Iterative methods
// array iterations methods
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods
arr.forEach
arr.map
arr.every/some
arr.filter
arr.reduce
.map() - // It calls a provided callbackFn function once for each element in an array and constructs a new array from the results.
/* --- work array sorting, array algorithms, sorting array --- */
// https://www.w3schools.com/js/js_array_sort.asp
arr.sort();
// The sort() method sorts an array alphabetically
// quick sorting, with callback func
const arr = [2, 4, 50, 8, 9, 12, 94];
function compareNum(a, b) {
return a - b;
}
arr.sort(compareNum);
/* --- work json --- */
https://learn.javascript.ru/json
JSON.stringify() // convert object to JSON.
JSON.parse() // convert JSON to object.
/*** --- BOM - Browser Object Model --- ***/
alert(location.href); // show current URL
if (confirm("Перейти на Wikipedia?")) {
location.href = "https://wikipedia.org"; // redirect browser to another address
}
// global browser object
window (globalThis object) // global object and browser window manipulator
window.innerHeight (height in px)
navigator.userAgent – информация о текущем браузере
navigator.platform - информация о платформе
location - obtain current url data
location.origin
/*** --- work DOM Document Object Model, work DOM --- ***/
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction
https://www.w3schools.com/whatis/whatis_htmldom.asp
DOM Living Standard на https://dom.spec.whatwg.org
// DOM objects properties
https://www.w3schools.com/jsref/dom_obj_all.asp
//--- DOM - navigation, work dom navigation
// https://javascript.info/dom-navigation
// <html> = document.documentElement
// <body> = document.body
// <head> = document.head
// DOM collections
// We can use for..of to iterate over it, Array methods won’t work, because it’s not an array.
// !!! Don’t use for..in to loop over collections
for (let node of document.body.childNodes) {
console.log(node); // shows all nodes from the collection
}
// load DOM, check DOM loaded
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
//--> Some Basis
// Finding HTML Elements
document.getElementById("intro");
document.getElementsByTagName("p");
document.getElementsByClassName("intro");
document.querySelectorAll("p.intro"); // does not work in Internet Explorer 8 and earlier versions.
// Finding HTML Elements by HTML Object Collections
document.anchors
document.forms
document.images
document.links
document.scripts
//--- DOM global objects ---//
https://javascript.info/global-object
document // global object, entry point
document.documentElement // all elements
document.body // body element
globalThis // it's a standardized name for a global object, that should be supported across all environments.
// Summary:
// - The global object holds variables that should be available everywhere.
// - That includes JavaScript built-ins, such as Array and environment-specific values, such as window.innerHeight – the window height in the browser.
// - The global object has a universal name globalThis.
// …But more often is referred by “old-school” environment-specific names, such as window (browser) and global (Node.js).
// - We should store values in the global object only if they’re truly global for our project. And keep their number at minimum.
// - In-browser, unless we’re using modules, global functions and variables declared with var become a property of the global object.
// - To make our code future-proof and easier to understand, we should access properties of the global object directly, as window.x.
//--- DOM tree, Walking the DOM, ---//
// The backbone of an HTML document is tags. Every HTML tag is an object.
// The topmost tree nodes are available directly as document properties:
// <html> = document.documentElement
// <body> = document.body
// <head> = document.head
// in DOM world null mean not exists.
// global declared data
// In a browser, global functions and variables declared with var (not let/const!) become the property of the global object!
// If a value is so important that you’d like to make it available globally, write it directly as a property:
window.currentUser = {
name: "John"
};
// get objects val.
currentUser.name
window.currentUser.name
// childrens
childNodes, firstChild, lastChild
// view all childNodes collection lists.
for (let i = 0; i < document.body.childNodes.length; i++) {
alert( document.body.childNodes[i] ); // Text, DIV, Text, UL, ..., SCRIPT
}
// Summary:
// An HTML/XML document is represented inside the browser as the DOM tree.
// - Tags become element nodes and form the structure.
// - Text becomes text nodes.
// - …etc, everything in HTML has its place in DOM, even comments.
//--- DOM collections ---//
// DOM collections are read-only
// DOM collections are live - In other words, they reflect the current state of DOM.
// ! - Don’t use for..in to loop over collections - Collections are iterable using for..of.
childNodes - // it's a collection, a special array-like iterable object.
// We can use for..of to iterate over it:
for (let node of document.body.childNodes) {
alert(node); // shows all nodes from the collection
}
//--- Siblings and the parent
// Siblings are nodes that are children of the same parent.
// For instance, here <head> and <body> are siblings:
{/* <html>
<head>...</head><body>...</body>
</html> */}
// get/take DOM elements
// https://learn.javascript.ru/searching-elements-dom
// selectors https://learn.javascript.ru/css-selectors
// https://www.w3schools.com/js/js_htmldom_nodelist.asp
document.getElementById(id) // take element by id, exists global var with this id:name
elem.querySelectorAll(css) // the most versatile method
// There are 6 main methods to search for nodes in DOM:
// search in element
querySelector // returns the first Element, with CSS-selector, call on an element, If no matches are found, null is returned.
querySelectorAll // NodeList, CSS-selector, call on an element.
getElementById // id
// return a live collection
getElementsByName // name, show live state of DOM
getElementsByTagName // tag or '*', show live state of DOM
getElementsByClassName // HTMLCollection[], class, show live state of DOM
elem.matches(css) // to check if elem matches the given CSS selector.
elem.closest(css) // to look for the nearest ancestor that matches the given CSS-selector. The elem itself is also checked.
.contains() // check if element contain needed classes
// get elements
document.getElementsById('box'); // return element
document.getElementsByTagName('elem'); // return pseudoarray (html collection)
document.getElementsByClassName('elemName'); // return pseudoarray (html collection)
document.querySelectorAll('button'); // return array - NodeList (html collection)
document.querySelector('button');
// exemplu document.querySelectorAll('button'), are metoda foreach
// foreach
button.forEach(item => {
console.log(item);
})
// :hover si :active la fel se pot aplica
document.querySelectorAll(':hover');
// some examples
document.body.classList.contains('class_name') // check if <body> contains class_name
document.querySelector("[data-popup-id='job-alert-form']").classList.add('is-active'); // add class to tag with 'data-popup-id' property, get data attribute
// element get atribute
element.getAttribute('data-video-url');
//--- manipulating DOM collections, create elements ---//
const div = document.createElement('div');
document.querySelector('.elem-name').append(div); // add element in .elem-name
wrapper = document.querySelector('.wrapper');
wrapper.append(div); // appendChild() old ver.
wrapper.prepend(div);
// the same like append and prepend
.after(div);
.before(div);
.remove(div); // .removeChild(div)
.replaceWith();
// old methods
.appendChild(div);
.removeChild(div);
.insertBefore(div, hearts[0]);
.replaceChild(div, div);
// insert content
div.innerHTML = "<h1>Hello World</h2>"; // use only for html
div.textContent = "Hello World"; // use only for text
/*** --- work debug, debugg, work debugger --- ***/
debugger; // will stop on this line and open Dev Tools
/*** --- work mobile, work DOM mobile --- ***/
// touchstart
// touchmove
// touchend
// touchenter
// touchleave
// touchcancel
// targetTouches
// changedTouches
// Test on DOM loaded
window.addEventListener('DOMContentLoaded', () => {
const box = document.querySelector('.box');
box.addEventListener('touchstart', (e) => {
e.preventDefault();
console.log('Start');
})
})
/* --- Element.classList --- */
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
// example
const div = document.createElement('div');
div.className = 'foo';
console.log(div.outerHTML);
// enum. classes
div.classList.length
// obtain first class name in element classes list
div.classList.item(0)
// check if class exists
div.classList.contains('className'); // return boolean
// use the classList API to remove and add classes
div.classList.remove("foo");
div.classList.add("anotherclass");
// if visible is set remove it, otherwise add it
div.classList.toggle("visible");
// add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );
// add or remove multiple classes
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");
// add or remove multiple classes using spread syntax
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);
// replace class "foo" with class "bar"
div.classList.replace("foo", "bar");
// find match className in classList
Element.matches(selectorString)
https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
//--> work event delegation, event-delegation
https://learn.javascript.ru/event-delegation
/* --- work with DOM styles, work DOM styles --- */
object.style
object.style.borderRadius = '100%';
object.style.cssText = 'background-color: red; width: 90px';
/* --- work with this context, work context this --- */
/* --- ES6 Modules, module, work modules --- */
// JavaScript modules allow you to break up your code into separate files.
// A module is just a bit of code encapsulated in a file, and exported to another file.
https://www.w3schools.com/js/js_modules.asp
https://medium.com/@cgcrutch18/commonjs-what-why-and-how-64ed9f31aa46
/* There are two types of exports:
Named Exports
Default Exports
*/
/* --- Import Functions --- */
// The main difference between named and default exports and imports is that you can have multiple named exports per file, but you can only have a single default export.
// 👇️ named export
export function funcName() {}
export function funcName2() {}
// 👇️ named import
import {funcName, funcName2} from './import-func-file.js';
/* --- work Regex --- */
// Tools for testing https://regex101.com/
// general version of pattern
/(<([^>]+)>)/gi
// my version for eliminating (...) in the end of sentence
/(<([^>]+)[>|\ ...])/gi
export function stripHTMLTags(originalString = '') {
const regex = /(<([^>]+)[>|\ ...])/gi;
let strippedString = '';
if (originalString !== '') {
strippedString = originalString.replace(regex, "")
} else {
console.log('Nofitication: No "job.short_description" text from API');
}
return strippedString;
}
//--- work fetch(), work with fetch API, Fetch API ---//
// The Fetch API provides an interface for fetching resources (including across the network).
// The Fetch API is a promise-based interface for fetching resources by making HTTP requests to servers from web browsers
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
// Simple explanation
https://www.topcoder.com/thrive/articles/fetch-api-javascript-how-to-make-get-and-post-requests
// Test API demo data
https://jsonplaceholder.typicode.com/
fetch('url') // this construction is returning a apromise
// example
fetch('url') // The fetch() method has two parameters. URL and init, if withou Init param then will be a classical Get query
.then(response => { // It then returns a promise that resolves into a response object.
//handle response
console.log(response);
})
.then(data => {
//handle data
console.log(data);
})
.catch(error => {
console.log(error);
});
// example with Init params (for server POST query sendind)
fetch('url', {
method: 'POST',
headers: {
Accept: 'application.json',
'Content-Type': 'application/json'
},
body: body,
Cache: 'default'
})
/*** --- Pattern of projecting --- ***/
// Immediately-Invoked Function Expressio - IIFE
// anonymous auto calling functio
// https://en.wikipedia.org/wiki/Immediately_invoked_function_expression
// https://habr.com/ru/company/ruvds/blog/419997/
(function () { /* ... */ }());
(() => { /* ... */ })(); // With ES6 arrow functions (though parentheses only allowed on outside)
(function() {
console.log('WORK');
}())
// Объявим модуль
const Module = (function () {
return {
myMethod: function () {
console.log('myMethod has been called.');
}
};
})();
// Вызовем функцию как метод объекта
Module.myMethod();
/* --- Miscellaneous --- */
//-> get query string
https://flaviocopes.com/urlsearchparams/
const params = new URLSearchParams(window.location.search)
for (const param of params) {
console.log(param)
}
// JavaScript Timing Events, work timing, work setTimeout
setTimeout(){
}
// transmit params to funcs in setTimeout
setTimeout(yourFunctionReference, 4000, param1, param2, paramN);
/* --- Current Screen Size --- */
var w = window.innerWidth;
var h = window.innerHeight;
/* --- about JS in deep mode --- */
// In JavaScript, classes are not exactly the same as constructor functions, but they can be seen as a syntactic sugar over constructor functions and prototype-based inheritance.
// Class
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person = new Person("John");
person.sayHello();
// Equivalent constructor function
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`Hello, my name is ${this.name}`);
};
var person = new Person("John");
person.sayHello();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment