This site can mainly be useful for beginner front-end developers as well as those just learning javascript and typescript. Information is collected on the site from various sources, all the information that is presented is placed in the open resources of the Internet, which is available to any user.
JavaScript
Array
[1, 2, 3].length; // 3
[1, 2, 3].push(4); //? [1,2,3,4]
[1, 2, 3].unshift(0); //? [0,1,2,3]
[1, 2, 3].pop(); //? [1,2]
[1, 2, 3].shift(); //? [2,3]
[1, 2, 3].at(2); //? 3
[1, 2, 3].indexOf(3); //? 2
[1, 2, 3].includes(3); //? true
[1, 2, 3].map((num) => Math.pow(num, 2)); //? [1, 4, 9]
[1, 2, 3].filter((num) => num % 2); //? [1,3]
[1, 2, 3].every((num) => num > 1); //? false
[1, 2, 3].some((num) => num == 3); //? true
[1, 2, 3].fill(10); //? [10,10,10]
[1, 2, 3].reduce((acc, num) => acc + num, 0); //? 6
[1, 2, 3].concat([4, 5]); //? [1,2,3,4,5]
[1, 2, 3].reverse(); //? [3,2,1]
[2, 1, 3].sort(); //? [1,2,3]
[1, 2, 3].join('-'); //? 1-2-3
[1, 2, [3]].flat(); //? [1,2,3]
[1, 2, 3].find((num, i) => i === 1); //? 2
[1, 2, 3].findIndex((num) => num === 2); //? 1
[1, 2, 3].toString(); //? 1,2,3
[1, 2, 3].slice(1, 3); //? [2,3]
[1, 4].splice(1, 0, 2, 3); //? [1,2,3,4]
Array.isArray("[1,2,3]"); //? false
Array.from("123"); //? '1', '2', '3']
----------------------------------------------------
CLONE array
const clone = arr => arr.slice(0)
const clone = arr => [...arr]
const clone = arr => arr.map(x => x)
const clone = arr => arr.slice(0)
const clone = arr => JSON.parse(JSON.stringify(arr))
const clone = arr => arr.concat([])
-----------------------------------------
String
"Hello".charAt(4)
"Hello".concat("", "world")
"Hello".startsWith("H")
"Hello".endsWith("o")
"Hello".includes("x")
"Hello".indexOf("l")
"Hello".lastIndexOf("l")
"Hello".match([A-Z/g])
"Hello".padStart(6, "?")
"Hello".padEnd(6, "?")
"Hello".repeat(3)
"Hello".replace("llo", "y")
"Hello".search("e")
"Hello".slice(1, 3)
"Hello".split("")
"Hello".substring(2, 4)
"Hello".toLowerCase()
"Hello".toUpperCase()
" Hello ".trim()
" Hello ".trimStart()
" Hello ".trimEnd()
Object
// Object Methods Cheat Sheet
// 1. Object.create(proto, [propertiesObject])
// Creates a new object with the specified prototype object and optional properties.
const obj1 = Object.create(null);
// 2. Object.keys(obj)
// Returns an array of a given object's own enumerable property names.
const keys = Object.keys(obj);
// 3. Object.values(obj)
// Returns an array of a given object's own enumerable property values.
const values = Object.values(obj);
// 4. Object.entries(obj)
// Returns an array of a given object's own enumerable property [key, value] pairs.
const entries = Object.entries(obj);
// 5. Object.assign(target, ...sources)
// Copies the values of all enumerable properties from one or more source objects to a target object.
const target = {};
Object.assign(target, obj1, obj2);
// 6. Object.hasOwnProperty(prop)
// Returns a boolean indicating whether the object has the specified property as its own property (not inherited).
const hasProp = obj.hasOwnProperty("property");
// 7. Object.is(obj1, obj2)
// Determines whether two values are the same value.
const isSame = Object.is(obj1, obj2);
// 8. Object.freeze(obj)
// Freezes an object: other code cannot delete or modify its properties.
const frozenObj = Object.freeze(obj);
// 9. Object.seal(obj)
// Seals an object: other code cannot add/delete properties, but can modify existing properties.
const sealedObj = Object.seal(obj);
// 10. Object.getPrototypeOf(obj)
// Returns the prototype of the specified object.
const proto = Object.getPrototypeOf(obj);
// 11. Object.setPrototypeOf(obj, proto)
// Sets the prototype of the specified object.
Object.setPrototypeOf(obj, proto);
// 12. Object.defineProperty(obj, prop, descriptor)
// Adds the named property described by a given descriptor to an object.
Object.defineProperty(obj, "property", {
value: "value",
writable: false,
enumerable: true,
configurable: true,
});
// 13. Object.getOwnPropertyDescriptor(obj, prop)
// Returns a property descriptor for a named property on an object.
const descriptor = Object.getOwnPropertyDescriptor(obj, "property");
// 14. Object.getOwnPropertyNames(obj)
// Returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
const propertyNames = Object.getOwnPropertyNames(obj);
// 15. Object.getOwnPropertySymbols(obj)
// Returns an array of all symbol properties found directly in a given object.
const symbols = Object.getOwnPropertySymbols(obj);
// 16. Object.toString()
// Returns a string representation of the object.
const str = Object.toString();
// Object Methods Cheat Sheet (Continued)
// 17. Object.hasOwnProperty(prop)
// Returns a boolean indicating whether the object has the specified property as its own property (not inherited).
const hasProp = obj.hasOwnProperty("property");
// 18. Object.isExtensible(obj)
// Determines if an object is extensible (i.e., if new properties can be added to it).
const isExtensible = Object.isExtensible(obj);
// 19. Object.preventExtensions(obj)
// Prevents any extensions of an object (i.e., prevents new properties from being added to it).
Object.preventExtensions(obj);
// 20. Object.isSealed(obj)
// Determines if an object is sealed (i.e., if it is neither extensible nor properties can be deleted).
const isSealed = Object.isSealed(obj);
// 21. Object.isFrozen(obj)
// Determines if an object is frozen (i.e., if it is neither extensible, properties can be deleted, nor properties can be modified).
const isFrozen = Object.isFrozen(obj);
// 22. Object.keys(obj)
// Returns an array of a given object's own enumerable property names.
const keys = Object.keys(obj);
// 23. Object.values(obj)
// Returns an array of a given object's own enumerable property values.
const values = Object.values(obj);
// 24. Object.entries(obj)
// Returns an array of a given object's own enumerable property [key, value] pairs.
const entries = Object.entries(obj);
// 25. Object.fromEntries(entries)
// Transforms a list of key-value pairs into an object.
const transformedObj = Object.fromEntries(entries);
// 26. Object.prototype.hasOwnProperty(prop)
// Returns a boolean indicating whether the object or its prototype chain has the specified property.
const hasPropInChain = obj.hasOwnProperty("property");
// 27. Object.prototype.toString()
// Returns a string representation of the object.
const str = obj.toString();
// 28. Object.prototype.valueOf()
// Returns the primitive value of the object.
const value = obj.valueOf();
// 29. Object.prototype.isPrototypeOf(obj)
// Checks if an object exists in another object's prototype chain.
const isProto = prototypeObj.isPrototypeOf(obj);
// 30. Object.prototype.propertyIsEnumerable(prop)
// Returns a boolean indicating whether the specified property is enumerable.
const isEnumerable = obj.propertyIsEnumerable("property");
// Object Methods Cheat Sheet (Continued)
// 31. Object.getOwnPropertyDescriptors(obj)
// Returns an object containing all own property descriptors of an object.
const descriptors = Object.getOwnPropertyDescriptors(obj);
// 32. Object.isPrototypeOf(obj)
// Checks if an object is in the prototype chain of another object.
const isProto = Object.isPrototypeOf(protoObj);
// 33. Object.values(obj)
// Returns an array of a given object's own enumerable property values.
const values = Object.values(obj);
// 34. Object.entries(obj)
// Returns an array of a given object's own enumerable property [key, value] pairs.
const entries = Object.entries(obj);
// 35. Object.keys(obj)
// Returns an array of a given object's own enumerable property names.
const keys = Object.keys(obj);
// 36. Object.defineProperties(obj, descriptors)
// Defines new or modifies existing properties directly on an object, returning the object.
Object.defineProperties(obj, {
property1: {
value: "value1",
writable: true,
enumerable: true,
configurable: true,
},
property2: {
value: "value2",
writable: false,
enumerable: true,
configurable: true,
},
});
// 37. Object.getOwnPropertyNames(obj)
// Returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
const propertyNames = Object.getOwnPropertyNames(obj);
// 38. Object.getOwnPropertySymbols(obj)
// Returns an array of all symbol properties found directly in a given object.
const symbols = Object.getOwnPropertySymbols(obj);
// 39. Object.toString()
// Returns a string representation of the object.
const str = Object.toString();
// 40. Object.valueOf()
// Returns the primitive value of the object.
const value = obj.valueOf();
Number
isNaN(12.4); // false
isFinite(12.4); // true
Number.isInteger (12.4); // false
Number.isSafeInteger(12.4); // false
parseFloat(12.4); // 12.4
parseInt(12.4); // 12
const num = 12.4;
num.toExponential(); // "1.24e+1"
num.toFixed(); // 12
num.toPrecision(3); // "12.4"
num.toString(10); // "12.4"
num.valueOf(); // 12.4
let today = new Date(); today.toLocaleString('en-IN'); // "1/9/2022, 11:03:17 am"
Most used codes
console.log("Hello, world!");
alert("Hello, world!");
let name = prompt("What is your name?");
let number = parseInt("42");
let number = parseFloat("3.14");
let str = String(42);
let num = Number("42");
typeof "Hello"; // returns "string"
Array.isArray([1, 2, 3]); // returns true
let strLength = "Hello".length; // returns 5
let uppercaseStr = "hello".toUpperCase(); // returns "HELLO"
let lowercaseStr = "HELLO".toLowerCase(); // returns "hello"
let fullName = "John".concat(" ", "Doe"); // returns "John Doe"
let str = ["Hello", "world"].join(" "); // returns "Hello world"
// -----------------------------------
let arr = [1, 2, 3];
arr.push(4);
// -----------------------------------
let arr = [1, 2, 3];
let lastElement = arr.pop(); // returns 3
// -----------------------------------
let arr = [1, 2, 3];
let firstElement = arr.shift(); // returns 1
// -----------------------------------
let arr = [2, 3, 4];
arr.unshift(1);
// -----------------------------------
let arr = [1, 2, 3, 4, 5];
let subArray = arr.slice(2, 4); // returns [3, 4]
// -----------------------------------
let arr = [1, 2, 3, 4, 5];
arr.splice(2, 1, "hello");
// -----------------------------------
let arr = [1, 2, 3, 4, 5];
let index = arr;
// ---------- STRING METHODS---------
// -----------------------------------
let str = "Hello, world!";
// Length of the string
let length = str.length;
console.log(length); // Output: 13
// Convert to uppercase
let uppercase = str.toUpperCase();
console.log(uppercase); // Output: HELLO, WORLD!
// Convert to lowercase
let lowercase = str.toLowerCase();
console.log(lowercase); // Output: hello, world!
// Check if a string includes a substring
let includesSubstring = str.includes("world");
console.log(includesSubstring); // Output: true
// Extract a substring
let substring = str.substring(7, 12);
console.log(substring); // Output: world
// Split a string into an array of substrings
let splitted = str.split(", ");
console.log(splitted); // Output: ['Hello', 'world!']
// Trim leading and trailing whitespace
let trimmed = str.trim();
console.log(trimmed); // Output: Hello, world!
// Replace a substring with another string
let replaced = str.replace("world", "JavaScript");
console.log(replaced); // Output: Hello, JavaScript!
// Concatenate strings
let str1 = "Hello";
let str2 = "JavaScript";
let concatenated = str1.concat(", ", str2, "!");
console.log(concatenated); // Output: Hello, JavaScript!
let str = "Hello, world!";
// Check if a string starts with a specific substring
let startsWith = str.startsWith("Hello");
console.log(startsWith); // Output: true
// Check if a string ends with a specific substring
let endsWith = str.endsWith("world!");
console.log(endsWith); // Output: true
// Find the index of a substring
let indexOfSubstring = str.indexOf("world");
console.log(indexOfSubstring); // Output: 7
// Find the last index of a substring
let lastIndexOfSubstring = str.lastIndexOf("o");
console.log(lastIndexOfSubstring); // Output: 8
// Repeat a string a certain number of times
let repeated = str.repeat(3);
console.log(repeated); // Output: Hello, world!Hello, world!Hello, world!
// Extract a character at a specific index
let charAt = str.charAt(4);
console.log(charAt); // Output: o
// Get the Unicode value of a character at a specific index
let charCode = str.charCodeAt(4);
console.log(charCode); // Output: 111
// Check if a string contains only numeric characters
let isNumeric = str.match(/^\d+$/);
console.log(isNumeric); // Output: null (if the string is not numeric)
// Split a string into an array of characters
let characters = str.split("");
console.log(characters); // Output:
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']
// Reverse a string
let reversed = str.split("").reverse().join("");
console.log(reversed); // Output: !dlrow ,olleH
// Extract a substring using regular expressions
let regexSubstring = str.match(/world/g);
console.log(regexSubstring); // Output: ['world']
let str = "Hello, world!";
// Check if a string is empty
let isEmpty = str.length === 0;
console.log(isEmpty); // Output: false
// Check if a string is a palindrome
let isPalindrome = str === str.split("").reverse().join("");
console.log(isPalindrome); // Output: false
// Extract a substring using substr
let substr = str.substr(7, 5);
console.log(substr); // Output: world
// Pad a string with a specified character
let padded = str.padStart(20, "*");
console.log(padded); // Output: ****Hello, world!
// Extract the first character of a string
let firstChar = str.charAt(0);
console.log(firstChar); // Output: H
// Extract the last character of a string
let lastChar = str.charAt(str.length - 1);
console.log(lastChar); // Output: !
// Convert a string to an array of words
let words = str.split(" ");
console.log(words); // Output: ['Hello,', 'world!']
// Replace multiple occurrences of a substring with another string
let replacedAll = str.replaceAll("o", "*");
console.log(replacedAll); // Output: Hell*, w*rld!
// Check if a string matches a regular expression
let matchesRegex = str.match(/Hello/g);
console.log(matchesRegex); // Output: ['Hello']
// Remove leading and trailing whitespace
let trimmedWhitespace = str.trim();
console.log(trimmedWhitespace); // Output: Hello, world!
let str = "Hello, world!";
// Convert the first character to uppercase
let capitalized = str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalized); // Output: Hello, world!
// Check if a string contains only alphabetic characters
let isAlpha = /^[a-zA-Z]+$/.test(str);
console.log(isAlpha); // Output: false
// Extract a substring between two indices
let substringBetweenIndices = str.substring(7, 12);
console.log(substringBetweenIndices); // Output: world
// Check if a string is a valid email address
let isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
console.log(isValidEmail); // Output: false
// Convert a string to an array of characters using Array.from
let charactersArray = Array.from(str);
console.log(charactersArray); // Output:
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']
// Remove a specific substring from a string
let removedSubstring = str.replace("Hello, ", "");
console.log(removedSubstring); // Output: world!
// Convert a string to title case
let titleCase = str.replace(/\w\S*/g, function (text) {
return text.charAt(0).toUpperCase() + text.substr(1).toLowerCase();
});
console.log(titleCase); // Output: Hello, World!
// Split a string into an array of words and count the number of words
let wordsArray = str.split(" ");
let wordCount = wordsArray.length;
console.log(wordCount); // Output: 2
// Reverse the words in a string
let reversedWords = wordsArray.reverse().join(" ");
console.log(reversedWords); // Output: world! Hello,
// Convert a string to a slug (lowercase, hyphen-separated words)
let slug = str.toLowerCase().replace(/\s+/g, "-");
console.log(slug); // Output: hello,-world!
let str = "Hello, world!";
// Convert a string to an array of words and capitalize each word
let capitalizedWords = str
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
console.log(capitalizedWords); // Output: Hello, World!
// Check if a string contains only numeric characters
let isNumeric = /^[0-9]+$/.test(str);
console.log(isNumeric); // Output: false
// Count the occurrences of a substring in a string
let substringCount = str.split("o").length - 1;
console.log(substringCount); // Output: 2
// Remove leading whitespace from a string
let trimmedLeft = str.trimStart();
console.log(trimmedLeft); // Output: Hello, world!
// Remove trailing whitespace from a string
let trimmedRight = str.trimEnd();
console.log(trimmedRight); // Output: Hello, world!
// Repeat a string with a separator in between
let repeatedWithSeparator = str.repeat(3).split("").join("-");
console.log(repeatedWithSeparator); //
Output: H-e-l-l-o-,- -w-o-r-l-d-!-H-e-l-l-o-,
- -w-o-r-l-d-!-H-e-l-l-o-,- -w-o-r-l-d-!
// Check if a string is a valid URL
let isValidURL = /^(http|https):\/\/([\w.]+\/?)\S*$/.test(str);
console.log(isValidURL); // Output: false
// Replace multiple substrings using a map of replacements
let replacements = new Map([
["Hello", "Hola"],
["world", "mundo"],
]);
let replacedMultiple = str.replace(/Hello|world/g, (match) =>
replacements.get(match)
);
console.log(replacedMultiple); // Output: Hola, mundo!
// Split a string into an array of lines
let linesArray = str.split(/\r?\n/);
console.log(linesArray); // Output: ['Hello, world!']
// Convert a string to kebab case (lowercase, hyphen-separated words)
let kebabCase = str.toLowerCase().replace(/\s+/g, "-");
console.log(kebabCase); // Output: hello,-world-
let str = "Hello, world!";
// Convert a string to camel case
let camelCase = str
.replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) => {
return index === 0 ? letter.toLowerCase() : letter.toUpperCase();
})
.replace(/\s+/g, "");
console.log(camelCase); // Output: helloWorld!
// Check if a string is a valid date in the format "YYYY-MM-DD"
let isValidDate = /^\d{4}-\d{2}-\d{2}$/.test(str);
console.log(isValidDate); // Output: false
// Get the Unicode value of a character at a specific index (codePointAt)
let unicodeValue = str.codePointAt(4);
console.log(unicodeValue); // Output: 111
// Repeat a string a certain number of times with a separator in between
let repeatedWithSeparator = str.repeat(3).split("").join("-");
console.log(repeatedWithSeparator); //
Output: H-e-l-l-o-,- -w-o-r-l-d-!-H-e-l-l-o-,
- -w-o-r-l-d-!-H-e-l-l-o-,- -w-o-r-l-d-!
// Check if a string contains only alphanumeric characters
let isAlphanumeric = /^[a-zA-Z0-9]+$/.test(str);
console.log(isAlphanumeric); // Output: false
// Remove all occurrences of a substring from a string
let removedAll = str.replace(/o/g, "");
console.log(removedAll); // Output: Hell, wrld!
// Convert a string to an array of characters using spread operator
let charactersArray = [...str];
console.log(charactersArray); // Output:
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']
// Check if a string contains only whitespace characters
let isWhitespace = /^\s+$/.test(str);
console.log(isWhitespace); // Output: false
// Check if a string is a valid JSON
let isValidJSON = (str) => {
try {
JSON.parse(str);
return true;
} catch (error) {
return false;
}
};
console.log(isValidJSON(str)); // Output: false
// ------------- number methods-----------
let num = 42;
// Convert a number to a string
let numToString = num.toString();
console.log(numToString); // Output: "42"
// Convert a string to a number
let stringToNum = parseInt("42");
console.log(stringToNum); // Output: 42
// Get the number of decimal places
let decimalPlaces = num.toString().split(".")[1]?.length || 0;
console.log(decimalPlaces); // Output: 0
// Round a number to a specified number of decimal places
let rounded = num.toFixed(2);
console.log(rounded); // Output: "42.00"
// Convert a number to exponential notation
let exponential = num.toExponential(2);
console.log(exponential); // Output: "4.20e+1"
// Check if a number is an integer
let isInteger = Number.isInteger(num);
console.log(isInteger); // Output: true
// Get the absolute value of a number
let absoluteValue = Math.abs(num);
console.log(absoluteValue); // Output: 42
// Check if a number is NaN (Not a Number)
let isNan = Number.isNaN(num);
console.log(isNan); // Output: false
// Get the maximum value among a list of numbers
let max = Math.max(10, 20, 30, 40, 50);
console.log(max); // Output: 50
// Get the minimum value among a list of numbers
let min = Math.min(10, 20, 30, 40, 50);
console.log(min); // Output: 10
// Generate a random number between a specified range
let random = Math.random() * (10 - 5) + 5;
console.log(random); // Output: a random number between 5 and 10
// Check if a number is finite
let isFiniteNum = isFinite(num);
console.log(isFiniteNum); // Output: true
let num = 42;
// Check if a number is positive infinity
let isPositiveInfinity =
Number.isFinite(num) && num === Number.POSITIVE_INFINITY;
console.log(isPositiveInfinity); // Output: false
// Check if a number is negative infinity
let isNegativeInfinity =
Number.isFinite(num) && num === Number.NEGATIVE_INFINITY;
console.log(isNegativeInfinity); // Output: false
// Check if a number is a safe integer
let isSafeInteger = Number.isSafeInteger(num);
console.log(isSafeInteger); // Output: true
// Convert a number to a fixed number of digits
let fixedDigits = num.toFixed(5);
console.log(fixedDigits); // Output: "42.00000"
// Get the square root of a number
let squareRoot = Math.sqrt(num);
console.log(squareRoot); // Output: 6.48074069840786
// Get the cube root of a number
let cubeRoot = Math.cbrt(num);
console.log(cubeRoot); // Output: 3.476026644159999
// Get the value of a number rounded to the nearest integer
let roundedNearestInt = Math.round(num);
console.log(roundedNearestInt); // Output: 42
// Get the value of a number rounded up to the nearest integer
let roundedUp = Math.ceil(num);
console.log(roundedUp); // Output: 42
// Get the value of a number rounded down to the nearest integer
let roundedDown = Math.floor(num);
console.log(roundedDown); // Output: 42
// Get the value of a number raised to a power
let power = Math.pow(num, 2);
console.log(power); // Output: 1764
// Generate a random integer between a specified range
let randomInteger = Math.floor(Math.random() * (10 - 5 + 1)) + 5;
console.log(randomInteger); // Output: a random integer between 5 and 10
// Check if a number is divisible by another number
let isDivisibleBy = num % 5 === 0;
console.log(isDivisibleBy); // Output: true
let num = 42;
// Get the value of a number rounded to a specified number of decimal places
let roundedDecimal = parseFloat(num.toFixed(3));
console.log(roundedDecimal); // Output: 42.000
// Get the value of a number as a binary string
let binaryString = num.toString(2);
console.log(binaryString); // Output: "101010"
// Get the value of a number as an octal string
let octalString = num.toString(8);
console.log(octalString); // Output: "52"
// Get the value of a number as a hexadecimal string
let hexString = num.toString(16);
console.log(hexString); // Output: "2a"
// Get the value of a number as a percentage string
let percentageString = (num * 100).toFixed(2) + "%";
console.log(percentageString); // Output: "4200.00%"
// Check if a number is within a specific range
let isInRange = num >= 0 && num <= 100;
console.log(isInRange); // Output: true
// Get the absolute difference between two numbers
let diff = Math.abs(10 - 20);
console.log(diff); // Output: 10
// Get the smallest integer greater than or equal to a number
let ceil = Math.ceil(num);
console.log(ceil); // Output: 42
// Get the largest integer less than or equal to a number
let floor = Math.floor(num);
console.log(floor); // Output: 42
// Convert degrees to radians
let degrees = 90;
let radians = (degrees * Math.PI) / 180;
console.log(radians); // Output: 1.5707963267948966
// Get the maximum value among an array of numbers
let max = Math.max(10, 20, 30, 40, 50);
console.log(max); // Output: 50
// Get the minimum value among an array of numbers
let min = Math.min(10, 20, 30, 40, 50);
console.log(min); // Output: 10
// Calculate the sum of an array of numbers
let sum = [1, 2, 3, 4, 5].reduce((acc, val) => acc + val, 0);
console.log(sum); // Output: 15
// Calculate the average of an array of numbers
let average = sum / [1, 2, 3, 4, 5].length;
console.log(average); // Output: 3
let num = 42;
// Check if a number is divisible by another number
let isDivisibleBy = num % 5 === 0;
console.log(isDivisibleBy); // Output: true
// Get the value of a number rounded to the nearest multiple of another number
let nearestMultiple = Math.round(num / 10) * 10;
console.log(nearestMultiple); // Output: 40
// Convert a number to a string with a specific base (radix)
let binaryString = num.toString(2);
console.log(binaryString); // Output: "101010"
// Get the number of digits in a number
let numDigits = Math.floor(Math.log10(Math.abs(num))) + 1;
console.log(numDigits); // Output: 2
// Check if a number is a prime number
let isPrime = isPrimeNumber(num);
console.log(isPrime); // Output: true
function isPrimeNumber(number) {
if (number < 2) {
return false;
}
for (let i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
// Get the factorial of a number
let factorial = getFactorial(num);
console.log(factorial); // Output:
1405006117752879898543142606244511569936384000000000
function getFactorial(number) {
if (number === 0 || number === 1) {
return 1;
}
let result = 1;
for (let i = 2; i <= number; i++) {
result *= i;
}
return result;
}
// Convert degrees to radians
let degrees = 90;
let radians = degrees * (Math.PI / 180);
console.log(radians); // Output: 1.5707963267948966
// Calculate the power of a number
let power = Math.pow(num, 3);
console.log(power); // Output: 74088
// Check if a number is within a specific range
let isInRange = num >= 0 && num <= 100;
console.log(isInRange); // Output: true
// Calculate the sum of an array of numbers using reduce
let sum = [1, 2, 3, 4, 5].reduce((acc, val) => acc + val, 0);
console.log(sum); // Output: 15
// Calculate the average of an array of numbers
let average = sum / [1, 2, 3, 4, 5].length;
console.log(average); // Output: 3
// -------------Boolean-------------
let bool = true;
// Convert a value to a Boolean
let convertedBool = Boolean(0);
console.log(convertedBool); // Output: false
// Negate a Boolean value
let negatedBool = !bool;
console.log(negatedBool); // Output: false
// Check if a value is truthy (not false, 0, '', null, undefined, NaN)
let isTruthy = !!0;
console.log(isTruthy); // Output: false
// Check if a value is falsy (false, 0, '', null, undefined, NaN)
let isFalsy = !"";
console.log(isFalsy); // Output: true
// Perform logical AND operation
let resultAnd = true && false;
console.log(resultAnd); // Output: false
// Perform logical OR operation
let resultOr = true || false;
console.log(resultOr); // Output: true
// Perform logical NOT operation
let resultNot = !true;
console.log(resultNot); // Output: false
// Check if a value is equal to another value (strict equality)
let isEqual = 5 === 5;
console.log(isEqual); // Output: true
// Check if a value is not equal to another value (strict inequality)
let isNotEqual = 5 !== 10;
console.log(isNotEqual); // Output: true
let bool = true;
// Check if a value is equal to another value (loose equality)
let isEqualLoose = "5" == 5;
console.log(isEqualLoose); // Output: true
// Check if a value is not equal to another value (loose inequality)
let isNotEqualLoose = "5" != 10;
console.log(isNotEqualLoose); // Output: true
// Check if a value is greater than another value
let isGreater = 10 > 5;
console.log(isGreater); // Output: true
// Check if a value is less than another value
let isLess = 5 < 10;
console.log(isLess); // Output: true
// Check if a value is greater than or equal to another value
let isGreaterOrEqual = 10 >= 10;
console.log(isGreaterOrEqual); // Output: true
// Check if a value is less than or equal to another value
let isLessOrEqual = 5 <= 10;
console.log(isLessOrEqual); // Output: true
// Perform logical XOR (exclusive OR) operation
let resultXor = true ^ false;
console.log(resultXor); // Output: true
// Perform logical NAND operation
let resultNand = !(true && true);
console.log(resultNand); // Output: false
// Perform logical NOR operation
let resultNor = !(true || true);
console.log(resultNor); // Output: false
// Check if a value is an instance of a specific type or class
let isInstanceOf = "Hello" instanceof String;
console.log(isInstanceOf); // Output: false
let bool = true;
// Check if a value is strictly greater than another value
let isStrictlyGreater = 10 > 5;
console.log(isStrictlyGreater); // Output: true
// Check if a value is strictly less than another value
let isStrictlyLess = 5 < 10;
console.log(isStrictlyLess); // Output: true
// Check if a value is strictly greater than or equal to another value
let isStrictlyGreaterOrEqual = 10 >= 10;
console.log(isStrictlyGreaterOrEqual); // Output: true
// Check if a value is strictly less than or equal to another value
let isStrictlyLessOrEqual = 5 <= 10;
console.log(isStrictlyLessOrEqual); // Output: true
// Check if a value is truthy using double negation
let isTruthy = !!"Hello";
console.log(isTruthy); // Output: true
// Check if a value is falsy using double negation
let isFalsy = !!null;
console.log(isFalsy); // Output: false
// Check if all values in an array are truthy
let areAllTruthy = [true, 1, "Hello"].every(Boolean);
console.log(areAllTruthy); // Output: true
// Check if any value in an array is truthy
let isAnyTruthy = [false, 0, "Hello"].some(Boolean);
console.log(isAnyTruthy); // Output: true
// Check if a value is NaN (Not a Number)
let isNaNValue = isNaN("Hello");
console.log(isNaNValue); // Output: true
// Check if a value is finite (not NaN, Infinity, or -Infinity)
let isFiniteValue = isFinite(42);
console.log(isFiniteValue); // Output: true
// -------------Objects-------------
let person = {
name: "John",
age: 30,
occupation: "Developer",
};
// Get the keys of an object
let keys = Object.keys(person);
console.log(keys); // Output: ["name", "age", "occupation"]
// Get the values of an object
let values = Object.values(person);
console.log(values); // Output: ["John", 30, "Developer"]
// Get the entries of an object
let entries = Object.entries(person);
console.log(entries);
// Output: [["name", "John"], ["age", 30], ["occupation", "Developer"]]
// Check if an object has a specific property
let hasProperty = person.hasOwnProperty("age");
console.log(hasProperty); // Output: true
// Merge two or more objects into a new object
let otherInfo = {
gender: "Male",
city: "New York",
};
let mergedObject = { ...person, ...otherInfo };
console.log(mergedObject);
// Output: { name: "John", age: 30, occupation:
"Developer", gender: "Male", city: "New York" }
// Clone an object (shallow copy)
let clonedObject = { ...person };
console.log(clonedObject === person); // Output: false
// Access a property value using a dynamic key
let propertyName = "age";
let propertyValue = person[propertyName];
console.log(propertyValue); // Output: 30
// Delete a property from an object
delete person.occupation;
console.log(person); // Output: { name: "John", age: 30 }
// Check if an object is empty
let isEmpty = Object.keys(person).length === 0;
console.log(isEmpty); // Output: false
// Get the number of properties in an object
let numProperties = Object.keys(person).length;
console.log(numProperties); // Output: 2
let person = {
name: "John",
age: 30,
occupation: "Developer",
};
// Check if an object has a specific value
let hasValue = Object.values(person).includes("Developer");
console.log(hasValue); // Output: true
// Check if an object is an instance of a specific type or class
let isInstanceOf = person instanceof Object;
console.log(isInstanceOf); // Output: true
// Get a shallow copy of an object with selected properties
let selectedProperties = ["name", "age"];
let selectedObject = Object.fromEntries(
Object.entries(person).filter(([key]) => selectedProperties.includes(key))
);
console.log(selectedObject); // Output: { name: "John", age: 30 }
// Determine if two objects have the same property values
let otherPerson = {
name: "John",
age: 30,
occupation: "Developer",
};
let hasSameValues = JSON.stringify(person) === JSON.stringify(otherPerson);
console.log(hasSameValues); // Output: true
// Get the prototype of an object
let prototype = Object.getPrototypeOf(person);
console.log(prototype); // Output: {}
// Set the prototype of an object
let newPrototype = { country: "USA" };
Object.setPrototypeOf(person, newPrototype);
console.log(person); // Output: { name: "John", age: 30, occupation: "Developer" }
// Iterate over the properties of an object
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// Output:
// name: John
// age: 30
// occupation: Developer
let person = {
name: "John",
age: 30,
occupation: "Developer",
};
// Check if an object has a specific property, including inherited properties
let hasProperty = "name" in person;
console.log(hasProperty); // Output: true
// Get the descriptor of a property in an object
let propertyDescriptor = Object.getOwnPropertyDescriptor(person, "name");
console.log(propertyDescriptor);
// Output: { value: "John", writable: true, enumerable: true, configurable: true }
// Define or modify a property descriptor of an object
Object.defineProperty(person, "name", {
value: "Jane",
writable: false,
enumerable: false,
configurable: false,
});
console.log(person.name); // Output: "Jane"
// Get the prototype of an object
let prototype = Object.getPrototypeOf(person);
console.log(prototype); // Output: {}
// Set the prototype of an object
let newPrototype = { country: "USA" };
Object.setPrototypeOf(person, newPrototype);
console.log(person); // Output: { name: "Jane", age: 30, occupation: "Developer" }
// Get all property names of an object, including inherited properties
let allProperties = [];
let currentObject = person;
while (currentObject !== null) {
allProperties.push(...Object.getOwnPropertyNames(currentObject));
currentObject = Object.getPrototypeOf(currentObject);
}
console.log(allProperties); // Output: ["name", "age", "occupation", "country"]
// Freeze an object to make it immutable
Object.freeze(person);
person.name = "Bob";
console.log(person.name); // Output: "Jane"
// Seal an object to prevent adding or deleting properties,
but allow modifying existing ones
Object.seal(person);
delete person.age;
console.log(person.age); // Output: 30
// Prevent extensions of an object, disallowing adding new properties
Object.preventExtensions(person);
person.gender = "Male";
console.log(person.gender); // Output: undefined
// ------------ Array----------
// push: Adds one or more elements to the end of an array.
// pop: Removes the last element from an array and returns it.
// shift: Removes the first element from an array and returns it.
// unshift: Adds one or more elements to the beginning of an array.
// concat: Combines two or more arrays and returns a new array.
// slice: Extracts a portion of an array into a new array.
// splice: Changes the contents of an array by removing, replacing, or adding elements.
// indexOf: Returns the first index at which a specified element is found in an array.
// lastIndexOf: Returns the last index at which a specified element is found in an array.
// includes: Determines whether an array includes a certain element, returning true or false.
// join: Joins all elements of an array into a string.
// reverse: Reverses the order of the elements in an array.
// sort: Sorts the elements of an array in place.
// filter: Creates a new array with all elements that pass a test.
// map: Creates a new array by applying a function to each element of an existing array.
// reduce: Applies a function to reduce the elements of an array to a single value.
// forEach: Executes a provided function once for each array element.
// some: Tests whether at least one element in the array passes a test.
// every: Tests whether all elements in the array pass a test.
// find: Returns the first element in the array that satisfies a provided testing function.
// findIndex: Returns the index of the first element in the array that satisfies a provided testing function.
// fill: Fills all or a portion of an array with a static value.
// isArray: Determines whether the passed value is an array.
// length: Property that returns the number of elements in an array.
let numbers = [1, 2, 3, 4, 5];
// push: Adds an element to the end of the array
numbers.push(6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
// pop: Removes the last element from the array
let poppedElement = numbers.pop();
console.log(poppedElement); // Output: 6
console.log(numbers); // Output: [1, 2, 3, 4, 5]
// shift: Removes the first element from the array
let shiftedElement = numbers.shift();
console.log(shiftedElement); // Output: 1
console.log(numbers); // Output: [2, 3, 4, 5]
// unshift: Adds an element to the beginning of the array
numbers.unshift(0);
console.log(numbers); // Output: [0, 2, 3, 4, 5]
// concat: Combines two arrays
let otherNumbers = [6, 7, 8];
let combinedArray = numbers.concat(otherNumbers);
console.log(combinedArray); // Output: [0, 2, 3, 4, 5, 6, 7, 8]
// slice: Extracts a portion of an array
let slicedArray = combinedArray.slice(2, 5);
console.log(slicedArray); // Output: [3, 4, 5]
// splice: Changes the contents of an array
let splicedArray = combinedArray.splice(2, 3, "a", "b", "c");
console.log(splicedArray); // Output: [3, 4, 5]
console.log(combinedArray); // Output: [0, 2, "a", "b", "c", 6, 7, 8]
// indexOf: Returns the index of an element in the array
let index = combinedArray.indexOf("c");
console.log(index); // Output: 4
// lastIndexOf: Returns the last index of an element in the array
let lastIndex = combinedArray.lastIndexOf("c");
console.log(lastIndex); // Output: 4
// includes: Checks if an element exists in the array
let includesElement = combinedArray.includes(6);
console.log(includesElement); // Output: true
// join: Joins array elements into a string
let joinedString = combinedArray.join("-");
console.log(joinedString); // Output: "0-2-a-b-c-6-7-8"
// reverse: Reverses the order of elements in the array
combinedArray.reverse();
console.log(combinedArray); // Output: [8, 7, 6, "c", "b", "a", 2, 0]
// sort: Sorts the array elements
combinedArray.sort();
console.log(combinedArray); // Output: [0, 2, 6, 7, 8, "a", "b", "c"]
// filter: Creates a new array with filtered elements
let filteredArray = combinedArray.filter(
(element) => typeof element === "number"
);
console.log(filteredArray); // Output: [0, 2, 6, 7, 8]
// map: Creates a new array by performing a function on each element
let mappedArray = combinedArray.map((element) => element * 2);
console.log(mappedArray); // Output: [0, 4, 12, 14, 16, NaN, NaN, NaN]
// reduce: Applies a function to reduce
let numbers = [1, 2, 3, 4, 5];
// forEach: Executes a provided function for each array element
numbers.forEach((element) => {
console.log(element);
});
// Output:
// 1
// 2
// 3
// 4
// 5
// some: Checks if at least one element satisfies a condition
let hasEvenNumber = numbers.some((element) => element % 2 === 0);
console.log(hasEvenNumber); // Output: true
// every: Checks if all elements satisfy a condition
let allEvenNumbers = numbers.every((element) => element % 2 === 0);
console.log(allEvenNumbers); // Output: false
// find: Returns the first element that satisfies a condition
let foundElement = numbers.find((element) => element > 3);
console.log(foundElement); // Output: 4
// findIndex: Returns the index of the first element that satisfies a condition
let foundIndex = numbers.findIndex((element) => element > 3);
console.log(foundIndex); // Output: 3
// fill: Fills the array with a static value
numbers.fill(0);
console.log(numbers); // Output: [0, 0, 0, 0, 0]
// isArray: Checks if a value is an array
let isArray = Array.isArray(numbers);
console.log(isArray); // Output: true
// length: Property that returns the number of elements in the array
let length = numbers.length;
console.log(length); // Output: 5
let numbers = [1, 2, 3, 4, 5];
// reduce: Applies a function to reduce the elements of an array to a single value
let sum = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
console.log(sum); // Output: 15
// flat: Creates a new array with all sub-array elements concatenated recursively
let nestedArray = [1, [2, [3, [4, [5]]]]];
let flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5]
// flatMap: Maps each element and flattens the result into a new array
let mappedAndFlattenedArray = numbers.flatMap((element) => [element * 2]);
console.log(mappedAndFlattenedArray); // Output: [2, 4, 6, 8, 10]
// from: Creates a new array from an array-like or iterable object
let arrayLikeObject = "Hello";
let newArray = Array.from(arrayLikeObject);
console.log(newArray); // Output: ["H", "e", "l", "l", "o"]
// reverse: Reverses the order of elements in the array
numbers.reverse();
console.log(numbers); // Output: [5, 4, 3, 2, 1]
// sort: Sorts the array elements
numbers.sort();
console.log(numbers); // Output: [1, 2, 3, 4, 5]
// slice: Extracts a portion of an array into a new array
let slicedArray = numbers.slice(2, 4);
console.log(slicedArray); // Output: [3, 4]
// filter: Creates a new array with all elements that pass a test
let filteredArray = numbers.filter((element) => element % 2 === 0);
console.log(filteredArray); // Output: [2, 4]
// map: Creates a new array by applying a function to each element
let mappedArray = numbers.map((element) => element * 2);
console.log(mappedArray); // Output: [2, 4, 6, 8, 10]
// find: Returns the first element that satisfies a condition
let foundElement = numbers.find((element) => element > 3);
console.log(foundElement); // Output: 4
// includes: Determines whether an array includes a certain element
let includesElement = numbers.includes(3);
console.log(includesElement); // Output: true
// indexOf: Returns the first index at which a specified element is found
let index = numbers.indexOf(2);
console.log(index); // Output: 1
// lastIndexOf: Returns the last index at which a specified element is found
let lastIndex = numbers.lastIndexOf(2);
console.log(lastIndex); // Output: 1
let numbers = [1, 2, 3, 4, 5];
// every: Checks if all elements satisfy a condition
let allGreaterThanZero = numbers.every((element) => element > 0);
console.log(allGreaterThanZero); // Output: true
// some: Checks if at least one element satisfies a condition
let someGreaterThanThree = numbers.some((element) => element > 3);
console.log(someGreaterThanThree); // Output: true
// findIndex: Returns the index of the first element that satisfies a condition
let index = numbers.findIndex((element) => element === 3);
console.log(index); // Output: 2
// fill: Fills the array with a static value from a start index to an end index
numbers.fill(0, 1, 3);
console.log(numbers); // Output: [1, 0, 0, 4, 5]
// join: Joins all elements of an array into a string
let joinedString = numbers.join("-");
console.log(joinedString); // Output: "1-0-0-4-5"
// reverse: Reverses the order of elements in the array
numbers.reverse();
console.log(numbers); // Output: [5, 4, 0, 0, 1]
// sort: Sorts the array elements
numbers.sort();
console.log(numbers); // Output: [0, 0, 1, 4, 5]
// isArray: Checks if a value is an array
let isArray = Array.isArray(numbers);
console.log(isArray); // Output: true
// length: Property that returns the number of elements in the array
let length = numbers.length;
console.log(length); // Output: 5
Example
// Variables and Data Types
let myNumber = 42;
const myString = "Hello, World!";
var myVar = "Old way of declaring variables";
// Conditional Statements
if (myNumber === 42) {
console.log("It's the answer to the Ultimate Question of Life,
the Universe, and Everything.");
} else {
console.log("It's not the answer.");
}
// Loops
for (let i = 0; i < 5; i++) {
console.log("Loop iteration: " + i);
}
// Arrays
const myArray = [1, 2, 3, 4, 5];
// Functions
function add(a, b) {
return a + b;
}
// Objects
const myObject = {
name: "John",
age: 30,
sayHello: function() {
console.log("Hello, " + this.name);
}
};
// Classes (ES6)
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log("Hello, " + this.name);
}
}
// Promises (Async/Await)
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
// Modules (ES6)
import {
myFunction
} from './myModule.js';
// Event Handling
document.getElementById("myButton").addEventListener("click", function() {
console.log("Button clicked!");
});
// Try-Catch for Error Handling
try {
// Code that might throw an error
} catch (error) {
console.error(error);
}
// Callbacks
function doSomething(callback) {
// Perform some task
callback();
}
doSomething(function() {
console.log("Callback executed!");
});
// And more...
// This example covers many JavaScript structures,
but there are more advanced concepts and libraries to explore
based on your specific needs.
Console
/* -----------------TABLE-------------- */
let info1 = [
["ABC"],
["Front-end dev"],
["JavaScript"]
];
console.table(info1);
/* -----------------TABLE END-------------- */
/* -----------------DIR-------------- */
let info2 = {
"name": "ABC",
"designation": "Frontend Engineer",
"social": "@javascript.js"
}
console.dir(info2)
/* -----------------DIR END-------------- */
/* -----------------COUNT-------------- */
console.count("Hey")
console.count("Hey")
console.count("Hey")
console.count("Hey")
/* -----------------COUNT END-------------- */
/* -----------------TIME-------------- */
console.time("Time")
let l = 0;
for (let i = 0; i < 5; i++) {
l += i
}
console.log("total", l);
console.timeEnd("Time")
/* -----------------TIME END-------------- */
Date
const today = new Date() //today 2020-08-09T61:40:51.0172
today.getDate() // 9
today.getDay() // 0 sunday
today.getMonth() // 7 (0 is jan)
today.getFullYear() // 2020
today.getYear() // 120 ?
today.getHours() // 11
today.getMinutes() // 40
today.getSeconds() //51
today.getMilliseconds() // 24
today.getTime() // 1596937251025
today.getTimezoneOffset() // -600
today.getUTCDate() // 9
today.getUTCDay() // 8
today.getUTCMonth() // 7
today.getUTCFullYear() // 2020
today.getUTCHours() // 1
today.getUTCMinutes() // 40
today.getUTCSeconds() // 51
today.getUTCMilliseconds() // 31
today.setDate(5)
today.setMonth(5)
today.setFullYear(2022)
today.setYear(100)
today.setHours(12)
today.setMinutes(5)
today.setSeconds(8)
today.setMilliseconds(45)
today.setTime(34)
today.setUTCDate(11)
today.setUTCMonth(5)
today.setUTCFullYear(2022)
today.setUTCHours(5)
today.setUTCMinutes(10)
today.setUTCSeconds(24)
today.setUTCMilliseconds(22)
const today = new Date();
today.toString() // Sun Aug 09 2020 16: 44: 29 GMT + 1000
(Australian Eastern Standard Time)
today.toLocaleString() // 09/08/2020, 16:44:29"
today.toGMTString() // Sun, 09 Aug 2020 06: 44: 29 GMT
today.toUTCString() // Sun, 69 Aug 2020 06: 44: 29 GMT
Date.parse('9 Aug 2020') // 1596895200800
//reurns number milliseconds since January 1, 1970 Returns NaN if invalid
let utcDate = new Date(Date.UTC(2028, 7, 9, 0, 0, 0));
utcDate // 2020-88-09T00:00:00.000Z
utcDate.valueOf() // 1596895200000 (same as parse)
-->
RegEx
"abc".match(/./) // . => any char
"abc".match(/b/) // b => must be present
"abc".match(/ab/) // ab => must be present
"abc".match(/a|z/) //alz=> a or z must be present
"abc".match(/z/) // z* => 0 or more times
"abc".match(/z+/) // z+ => 1 or more times
"abc".match(/z?/) // z? => 0 or 1 times
"abc".match(/(ab)/) // 11 => group, ab should present
"zta".match(/[ab-e]/) // match any char a, b, c, d, e
"ztf".match(/[^ab-e]/) // NOT any char a, b, c, d, e
"ab5".match(/\d/) // d => one digit
"ab5".match(/\D/) // D=> one non-digit
"355".match(/\D/) // fail bcoz all are digits
"ab c".match(/\s/) // \s => one whitespace
"ab c".match(/\S/) // \S => one non-whitespace
"".match(/\S/) // fail bcoz only whitespace
"abcd" .match(/\w/) // \w one word char
"ab cd".match(/\w/) // \w non word char fine
"abcd" .match(/\W/) // \W=> fail not a non-word char
"ab cd".match(/\W/) // \W=> pass one non-word char (" ")
"abc".match(/^a/) // ^ => start of string
"abc".match(/c$/) // $ => end of string
() // => group with parenthesis
\t // => tab
\n // => line breaks
\r // => CR
\0 // => null character
a{5} // => match a for 5 occurences
a{3,5} // => match a for min 2 & max 5 times
a{3,} // => match a for min 3 & more times
// REGEX flag
g // => global match
i // => ignore cases
Operators
5 == 5 //true
5 == '5' //true
5 === 5 //true
5 === '5'//false
---------------------------
5 != 5 //false
5 != '5' //false
5 !== 5 //false
5 !== '5'//true
--------------------------
2 + 2 // 4
4-2 // 2
2* 3 // 6
4 / 2 // 2
-------------------------
let a = 10; log(++a, a); // 11 11
let b = 10; log(b++, b); // 10 11
let c = 10; log(--c, c); // 9 9
let d = 10; log(d--, d); // 10 9
let a = 20; a += 5; // a = 25
let b = 20; b -= 5; // b = 15
let c = 20; c *= 5; // c=100
let d = 20; d / 5; // d = 4
let e = 20; e %= 5; // e = 0
(5 === 5) ? 'a' : 'b' // a
3 > 2 && 1 < 2 // true
3 > 2 | 5 < 2 // true
!true // false
3 > 3 // false
3 < 3 // false
3 >= 3 // true
3 <= 3 // true
5 % 2 // 1
DOM
//single element defined by id
const app = document.getElementById('app')
//multiple elements (arrays) defined by class name
const hero = document.getElementsByClassName('hero')
//multiple elements based on html tag
const h1 = document.getElementsByTagName('h1')
//first element based on selector
const hero = document.querySelector(".hero")
//multiple elements based on selector
const heroes = document.querySelectorAll(".hero")
h1.insertAdjacentHTML ("beforebegin", "cool")
app.classList.remove('dark')
//remove class
// beforebegin => placed before hi as a sibling
// afterbegin => placed inside h1 as a first child
// beforeend >> placed inside h1 as a last child
// afterend => placed after h1 as a sibling
app.classList.remove('dark') // renove class
app.classList.add('light') // add class
app.classList.toggle("visible") // toggle class
app.classList.contains('app') // true if app present
app.childNodes // retrieve all child nodes
app.parentNode // return parent
//create html element of tag
let para = document.createElement('p')
//create text node
let text = document.createTextNode('Hello') //
Hello
//add text node to the para element
para.appendChild(text)
//insert h2 before h1
app.insertBefore(h2, h1)
Mouse Events
click: //Triggered when a mouse click occurs.
dblclick: //Triggered when a mouse double click occurs.
mousedown: //Triggered when the mouse button is pressed down.
mouseup: //Triggered when the mouse button is released.
mousemove: //Triggered when the mouse pointer moves over an element.
mouseover: //Triggered when the mouse pointer enters an element.
mouseout: //Triggered when the mouse pointer leaves an element.
mouseenter: //Similar to mouseover, but doesn't bubble.
mouseleave: //Similar to mouseout, but doesn't bubble.
contextmenu: //Triggered when the right mouse button is clicked.
Keyboard Events:
keydown: //Triggered when a key is pressed down.
keyup: //Triggered when a key is released.
keypress: //Triggered when a key is pressed and released
(not all keys trigger this event).
Form Events:
submit: //Triggered when a form is submitted.
reset: //Triggered when a form is reset.
input: //Triggered when the value of an input field changes.
change: //Triggered when the value of a form element changes
(input, select, textarea).
focus: //Triggered when an element receives focus.
blur: //Triggered when an element loses focus.
Window and Document Events:
load: //Triggered when the page finishes loading.
unload: //Triggered when the user leaves the page.
resize: //Triggered when the window is resized.
scroll: //Triggered when the user scrolls the page.
DOMContentLoaded: //Triggered when the DOM is fully loaded,
even if other resources like images are still loading.
Drag and Drop Events:
dragstart: //Triggered when an element is dragged.
dragend: //Triggered when the dragging operation is completed.
dragenter: //Triggered when a dragged element enters a valid drop target.
dragover: //Triggered when a dragged element is over a valid drop target.
dragleave: //Triggered when a dragged element leaves a valid drop target.
drop: //Triggered when a dragged element is dropped on a valid drop target.
Media Events:
play: //Triggered when media playback starts.
pause: //Triggered when media playback is paused.
ended: //Triggered when media playback finishes.
Touch Events (for mobile devices):
touchstart: //Triggered when a finger touches the screen.
touchmove: //Triggered when a finger moves on the screen.
touchend: //Triggered when a finger is lifted from the screen.
Custom Events: //You can also create custom events using
the CustomEvent constructor and dispatch them on DOM elements.
async await
async function getCurrencies() {
const response = await fetch(
"https://asatryanhov.github.io/data_exchanges/"
);
const data = await response.json();
return data;
}
getCurrencies()
.then((data) => {
const x = data;
return x;
})
.then((x) => {
console.log(x);
});
try catch
try {
let num = 5 * 5;
console.log("Script is working")
} catch ({name,message}) {
console.log(name);
console.log(message);
}
Loops
// For Loop
for (let i = 0; i < 5; i++) {
console.log("For Loop:", i);
}
// While Loop
let j = 0;
while (j < 5) {
console.log("While Loop:", j);
j++;
}
// Do-While Loop
let k = 0;
do {
console.log("Do-While Loop:", k);
k++;
} while (k < 5);
// For-In Loop (Object)
const person = { name: "John", age: 30 };
for (const key in person) {
console.log("For-In Loop (Object):", key, person[key]);
}
// For-Of Loop (Array)
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log("For-Of Loop (Array):", color);
}
// For-Each Method (Array)
const numbers = [1, 2, 3];
numbers.forEach((number) => {
console.log("For-Each Method (Array):", number);
});
// For-Of Loop with Entries (Array)
for (const [index, color] of colors.entries()) {
console.log("For-Of Loop with Entries (Array):", index, color);
}
// For-Of Loop with Keys and Values (Object)
for (const [key, value] of Object.entries(person)) {
console.log("For-Of Loop with Keys and Values (Object):", key, value);
}
// For-Of Loop with Keys (Object)
for (const key of Object.keys(person)) {
console.log("For-Of Loop with Keys (Object):", key);
}
import export
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// main.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // 8
console.log(subtract(10, 4)); // 6
// person.js
const person = {
name: 'John',
age: 30,
};
export default person;
// main.js
import person from './person.js';
console.log(person.name); // 'John'
// main.js
import { add as addition, subtract as subtraction } from './math.js';
console.log(addition(5, 3)); // 8
console.log(subtraction(10, 4)); // 6
// myModule.js
export default function myFunction() {
console.log('Default export');
}
export function namedFunction() {
console.log('Named export');
}
// main.js
import myFunction, { namedFunction } from './myModule.js';
myFunction(); // Default export
namedFunction(); // Named export
Debounce & Throttle
const input = document.querySelector("input");
const defaultText = document.getElementById("default");
const debounceText = document.getElementById("debounce");
const throttleText = document.getElementById("throttle");
// Throttle
const updateThrottleText = throttle((text) => {
// throttleText.textContent = text;
incrementCount(throttleText);
}, 100)
const updateDebounceText = debounce((text) => {
// debounceText.textContent = text;
incrementCount(debounceText);
})
// input.addEventListener("input", e => {
// defaultText.textContent = e.target.value;
// updateDebounceText(e.target.value);
// updateThrottleText(e.target.value);
// });
function debounce(callBack, delay = 1000) {
let timeout;
return (arg) => {
clearInterval(timeout);
timeout = setTimeout(() => {
callBack(arg);
}, delay);
}
}
function throttle(callBack, delay = 1000) {
let isPaused = false;
return (...arg) => {
if (isPaused) return;
callBack(...arg);
isPaused = true;
setTimeout(() => {
isPaused = false;
}, delay);
}
}
function incrementCount(element) {
element.textContent = (parseInt(element.innerText) || 0) + 1;
}
document.addEventListener('mousemove', (event) => {
incrementCount(defaultText);
updateDebounceText()
updateThrottleText()
})
ES7-ES9
Object methods
get Own Property Descriptors
Minor enhancers
Minor enhancers 2
Async functions
Async errors handling
Async iterators
Array methods
String methods
RegExp
Object methods
// .entries() for Object:
const user = {
firstName: "Yauhen",
lastName: "Kavalchuk",
};
Object.entries(user); // [ [ 'firstName', "Yauhen" ], [ 'lastName', "Kavalchuk" ] ];
// .entries() for Array:
const name = ['Y', 'a', 'u', 'h', 'e', 'n'];
Object.entries(name); // [ [ '0', 'Y' ], [ '1', 'a' ], [ '2', 'u' ], [ '3', 'h' ], [ '4', 'e' ], [ '5', 'n' ] ];
// .entries() ignore Symbol key:
const admin = {
[Symbol('password')]: '123pass',
name: 'Yauhen',
};
Object.entries(admin); // [ [ 'name', 'Yauhen' ] ];
// .fromEntries() using:
const arr = [['one', 1], ['two', 2], ['three', 3]];
Object.fromEntries(arr); // { one: 1, two: 2, three: 3 }
// .values() using:
const user = {
firstName: "Yauhen",
lastName: "Kavalchuk",
};
Object.values(user); // [ "Yauhen", "Kavalchuk" ] ];
get Own Property Descriptors
// Base object with properties, get and set:
const person = {
name: 'Max',
age: 30,
set personName(name) {
this.name = name;
},
get password() {
return `${this.name}${this.age}`;
},
};
console.log(person); // {name: "Max", age: 30}
console.log(person.password); // "Max30"
// Get property descriptors:
console.log(Object.getOwnPropertyDescriptors(person));
/*
age: {value: 30, writable: true, enumerable: true, configurable: true}
name: {value: "Max", writable: true, enumerable: true, configurable: true}
password: {get: ƒ, set: undefined, enumerable: true, configurable: true}
personName: {get: undefined, set: ƒ, enumerable: true, configurable: true}
*/
// Clone object:
// Using assign()
const admin = Object.assign({}, person);
// Using destructuring
const admin = { ...person };
console.log(admin); // {name: "Max", age: 30, personName: undefined, password: "Max30"}
console.log(Object.getOwnPropertyDescriptors(admin));
/*
age: {value: 30, writable: true, enumerable: true, configurable: true}
name: {value: "Max", writable: true, enumerable: true, configurable: true}
password: {value: "Max30", writable: true, enumerable: true, configurable: true}
personName: {value: undefined, writable: true, enumerable: true, configurable: true}
*/
// Clone object:
// Using .getOwnPropertyDescriptors()
const superAdmin = Object.defineProperties({}, Object.getOwnPropertyDescriptors(person));
console.log(Object.getOwnPropertyDescriptors(superAdmin));
/*
age: {value: 30, writable: true, enumerable: true, configurable: true}
name: {value: "Max", writable: true, enumerable: true, configurable: true}
password: {get: ƒ, set: undefined, enumerable: true, configurable: true}
personName: {get: undefined, set: ƒ, enumerable: true, configurable: true}
*/
Minor enhancers
// Math.pow():
Math.pow(7, 2) // 49
// Exponentiation operator:
7**2 // 49
5**3 // 125
2**4 // 16
// Complecated math operation
// Old:
Math.pow(7, 2) + Math.pow(5, 3) / Math.pow(2, 4);
// New version:
7**2 + 5**3 / 2**4;
// New version with braces:
(7**2) + (5**3) / (2**4);
// Base Object:
const user = {
firstName: "Yauhen",
lastName: "Kavalchuk"
};
// Base function constructor:
function Person(
name,
age
) {
this.name = name;
this.age = age;
};
// Added property for Object:
const user = {
firstName: "Yauhen",
lastName: "Kavalchuk",
age: 30
};
// Added argument for function constructor:
function Person(
name,
age,
city
) {
this.name = name;
this.age = age;
this.city = city;
};
// The same changes, but with trailing commas:
const user = {
firstName: "Yauhen",
lastName: "Kavalchuk",
age: 30,
};
function Person(
name,
age,
city,
) {
this.name = name;
this.age = age;
this.city = city;
};
Async_functions
// Base async function:
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
const fetchedText = await fetchText();
console.log(`This is a feature of ${fetchedText}`);
};
showText(); // This is a feature of ES8
// Work sync with async functionality:
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = () => {
const fetchedText = fetchText();
console.log(`This is feature a of ${fetchedText}`);
};
showText(); // This is a feature of [object Promise]
// Async function always return Promise
// We can handle result:
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
const fetchedText = await fetchText();
return `This is feature a of ${fetchedText}`;
};
showText().then(data => console.log(data)); // This is a feature of ES8
// if async function return simple value,
// this value still be in Promise
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
const fetchedText = await fetchText();
return 10;
};
console.log(showText()); // Promise
showText().then(data => console.log(data)); // 10
// Execute of 2 and more async functions:
const fetchDescrText = () => new Promise(resolve => { setTimeout(() => resolve('This is a feature of'), 2000); });
const fetchEsText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
const fetchedDescrText = await fetchDescrText();
const fetchedEsText = await fetchEsText();
return `${fetchedDescrText} ${fetchedEsText}`;
};
// Receive result after ~4000ms
showText().then(data => console.log(data)); // This is a feature of ES8
// Parallel execute of async functions:
const showText = async () => {
const [fetchedDescrText, fetchedEsText] = await Promise.all([fetchDescrText(), fetchEsText()]);
return `${fetchedDescrText} ${fetchedEsText}`;
};
// Receive result after ~2000ms
showText().then(data => console.log(data)); // This is a feature of ES8
Async errors handling
// Base async functional:
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
const fetchedText = await fetchText();
console.log(`This is a feature of ${fetchedText}`); // This is a feature of ES8
};
showText();
// Error handling with 'try/catch':
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
try {
const fetchedText = await fetchText();
console.log(`This is a feature of ${fetchedText}`);
} catch (e) {
console.log(e);
}
};
showText();
// Argument 'e' (error object) in 'catch' is not nessesary anymore
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
try {
const fetchedText = await fetchText();
console.log(`This is a feature of ${fetchedText}`);
} catch {
console.log('Something going wrong...');
}
};
showText();
// Error handling with 'catch' in 'await' function:
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
const fetchedText = await fetchText().catch(e => console.log(e));
console.log(`This is a feature of ${fetchedText}`);
};
showText();
// Error handling with 'catch' for full async function:
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
const fetchedText = await fetchText();
console.log(`This is a feature of ${fetchedText}`);
};
showText()
.then(console.log('Everything is OK!'))
.catch(e => console.log(e));
// Using 'finally' as a 3rd step of 'try/catch':
const fetchText = () => new Promise(resolve => { setTimeout(() => resolve('ES8'), 2000); });
const showText = async () => {
try {
showSpiner = true;
const fetchedText = await fetchText();
console.log(`This is a feature of ${fetchedText}`);
} catch {
console.log('Something going wrong...');
} finally {
showSpiner = false;
}
}
showText();
Async iterators
// Base Array (iterable instance):
const names = ['Jack', 'Max', 'Leo'];
// 'for-of' iteration:
for(let name of names) {
console.log(name); // 'Jack', 'Max', 'Leo'
}
// Base async Array:
const names = [
new Promise(resolve => resolve('Jack')),
new Promise(resolve => resolve('Max')),
new Promise(resolve => resolve('Leo')),
];
// Async function for iteration with 'for-of':
const showNames = async () => {
for (name of names) {
console.log(name);
}
};
showNames(); // Promise, Promise, Promise
// Async function for iteration with 'for-await-of':
const showNames = async () => {
for await (name of names) {
console.log(name);
}
};
showNames(); // 'Jack', 'Max', 'Leo'
// Async generator function:
async function* readLines(path) {
let file = await fileOpen(path);
try {
while (!file.EOF) {
yield await file.readLine();
}
} finally {
await file.close();
}
};
// Async iteration of async generator function results:
for await (const line of readLines(filePath)) {
console.log(line);
};
Array methods
// Base Array:
const arr = [1,2,3,4, 'five', NaN];
// Find element using .indexOf:
if(arr.indexOf(3) >= 0) {
console.log(true); // true
}
// Find element using .includes:
if(arr.includes(3)) {
console.log(true); // true
}
// Find NaN in Array:
const index = arr.findIndex(Number.isNaN);
console.log(index); // 5
// Difference in finding NaN in Array:
arr.indexOf(NaN); // -1
arr.includes(NaN); // true
// .flat() of 1st level:
const arr1 = [1, 2, [3, 4]];
arr1.flat(); // [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat(); // [1, 2, 3, 4, [5, 6]]
// .flat() of 2nd level:
const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2); // [1, 2, 3, 4, 5, 6]
// .flat() of Infinity level:
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// .flat() remove empty values:
const arr5 = [1, 2, , 4, 5];
arr5.flat(); // [1, 2, 4, 5]
// .flat() remove empty values from 1st & 2nd levels of Array:
const arr6 = [1, 2, , 4, 5, [6, , 8]];
arr6.flat(); // [1, 2, 4, 5, 6, 8]
// Using of .flatMap():
const arr7 = [[1], [2], [3], [4]];
arr7.flatMap(x => [x * 2]); // [2, 4, 6, 8]
String methods
// Base String:
const str = "test";
// .padStart() with argument:
str.padStart(10, '~'); // '~~~~~~test'
str.padEnd(10, '~'); // 'test~~~~~~'
// .padStart() without of argument:
str.padStart(10); // ' test'
str.padEnd(10); // 'test '
// Base String:
const str = "Hello, my name is Yauhen";
// .startsWith() using:
str.startsWith("Hello"); // true
str.startsWith("Hi"); // false
// .endsWith() using:
str.endsWith("Yauhen"); // true
str.endsWith("Jack"); // false
// Base String:
const str = "Hello, my name is Yauhen";
// The resulting string after .startsWith() is "my name is Yauhen":
str.startsWith("my", 7); // true
// The resulting string after .startsWith() is "my name is Yauhen":
str.startsWith("name", 7); // false
// The resulting string after .endsWith() is "Hello, my name":
str.endsWith("name", 14); // true
// The resulting string after .endsWith() is "Hello, my name":
str.endsWith("name", 10); // false
// Base String:
const str = " Just test string ";
// base string after .trim():
str.trim(); // "Just test string"
// Base String:
const str = " Just test string ";
// Base string after .trimStart():
str.trimStart(); // "Just test string "
// Base string after .trimEnd():
str.trimEnd(); // " Just test string"
Minor enhancers 2
// Base function:
function /* just a comment */ test () {}
// Difference between old and new versions of .toString():
// Old version:
test.toString(); // 'function test() {}'
// New version:
test.toString(); // 'function /* just a comment */ test () {}'
// Base function:
function greeting() {
const name = 'webDev';
console.log(`hello from ${name}`);
};
// Difference between old and new versions of .toString():
// Old version:
test.toString(); //'function greeting() {\nconst name = \'webDev\'\nconsole.log(`hello from ${name} //`)\n}'
// New version:
test.toString();
/* 'function greeting() {\n' +
" const name = 'webDev'\n" +
' console.log(`hello from ${name}`)\n' +
'}'
*/
// Symbol creation:
const mySymbol = Symbol('Symbol description');
// Define Symbol description
String(mySymbol) === 'Symbol(Symbol description)'; // true
// Define Symbol description using property description:
mySymbol.description; // 'Symbol description'
mySymbol.description === 'Symbol description'; // true
// If Symbol was created without description
// default value for property is 'undefined':
const myNewSymbol = Symbol();
myNewSymbol.description; // undefined
// Difference between old and new versions of .stringify():
// Old version:
JSON.stringify("\uD800"); // '"�"'
// New version:
JSON.stringify("\uD800"); // '"\\ud800"'
Reg Exp
// Difference between old and new versions of 'dot' behavior:
// Old version:
/one.two/.test('one\ntwo'); // false
// New version (dotAll)
// with flag /s:
/one.two/s.test('one\ntwo'); // true
// Base RegEx to work with date:
const regEx = /(\d{4})-(\d{2})-(\d{2})/;
const result = regEx.exec('2019-08-23');
console.log(result); // ["2019-08-23", "2019", "08", "23", index: 0, input: "2019-08-23", groups: undefined]
// RegExp with named groups - (?...):
const regEx = /(?\d{4})-(?\d{2})-(?\d{2})/;
const result = regEx.exec('2019-08-23');
console.log(result); // ["2019-08-23", "2019", "08", "23", index: 0, input: "2019-08-23", groups: {...}];
console.log(result.groups); // { year: "2019", month: "08", day: "23" }
// RegExp named groups and .replace():
const str = 'Kavalchuk Yauhen';
const repl = /(?[A-Za-z]+) (?[A-Za-z]+$)/u;
const newStr = str.replace(repl, '$, $');
console.log(newStr); // "Yauhen, Kavalchuk"
// Using named groups inside RegExp - \k:
let sameWords = /(?apple|orange) === \k/u;
sameWords.test('apple === apple'); //true
sameWords.test('orange === orange'); //true
sameWords.test('apple === orange'); //false
// Positive lookbehind (?<=[symbol]):
/(?<=#).*/.test('#frontend'); // true
/(?<=#).*/.test('frontend'); // false
// Difference between old and new approaches:
// Old
'#frontend'.match(/#.*/)[0]; // '#frontend'
// New
'#frontend'.match(/(?<=#).*/)[0]; // 'frontend'
// Negative lookbehind (?>![symbol]):
'course coasts $20'.match(/(?
TypeScript
Basic-1
// Data types in JavaScript
- number
- string
- boolean
- null
- undefined
- object
- Symbol // ES6
// Variable type changing
var num = 42; // number
num = 'hello'; // string
num = false; // boolean
// Defining types using operator typeof
typeof 42; // "number"
typeof 'str'; // "string"
typeof true; // "boolean"
typeof []; // "object"
typeof {}; // "object"
typeof null; // "object"
typeof undefined; // "undefined"
typeof Symbol(); // "symbol"
// const
const num = 42;
num = 'hello'; // Uncaught TypeError: Assignment to constant variable
// let
let num = 42;
num = 'hello'; // No errors
// Boolean Type
let isCompleted: boolean = false;
isCompleted = 42; // Type '42' is not assignable to type 'boolean'
isCompleted = '42'; // Type ’"42"' is not assignable to type 'boolean'
isCompleted = true;
// Number Type
const decimal: number = 6;
const integer: number = 7.10;
const hex: number = 0xf00d;
const binary: number = 0b1010;
const octal: number = 0o744;
// String Type for simple string
const name: string = 'Yauhen';
// String Type for template string
const sentence: string = `Hello, my name is ${ name }!`;
// Null & Undefined Types
// JavaScript:
typeof null; // "object"
typeof undefined; // "undefined"
// TypeScript types:
const u: undefined = undefined;
const n: null = null;
// Void Type
// For function result:
const greetUser = (): void => {
alert("Hello, nice to see you!");
};
// For 'greetUser'
// Error: Type '() => void' is not assignable to type 'void'
const greetUser: void = () => {
alert("Hello, nice to see you!");
};
Basic-2
// Array Type
let list: number[] = [1, 2, 3];
let list: Array = [1, 2, 3]; // Generic type
// Tuple Type
// Multiple lines
let x: [string, number];
x = ["hello", 10];
// One line
let y: [string, number] = ["goodbuy", 42];
// Error case:
x = [10, "hello"]; // Type 'string' is not assignable to type 'number'
// Any Type
// Any type for array
let y: [any, any] = ["goodbuy", 42];
let z: Array = [10, "hello"];
// Any type for string
let notSure: any = false;
// Issue case (no error)
notSure = true; // boolean
notSure = 42; // number
notSure = "hello"; // string
// Enum Type
enum Directions {
Up,
Down,
Left,
Right
}
Directions.Up; // 0
Directions.Down; // 1
Directions.Left; // 2
Directions.Right; // 3
// Custom index for enum elements
enum Directions {
Up = 2,
Down = 4,
Left = 6,
Right
}
Directions.Up; // 2
Directions.Down; // 4
Directions.Left; // 6
Directions.Right; // 7
// Never Type
// Function return Error
const msg = "hello";
const error = (msg: string): never => {
throw new Error(msg);
};
// Function infinite loop
const infiniteLoop = (): never => {
while (true) {
}
};
// Object Type
const create = (o: object | null): void => { };
create(1); // Argument of type '1' is not assignable to parameter of type 'object | null'
create('42'); // Argument of type '"42"' is not assignable to parameter of type 'object | null'
create({ obj: 1 });
// Multiple types for one value
let id: number | string;
id = 10; // number is valid
id = '42'; // string is valid
id = true; // Type 'true' is not assignable to type 'string | number'
// Type
type Name = string; // Custom type creation
let id: Name; // Apply custom type
id = "42"; // No error, because type of "42" is a string
id = 10; // Type '10' is not assignable to type 'string'
Enums
// Simple example of enum type
enum Directions {
Up,
Down,
Left,
Right
}
Directions.Up; // 0
Directions.Down; // 1
Directions.Left; // 2
Directions.Right; // 3
// Reverse enum
enum Directions {
Up,
Down,
Left,
Right
}
Directions[0] // "Up"
Directions[1] // "Down"
Directions[2] // "Left"
Directions[3] // "Right"
// Compiled code
"use strict";
var Directions;
(function (Directions) {
Directions[Directions["Up"] = 0] = "Up";
Directions[Directions["Down"] = 1] = "Down";
Directions[Directions["Left"] = 2] = "Left";
Directions[Directions["Right"] = 3] = "Right";
})(Directions || (Directions = {}));
// Custom index for enum elements
enum Directions {
Up = 2,
Down = 4,
Left = 6,
Right = 8
}
Directions.Up; // 2
Directions.Down; // 4
Directions[6]; // Left
Directions[8]; // Right
// Custom name for keys
enum links {
youtube = 'https://youtube.com/',
vk = 'https://vk.com/',
facebook = 'https://facebook.com/'
}
// Using
links.vk // "https://vk.com/"
links.youtube // "https://youtube.com/"
// Compiled code
"use strict";
var links;
(function (links) {
links["youtube"] = "https://youtube.com/";
links["vk"] = "https://vk.com/";
links["facebook"] = "https://facebook.com/";
})(links || (links = {}));
// const enum (without using)
const enum links {
youtube = 'https://youtube.com/',
vk = 'https://vk.com/',
facebook = 'https://facebook.com/'
}
// Compiled code is empty
"use strict";
// const enum (with using)
const enum links {
youtube = 'https://youtube.com/',
vk = 'https://vk.com/',
facebook = 'https://facebook.com/'
}
// Using of enum properties
const arr = [links.vk, links.facebook];
// Compiled code
"use strict";
const arr = ["https://vk.com/" /* vk */, "https://facebook.com/" /* facebook */];
Functions
// Function example
const createPassword = (name, age) => `${name}${age}`;
createPassword('Jack', 31); // "Jack31"
// Arguments type
const createPassword = (name: string, age: number) => `${name}${age}`;
// Multiple argument types
const createPassword = (name: string, age: number | string) => `${name}${age}`;
createPassword('Jack', 31); // 'Jack31'
createPassword('Jack', '31'); // 'Jack31'
// Default Arguments
const createPassword = (name: string = 'Max', age: number | string = 20) => `${name}${age}`;
createPassword(); // "Max20"
createPassword(null); // Argument of type 'null' is not assignable to parameter of type 'string | undefined'
// Function with two required arguments
const createPassword = (name: string, age: number): string => `${name}${age}`;
// Call function with one argument
createPassword('Jack'); // 'An argument for 'age' was not provided.'
// Function with optional argument 'age'
const createPassword = (name: string, age?: number) => `${name}${age}`;
// REST
const createSkills = (name, ...skills) => `${name}, my skils are ${skills.join()}`;
// REST type
const createSkills = (name: string, ...skills: Array) => `${name}, my skils are ${skills.join()}`;
// Call function with REST arguments
createSkills('Jack', 'JS', 'ES6', 'React'); // "Jack, my skils are JS,ES6,React"
// Returned type is string
const createPassword = (name: string, age: number | string): string => `${name}${age}`;
// Returned type is number
const sum = (first: number, second: number): number => first + second;
// Returned type is object
const createEmptyObject = (): object => ({});
// Void
const greetUser: void = () => {
alert("Hello, nice to see you!");
};
// Never Type
// Function return Error
const msg = "hello";
const error = (msg: string): never => {
throw new Error(msg);
};
// Function infinite loop
const infiniteLoop = (): never => {
while (true) {
}
};
// Function variable type
let myFunc;
function oldFunc(name: string):void {
alert(`Hello ${name}, nice to see you!`);
};
myFunc = oldFunc;
// Function type description
let myFunc: (firstArg: string) => void;
// Describe function type with wrong return type
let myFunc: (firstArg: string) => number;
function oldFunc(name: string):void {
alert(`Hello ${name}, nice to see you!`);
};
/*
Error:
Type '(name: string) => void' is not assignable to type '(firstArg: string) => number'.
Type 'void' is not assignable to type 'number'
*/
myFunc = oldFunc;
Objects
// Simple object example
let user = {
name: 'Yauhen',
age: 30,
};
// Object type using any
let user: any = {
name: 'Yauhen',
age: 30,
};
user = 'test'; // Now type of user is string
// Array Type
let list: Array = [1, 2, 3];
// Define object type
let user: { name: string, age: number } = {
name: 'Yauhen',
age: 30,
};
// Try to change property
let user: { name: string, age: number } = {
name: 'Yauhen',
/*
Error:
The expected type comes from property 'age'
which is declared here on type '{ name: string; age: number; }'
*/
age: 'test', // <--- Must be a number
};
// Try to change variable type
user = 'test'; // Type '"test"' is not assignable to type '{ name: string; age: number; }'
// Additional property
let user: { name: string, age: number } = {
name: 'Yauhen',
age: 30,
nickName: 'webDev', // Object literal may only specify known properties, and 'nickName' does not exist in type '{ name: string; age: number; }'
};
// Updating object type
let user: { name: string, age: number, nickName: string } = {
name: 'Yauhen',
age: 30,
nickName: 'webDev',
};
// Base object structure
let user: { name: string, age: number } = {
name: 'Yauhen',
age: 30,
};
// Dynamically try to add 'nickName' property
user.nickName = 'webDev'; // Property 'nickName' does not exist on type '{name: string; age: number;}'
// Updating object type
let user: { name: string, age: number, nickName: string } = {
name: 'Yauhen',
age: 30,
nickName: 'webDev', // Now everything is correct
};
// New admin object
let admin: { name: string, age: number, nickName: string } = {
name: 'Max',
age: 20,
nickName: 'Mad',
};
// 2 object with the same types
let user: { name: string, age: number, nickName: string } = {
name: 'Yauhen',
age: 30,
nickName: 'webDev',
};
let admin: { name: string, age: number, nickName: string } = {
name: 'Max',
age: 20,
nickName: 'Mad',
};
// Using Type for objects structure
type Person = { name: string, age: number, nickName: string };
// Apply Person type for objects with the same structure
let user: Person = {
name: 'Yauhen',
age: 30,
nickName: 'webDev',
};
let admin: Person = {
name: 'Max',
age: 20,
nickName: 'Mad',
};
// 2 object with almost the same structure
let user: Person = {
name: 'Yauhen',
age: 30,
nickName: 'webDev', // <--- property
};
let admin: Person = {
name: 'Max',
age: 20,
getPass(): string { // <--- new method
return `${this.name}${this.age}`;
},
};
// Updating type with optional properties
type Person = {
name: string,
age: number,
nickName?: string,
getPass?: () => string,
};
Classes
// Simple class example
class User {
}
// Class types
class User {
name: string;
age: number;
nickName: string;
}
// Class types, including constructor
class User {
name: string;
age: number;
nickName: string;
constructor(name: string, age: number, nickName: string) {
this.name = name;
this.age = age;
this.nickName = nickName;
}
}
const yauhen = new User('Yauhen', 31, 'webDev');
yauhen; // { name: "Yauhen", age: 31, nickName: "webDev" }
// Class types modificators
class User {
public name: string;
private nickName: string;
protected age: number;
readonly pass: number;
constructor(name: string, age: number, nickName: string, pass: number) {
this.name = name;
this.age = age;
this.nickName = nickName;
this.pass = pass;
}
}
const yauhen = new User('Yauhen', 31, 'webDev', 123);
yauhen.name; // "Yauhen"
yauhen.nickName; // Prop 'nickName' is private and only accessible within class 'User'
yauhen.age; // Prop 'age' is protected and only accessible within class 'User' and its subclasses
yauhen.pass = 42; // Cannot assign to 'pass' because it is a read-only property
// Class default properties
class User {
name: string;
age: number = 20;
nickName: string = 'webDev';
constructor(name: string) {
this.name = name;
}
}
const user = new User('Yauhen');
user; // { name: "Yauhen", age: 20, nickName: "webDev" }
// Class default properties (example)
class User {
name: string;
age: number = 20;
nickName: string = 'webDev';
constructor(name: string) {
this.name = name;
}
getPass(): string {
return `${this.nickName}${this.age}`;
}
}
const user = new User('Yauhen');
user.getPass(); // "webDev20"
// Minimization of Class properties
class User {
constructor(
public name: string,
public age: number,
public nickName: string,
public pass: number
) {}
}
// Try to change private property
class User {
private age: number = 20;
constructor(public name: string) {}
}
const yauhen = new User('Yauhen');
yauhen.age = 30; // Property 'age' is private and only accessible within class 'User'
// Get access to private property
class User {
private age: number = 20;
constructor(public name: string) {}
setAge(age: number) {
this.age = age;
}
set myAge(age: number) {
this.age = age;
}
}
const yauhen = new User('Yauhen');
yauhen.setAge(30); // 30
yauhen.myAge = 31; // 31
Inheritance
// Simple Class example
class User {
constructor(public name: string, public age: number) {}
}
const yauhen = new User('Yauhen', 31);
yauhen; // { name: 'Yauhen', age: 31 }
// Class with static property
class User {
static secret = 12345; // static property
constructor(public name: string, public age: number) {}
}
// Example of call static property
User.secret
// Call static property in class method
class User {
static secret = 12345;
constructor(public name: string, public age: number) {}
getPass(): string {
return `${this.name}${User.secret}`;
}
}
const yauhen = new User('Yauhen', 30);
yauhen.getPass(); // "Yauhen12345"
// Compiled code
"use strict";
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
getPass() {
return this.name + User.secret;
}
}
User.secret = 12345;
// Class example
class User {
private nickName: string = 'webDev';
static secret = 12345;
constructor(public name: string, public age: number) {}
getPass(): string {
return `${this.name}${User.secret}`;
}
}
// Inheritance example
class Yauhen extends User {
name: string = 'Yauhen';
}
// Create instances based on 'User' and 'Yauhen' classes
const max = new User('Max', 20);
const yauhen = new Yauhen(31); // Expected 2 arguments, but got 1
// Realization of constructor in the inherited class
class Yauhen extends User {
name: string = 'Yauhen';
constructor(age: number) {
super(name, age);
}
}
// No error
// Create instances based on 'User' and 'Yauhen' classes
const max = new User('Max', 20);
const yauhen = new Yauhen(31);
// Personal method in inherited class
class Yauhen extends User {
name: string = 'Yauhen';
constructor(age: number) {
super(name, age);
}
getPass(): string {
return `${this.age}${this.name}${User.secret}`;
}
}
const yauhen = new Yauhen(31);
yauhen.getPass(); // "31Yauhen12345"
// Abstract class example
abstract class User {
constructor(public name: string, public age: number) {}
greet(): void {
console.log(this.name);
}
abstract getPass(): string; // Abstract method
}
const max = new User('Max', 20); // Cannot create an instance of an abstract class
// Create class using Abstraction
class Yauhen extends User { // Non-abstract class 'Yauhen' does not implement inherited abstract member 'getPass' from class 'User'
name: string = 'Yauhen';
constructor(age: number) {
super(name, age);
}
}
// Realization of 'getPass' method
class Yauhen extends User {
name: string = 'Yauhen';
constructor(age: number) {
super(name, age);
}
getPass(): string {
return `${this.age}${this.name}`;
}
}
// Call prototype method
yauhen.greet(); // "Yauhen"
// Call personal method
yauhen.getPass(); // "31Yauhen"
Namespaces_&_Modules
// Just example of functionality
const SECRET: string = '123321';
const PI: number = 3.14;
const getPass = (name: string, age: number): string => `${name}${age}`;
const isEmpty = (data: T): boolean => !data;
// ES5 Module
(function () {
const SECRET: string = '123321';
const PI: number = 3.14;
const getPass = (name: string, age: number): string => `${name}${age}`;
const isEmpty = (data: T): boolean => !data;
}());
// Define namespace
namespace Utils {
const SECRET: string = '123321';
const PI: number = 3.14;
const getPass = (name: string, age: number): string => `${name}${age}`;
const isEmpty = (data: T): boolean => !data;
};
// Call namespace method
namespace Utils {
const SECRET: string = '123321';
const PI: number = 3.14;
const getPass = (name: string, age: number): string => `${name}${age}`;
const isEmpty = (data: T): boolean => !data;
};
// Try to call method outside namespace
const myPass = Utils.getPass('Yauhen', 31); // Property 'getPass' does not exist on type 'typeof Utils'
// Export data from Namespace
namespace Utils {
export const SECRET: string = '123321';
const PI: number = 3.14;
export const getPass = (name: string, age: number): string => `${name}${age}`;
export const isEmpty = (data: T): boolean => !data;
};
// Calling exported from namespace methods
const myPass = Utils.getPass('Yauhen', 31); // "Yauhen31"
const isSecret = Utils.isEmpty(Utils.SECRET); // "false"
// Constant with the same name outside namespace
const PI = 3; // No Errors
// File "Utils.ts"
// Export
namespace Utils {
export const SECRET: string = '123321';
export const getPass = (name: string, age: number): string => `${name}${age}`;
};
// File "Customers.ts"
// Import
/// // <--- Import
// Calling "Utils" namespace method
const myPass = Utils.getPass('Yauhen', 31); // "Yauhen31"
// Import/Export (ES6 Modules)
// File "Utils.ts"
export const SECRET: string = '123321';
export const getPass = (name: string, age: number): string => `${name}${age}`;
// File "Customers.ts"
import { getPass, SECRET } from "./Utils";
const myPass = getPass(SECRET, 31); // "Yauhen31"
Type_Interface
// Simple interface example
interface User {
name: string,
age: number,
}
// Interface & Type
interface User {
name: string,
age: number,
}
type User {
name: string,
age: number,
}
// Create object based on Interface
interface User {
name: string,
age: number,
}
const yauhen: User = {
name: 'Yauhen',
age: 31,
}
// Interface optional property
interface User {
name: string,
age?: number, // <--- Optional
}
// Creation with a required property
const yauhen: User = {
name: 'Yauhen',
}
// Creation with missing a required property
/*
Error:
Property 'name' is missing in type '{ age: number; }' but required in type 'User'
*/
const max: User = {
age: 20,
}
// Interface 'readonly' modifier
interface User {
readonly name: string,
age: number,
}
const yauhen: User = {
name: 'Yauhen',
age: 31,
}
yauhen.age = 30;
yauhen.name = 'Max'; // Cannot assign to 'name' because it is a read-only property
// Compare interface type and object
interface User {
name: string,
age: number,
}
const yauhen: User = {
name: 'Yauhen',
age: 31,
/*
Error:
Object literal may only specify known properties, and 'nickName' does not exist in type 'User'
*/
nickName: 'webDev', // <--- Didn't described in interface "User"
}
// Interface extension
interface User {
name: string,
age: number,
[propName: string]: any;
}
const yauhen: User = {
name: 'Yauhen',
age: 31,
nickName: 'webDev',
justTest: 'test',
}
// Class Interface
interface User {
name: string,
age: number,
getPass(): string,
}
class Yauhen implements User {
name: string = 'Yauhen';
age: number = 31;
nickName: string = 'webDev';
getPass() {
return `${this.name}${this.age}`;
}
}
// Create Class based on multiple interfaces
interface User {
name: string,
age: number,
}
// Separate interface with one method
interface Pass {
getPass(): string,
}
class Yauhen implements User, Pass {
name: string = 'Yauhen';
age: number = 31;
getPass() {
return `${this.name}${this.age}`;
}
}
// Interface extends
interface User {
name: string,
age: number,
}
// Interface extends
interface Admin extends User {
getPass(): string,
}
class Yauhen implements Admin {
name: string = 'Yauhen';
age: number = 31;
getPass() {
return `${this.name}${this.age}`;
}
}
Generic
// Example of using 'any'
const getter = (data: any): any => data;
getter(10); // 10
getter('test'); // "test"
// Issue we have
const getter = (data: any): any => data;
getter(10).length; // undefined
getter('test').length; // 4
// Using of generic type
const getter = (data: T): T => data;
function getter(data: T): T {
return data;
}
// Defining issue immediately
const getter = (data: T): T => data;
getter(10).length; // Property 'length' does not exist on type '10'
getter('test').length; // 4
// Generic behavior explanation
// For a number
const getter = (data: number): number => data;
getter(10).length; // Property 'length' does not exist on type '10'
// For a string
const getter = (data: string): string => data;
getter('test').length; // 4
// Function arguments type
const getter = (data: T): T => data;
// Define type in function calling
getter(10).length; // Property 'length' does not exist on type '10'
getter('test').length; // 4
// Array generic type
let list: Array = [1, 2, 3];
// Simple class example
class User {
constructor(public name: string, public age: number) {}
public getPass(): string {
return `${this.name}${this.age}`;
}
}
// Generic class
class User {
constructor(public name: T, public age: T) {}
public getPass(): string {
return `${this.name}${this.age}`;
}
}
const yauhen = new User('Yauhen', '31');
const max = new User(123, 321);
yauhen.getPass(); // "Yauhen31"
max.getPass(); // "123321"
// Multiple generic types
class User {
constructor(public name: T, public age: K) {}
public getPass(): string {
return `${this.name}${this.age}`;
}
}
const yauhen = new User('Yauhen', '31'); // string, string
const max = new User(123, 321); // number, number
const leo = new User('Leo', 22); // string, number
yauhen.getPass(); // "Yauhen31"
max.getPass(); // "123321"
leo.getPass(); // "Leo22"
// New Class method 'getSecret'
class User {
constructor(public name: T, public age: K) {}
public getPass(): string {
return `${this.name}${this.age}`;
}
public getSecret(): number {
return this.age**2;
}
}
// Specify generic type 'K' with key-word 'extends'
class User {
constructor(public name: T, public age: K) {}
public getPass(): string {
return `${this.name}${this.age}`;
}
public getSecret(): number {
return this.age**2;
}
}
const yauhen = new User('Yauhen', 31);
const leo = new User(123, 321);
/*
Error:
Argument of type '"20"' is not assignable to parameter of type 'number'
*/
const max = new User('Max', '20');
Decorators
// Simple class example
class User {
constructor(public name: string, public age: number) {}
public getPass(): string {
return `${this.name}${this.age}`;
}
}
// Base structure of Decorator :)
const logClass = () => ();
// Class Decorator
const logClass = (constructor: Function) => {
console.log(constructor); // Result of call: class User {}
};
@logClass // <--- Apply decorator for class
class User {
constructor(public name: string, public age: number) {}
public getPass(): string {
return `${this.name}${this.age}`;
}
}
// Property Decorator
const logProperty = (target: Object, propertyKey: string | symbol) => {
console.log(propertyKey); // Result of call: "secret"
};
class User {
@logProperty // <--- Apply decorator for property
secret: number;
constructor(public name: string, public age: number, secret: number) {
this.secret = secret;
}
public getPass(): string {
return `${this.name}${this.age}`;
}
}
// Method Decorator
const logMethod = (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
console.log(propertyKey); // Result of call: "getPass"
};
class User {
constructor(public name: string, public age: number) {}
@logMethod // <--- Apply decorator for method
public getPass(): string {
return `${this.name}${this.age}`;
}
}
// get/set Decorator
const logSet = (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
console.log(propertyKey); // Result of call: "myAge"
};
class User {
constructor(public name: string, public age: number) {}
@logSet // <--- Apply decorator for set
set myAge(age: number) {
this.age = age;
}
}
// Factory Decorator
function factory(value: any) { // Factory
return function (target: any) { // Decorator
console.log(target); // Decorator logic
}
}
// Applying Factory Decorator
const enumerable = (value: boolean) => {
return (
target: any,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
descriptor.enumerable = value;
};
}
class User {
constructor(public name: string, public age: number) {}
@enumerable(false) // <--- Call decorator factory with argument
public getPass(): string {
return `${this.name}${this.age}`;
}
}
// Decorator composition syntax
// Apply decorators (one line)
@f @g x
// Apply decorators (multiple lines)
@f
@g
x
// Example of two factory decorators
const first = () => {
console.log('first() completing');
return (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
console.log('first() called');
};
}
const second = () => {
console.log('second() completing');
return (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
console.log('second() called');
};
}
// Apply and call two factory decorators
class User {
constructor(public name: string, public age: number) {}
@first()
@second()
public getPass(): string {
return `${this.name}${this.age}`;
}
}
// Call results:
"first() completing" // Factory 1
"second() completing" // Factory 2
"second() called" // Decorator 2
"first() called" // Decorator 1
Utility_Types
// Readonly
interface User {
name: string;
}
const user: Readonly = {
name: 'Yauhen',
};
user.name = 'Max'; // Error: cannot reassign a readonly property
// Required
interface Props {
a?: number;
b?: string;
};
const obj: Props = { a: 5 }; // OK
const obj2: Required = { a: 5 }; // Error: property 'b' missing
// Record
interface PageInfo {
title: string;
}
type Page = 'home' | 'about' | 'contact';
const x: Record = {
about: { title: 'about' },
contact: { title: 'contact' },
home: { title: 'home' },
};
// Compiled code
"use strict";
const x = {
about: { title: 'about' },
contact: { title: 'contact' },
home: { title: 'home' },
};
// Pick
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
// Omit
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
// Exclude
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
type T2 = Exclude void), Function>; // string | number
// Extract
type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
type T1 = Extract void), Function>; // () => void
// NonNullable
type T0 = NonNullable; // string | number
type T1 = NonNullable; // string[]
// ReturnType
declare function f1(): { a: number, b: string };
type T0 = ReturnType<() => string>; // string
type T1 = ReturnType<(s: string) => void>; // void
type T2 = ReturnType<(() => T)>; // {}
type T3 = ReturnType<(() => T)>; // number[]
type T4 = ReturnType; // { a: number, b: string }
type T5 = ReturnType; // any
type T6 = ReturnType; // any
type T7 = ReturnType; // Error
type T8 = ReturnType; // Error
// InstanceType
class C {
x = 0;
y = 0;
}
type T0 = InstanceType; // C
type T1 = InstanceType; // any
type T2 = InstanceType; // any
type T3 = InstanceType; // Error
type T4 = InstanceType; // Error
HTML
Base HTML Document Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
Meta Data & External Imports
<!-- Document title in browser tabs -->
<title>HTML Basics</title>
<!-- Document Favicon in browser tabs -->
<link rel="shortcut icon" href="icon.ico" type="image/x-icon">
<!-- Additional approach to add favicon -->
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
<!-- SEO -->
<meta name="description" content="Test web page">
<meta name="keywords" content="html, webdev, Yauhen">
<meta name="author" content="Yauhen Kavalchuk">
<!-- For mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- For mobile & no resize -->
<meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no">
<!-- Use latest version of IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- For external styles -->
<link rel="stylesheet" href="styles.css">
<!-- Local styles -->
<style>
div {
background-color: red;
}
</style>
<!-- Local styles fonts -->
<link rel="stylesheet" href="styles.css">
<!-- Google fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
Validation Semantic Accessibility
<!-- Block element -->
<div>Simple text</div>
<!-- Inline element -->
<span>Simple text</span>
<!-- Examples of semantic tags -->
<header></header>
<nav></nav>
<article></article>
<footer></footer>
Text
<!-- Headings -->
<h1>Different Headings</h1>
<h2>Different Headings</h2>
<h3>Different Headings</h3>
<h4>Different Headings</h4>
<h5>Different Headings</h5>
<h6>Different Headings</h6>
<hr>
<!-- Paragraph -->
<p>Simple paragraph with text.</p>
<hr>
<!-- Information about author -->
<p>Here is my HTML basics course, which was created on 2019.</p>
<address>Yauhen Kavalchuk, YouTube lecturer</address>
<hr>
<!-- Quote and author -->
<q>Hello, welcome to "webDev" channel</q>
<address>Yauhen Kavalchuk, YouTube lecturer</address>
<hr>
<!-- Block of Quote -->
<blockquote>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type.
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
</p>
</blockquote>
<hr>
<!-- Time or date information -->
<time>1989-01-26</time>
<br>
<time datetime="1989-01-26">My Birthday</time>
<hr>
<!-- Bold & Italic, Typing, Deleted text -->
<b>Bold text</b><br>
<i>Italic text</i><br>
<tt>Typing text</tt><br>
<s>Deleted text</s>
<hr>
<!-- Code examples -->
<code>
const args = {
name: "Yauhen",
age: 30
};
const getDate = () => new Date;
</code>
<hr>
<!-- Save test formating -->
<pre>
<code>
const args = {
name: "Yauhen",
age: 30
};
const getDate = () => new Date;
</code>
</pre>
<hr>
<!-- Bold & Italic text with semantic accent -->
<strong>Bold accent text</strong><br>
<em>Italic accent text</em><br>
<hr>
<!-- Small text -->
<small>Small</small>
<h2>To know HTML <small>semantic</small> is important</h2>
<hr>
<!-- Small text -->
<big>Big</big>
<h2>To know HTML <big>semantic</big> is important</h2>
<hr>
<!-- Deleted text -->
<del>Deleted</del>
<h2>To know HTML <del>semantic</del> is important</h2>
<hr>
<!-- Inserted/added text -->
<ins>Inserted</ins>
<h2>To know HTML <ins>semantic</ins> is important</h2>
<hr>
<!-- Subscripted text -->
<sub>Subscripted</sub>
<h2>To know HTML <sub>semantic</sub> is important</h2>
<h2>H<sub>2</sub>O</h2>
<hr>
<!-- Superscripted text -->
<sup>Superscripted</sup>
<h2>To know HTML <sup>semantic</sup> is important</h2>
<h2>X<sup>2</sup> = 9</h2>
<hr>
Lists
<!-- Unordered List -->
<ul>
<li>Front-end Developer</li>
<li>Bask-end Developer</li>
<li>Full-stack Developer</li>
</ul>
<hr>
<!-- Ordered List -->
<ol>
<li>Front-end Developer</li>
<li>Back-end Developer</li>
<li>Full-stack Developer</li>
</ol>
<hr>
<!-- Ordered List with start -->
<ol start="10">
<li>Front-end Developer</li>
<li>Back-end Developer</li>
<li>Full-stack Developer</li>
</ol>
<hr>
<!-- Ordered List with reversed -->
<ol reversed>
<li>Front-end Developer</li>
<li>Back-end Developer</li>
<li>Full-stack Developer</li>
</ol>
<hr>
<!-- Nested Unordered List -->
<ul>
<li>
Front-end Developer
<ul>
<li>Mobile</li>
<li>UI</li>
<li>Node.js</li>
</ul>
</li>
<li>Back-end Developer</li>
<li>Full-stack Developer</li>
</ul>
<hr>
<!-- Nested Ordered List -->
<ol>
<li>
Front-end Developer
<ol>
<li>Mobile</li>
<li>UI</li>
<li>Node.js</li>
</ol>
</li>
<li>Back-end Developer</li>
<li>Full-stack Developer</li>
</ol>
<hr>
<!-- Nested Unordered List with Inner Ordered List -->
<ul>
<li>
Front-end Developer
<ol>
<li>Mobile</li>
<li>UI</li>
<li>Node.js</li>
</ol>
</li>
<li>Back-end Developer</li>
<li>Full-stack Developer</li>
</ul>
<hr>
<!-- Definitions List -->
<dl>
<dt>Front-end Developer</dt>
<dd>It is a person who works with the visible part of website.</dd>
<dt>Back-end Developer</dt>
<dd>It is a person who works with the hidden part of a website, including databases and environments.</dd>
</dl>
<hr>
Images
<!-- Simple image -->
<img src="https://picsum.photos/300/300" alt="Just image">
<!-- Responsive image -->
<picture>
<source media="(min-width: 1024px)" srcset="https://picsum.photos/600/600">
<source media="(min-width: 768px)" srcset="https://picsum.photos/300/300">
<source media="(min-width: 360px)" srcset="https://picsum.photos/100/100">
<img src="https://picsum.photos/300/300" alt="Just image">
</picture>
<!-- Image with semantic description -->
<figure>
<img src="https://picsum.photos/300/300" alt="Just image" />
<figcaption>It is a simple description for a picture above</figcaption>
</figure>
<!-- Images with semantic description -->
<figure>
<img src="https://picsum.photos/300/300" alt="Just image" />
<img src="https://picsum.photos/300/300" alt="Just image" />
<img src="https://picsum.photos/300/300" alt="Just image" />
<figcaption>
<p>It is a simple description for a couple pictures above.It is a simple description for a couple pictures above.It is a simple description for a couple pictures above</p>
</figcaption>
</figure>
Table
<!-- Minimum valid markup for table -->
<table>
<tr>
<td>Front-end</td>
</tr>
</table>
<hr>
<!-- Table row with data -->
<table>
<tr>
<td>Front-end</td>
<td>Back-end</td>
<td>Full-stack</td>
<td>QA</td>
</tr>
</table>
<hr>
<!-- Table column with data -->
<table>
<tr>
<td>Front-end</td>
</tr>
<tr>
<td>Back-end</td>
</tr>
<tr>
<td>Full-stack</td>
</tr>
<tr>
<td>QA</td>
</tr>
</table>
<hr>
<!-- Simple example of table -->
<table>
<tr>
<td>Front-end</td>
<td>1 Person</td>
</tr>
<tr>
<td>Back-end</td>
<td>7 Persons</td>
</tr>
<tr>
<td>Full-stack</td>
<td>2 Persons</td>
</tr>
<tr>
<td>QA</td>
<td>5 Persons</td>
</tr>
</table>
<hr>
<!-- Table with caption -->
<table>
<caption>Team members list</caption>
<tr>
<td>Front-end</td>
<td>1 Person</td>
</tr>
<tr>
<td>Back-end</td>
<td>7 Persons</td>
</tr>
<tr>
<td>Full-stack</td>
<td>2 Persons</td>
</tr>
<tr>
<td>QA</td>
<td>5 Persons</td>
</tr>
</table>
<hr>
<!-- Table with semantic sections -->
<table>
<caption>Team members list</caption>
<thead>
<tr>
<td>Speciality</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
<tr>
<td>Front-end</td>
<td>1 Person</td>
</tr>
<tr>
<td>Back-end</td>
<td>7 Persons</td>
</tr>
<tr>
<td>Full-stack</td>
<td>2 Persons</td>
</tr>
<tr>
<td>QA</td>
<td>5 Persons</td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td>15</td>
</tr>
</tfoot>
</table>
<hr>
<!-- Colspan in tfoot and th tag for table head -->
<table>
<caption>Team members list</caption>
<thead>
<tr>
<th>Speciality</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>Front-end</td>
<td>1 Person</td>
</tr>
<tr>
<td>Back-end</td>
<td>7 Persons</td>
</tr>
<tr>
<td>Full-stack</td>
<td>2 Persons</td>
</tr>
<tr>
<td>QA</td>
<td>5 Persons</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">15</td>
</tr>
</tfoot>
</table>
<hr>
Links & Buttons
<!-- Simple link -->
<a href="https://youtube.com/YauhenKavalchuk">Youtube</a>
<hr>
<!-- Download link -->
<a href="test.txt" download>Download</a>
<hr>
<!-- Open link in new tab -->
<a href="https://youtube.com/YauhenKavalchuk" target="_blank">Youtube</a>
<hr>
<!-- Open link in new tab -->
<a href="tel:+123-32-23">+123-32-23</a><br>
<a href="mailto:test@test.com">My e-mail</a><br>
<a href="skype:test">Skype Call</a><br>
<hr>
<!-- Anchor link -->
<a href="#bottom">Go to Bottom</a>
<hr>
<!-- Simple buttons -->
<button type="button">Button</button>
<button type="submit">Button</button>
<button type="reset">Button</button>
<hr>
<!-- Button with autofocus -->
<button type="button" autofocus>Button</button>
<hr>
<!-- Disabled Button -->
<button type="button" disabled>Button</button>
<hr>
<!-- Necessary div with id -->
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p id="bottom">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
Useful Tags
<!-- Abbreviation -->
<abbr title="HyperText Markup Language">HTML</abbr> was created in 1993.
<hr>
<!-- List of options -->
<input list="list">
<datalist id="list">
<option value="Front-end">
<option value="Back-end">
<option value="Full-stack">
</datalist>
<hr>
<!-- Meter -->
<meter value="0" max="100" low="10" high="60">Course Progress</meter><br>
<meter value="20" max="100" low="40" high="60">Course Progress</meter><br>
<meter value="80" max="100" low="10" high="60">Course Progress</meter><br>
<meter value="100" max="100">Course Progress</meter>
<hr>
<!-- Progress bar -->
<progress value="30" max="100"></progress>
<hr>
<!-- No scripts tag -->
<noscript>Please switch on scripts in your browser!</noscript>
<!-- Marked text -->
<mark>Marked</mark>
<h2>To know HTML <mark>semantic</mark> is important</h2>
<hr>
<canvas id="example" width="200" height="200"></canvas>
<script>
const drawingCanvas = document.getElementById('example');
if(drawingCanvas && drawingCanvas.getContext) {
const context = drawingCanvas.getContext('2d');
context.fillStyle = "#000";
context.beginPath();
context.arc(100,100,100,0,Math.PI*2,true);
context.closePath();
context.stroke();
context.fill();
}
</script>
Global Site Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Basics</title>
<style>
html {
padding: 0;
}
* {
border: 1px dashed #000;
padding: 10px;
}
body {
min-height: 100vh;
margin: 0;
padding: 0;
display: grid;
grid-template-rows: 200px 1fr 200px;
grid-template-columns: 200px 1fr 200px;
font-size: 30px;
font-weight: 900;
color: #fff;
text-shadow: 1px 1px 2px #000;
}
header,
footer {
background-color: red;
grid-column: 1 / 4;
}
main {
grid-column: 1 / 3;
}
section,
article,
nav {
margin: 20px;
}
header { background-image: linear-gradient(to top, #a18cd1 0%, #fbc2eb 100%); }
footer { background-image: linear-gradient(to right, #ff8177 0%, #cf556c 100%); }
main { background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%); }
section { background-image: linear-gradient(120deg, #a6c0fe 0%, #f68084 100%); }
nav { background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%); }
article { background-image: linear-gradient(to right, #43e97b 0%, #38f9d7 100%); }
aside { background-image: linear-gradient(to right, #d4fc79 0%, #f68084 100%); }
</style>
</head>
<body>
<!-- Header -->
<header>
HEADER
<!-- Main navigation -->
<nav>NAVIGATION</nav>
</header>
<!-- Main part of site -->
<main>
MAIN
<!-- Independent block -->
<section>
SECTION
<!-- Peace of news, article -->
<article>ARTICLE 1</article>
<article>ARTICLE 2</article>
<article>ARTICLE 3</article>
</section>
<section>
SECTION
<article>ARTICLE 4</article>
</section>
</main>
<!-- Aditional information -->
<aside>ASIDE</aside>
<!-- Footer -->
<footer>FOOTER</footer>
</body>
</html>
Form
<!-- Simple form -->
<form action="formHandler.php" name="simple form" autocomplete="on">
<input type="text" /><br>
<select>
<option value="Front-end">Front-end</option>
<option value="Back-end">Back-end</option>
</select><br>
<textarea rows="10" cols="45" name="text"></textarea><br>
<input type="submit"><br>
</form>
<hr>
<!-- Fieldset & label -->
<form action="formHandler.php" name="simple form2">
<fieldset>
<legend>Simple form legend</legend>
<input type="text" /><br>
<select>
<option value="Front-end">Front-end</option>
<option value="Back-end">Back-end</option>
</select><br>
<textarea rows="10" cols="45" name="text"></textarea><br>
<input type="submit"><br>
</fieldset>
</form>
<hr>
<!-- Inner fieldset & label -->
<form action="formHandler.php" name="simple form3">
<fieldset>
<legend>Personal data</legend>
<input type="text" /><br>
<select>
<option value="Front-end">Front-end</option>
<option value="Back-end">Back-end</option>
</select><br>
</fieldset>
<fieldset>
<legend>Personal Message</legend>
<textarea rows="10" cols="45" name="text"></textarea><br>
</fieldset>
<input type="submit"><br>
</form>
<hr>
<!-- Form element label -->
<label for="username">Username</label>
<input id="username"><br>
<label>
Password
<input type="password">
</label>
<hr>
<!-- Result form -->
<form action="formHandler.php" name="simple form3">
<fieldset>
<legend>Personal data</legend>
<label for="name">Your name</label>
<input type="text" id="name" /><br>
<label for="speciality">Choose your speciality</label>
<select id="speciality">
<option value="Front-end">Front-end</option>
<option value="Back-end">Back-end</option>
</select><br>
</fieldset>
<fieldset>
<legend>Personal Message</legend>
<label for="message">Enter your message</label>
<textarea id="message" rows="10" cols="45" name="text"></textarea><br>
</fieldset>
<input type="submit"><br>
</form>
<hr>
<!-- Textarea -->
<textarea rows="10" cols="45"></textarea><br>
<textarea rows="5" cols="20" name="test"></textarea><br>
<textarea rows="5" cols="20" autofocus></textarea><br>
<textarea rows="5" cols="20" disabled></textarea><br>
<textarea rows="5" cols="20" readonly>This text you can't change</textarea><br>
<textarea rows="5" cols="20" placeholder="your message..."></textarea><br>
<textarea rows="5" cols="20" maxlength="5"></textarea><br>
<textarea rows="5" cols="20" required></textarea><br>
<hr>
<!-- Required attribute -->
<form>
<textarea rows="5" cols="20" required></textarea><br>
<input type="submit" value="Send">
</form>
<hr>
<!-- Select -->
<select>
<option value="Front-end">Front-end</option>
<option value="Back-end">Back-end</option>
</select>
<hr>
<!-- Select with optgroup -->
<select>
<optgroup label="Speciality">
<option value="Front-end">Front-end</option>
<option value="Back-end">Back-end</option>
</optgroup>
<optgroup label="Direction">
<option value="Mobile">Mobile development</option>
<option value="Node">Node.js development</option>
</optgroup>
</select>
<hr>
<!-- Multiple select -->
<select multiple>
<option value="Front-end">Front-end</option>
<option value="Back-end">Back-end</option>
</select>
<hr>
<!-- Different options -->
<select>
<option value="Front-end">Front-end</option>
<option value="Back-end" label="Back-end">
<option value="sel" selected>Selected</option>
<option value="dis" disabled>Disabled</option>
</select>
<hr>
Input Types Part 1
<!-- Text -->
<input type="text">
<hr>
<!-- Number -->
<input type="number"><br>
<input type="number" min="1" max="10"><br>
<input type="number" step="5"><br>
<hr>
<!-- Password -->
<input type="password">
<hr>
<!-- Range -->
<input type="range">
<hr>
<!-- Date -->
<input type="date">
<hr>
<!-- Color -->
<input type="color">
<hr>
<!-- Submit & reset buttons -->
<input type="submit"><br>
<input type="reset"><br>
<hr>
<!-- Submit & reset buttons with custom labels -->
<input type="submit" value="Submit form"><br>
<input type="reset" value="Reset form"><br>
<hr>
<!-- List of options -->
<input type="text" list="list">
<datalist id="list">
<option value="Front-end">
<option value="Back-end">
<option value="Full-stack">
</datalist>
<hr>
<!-- E-mail -->
<input type="email">
<hr>
<!-- URL -->
<input type="url">
<hr>
<!-- Input image -->
<input type="image" src="https://picsum.photos/300/300" alt="Just image">
<hr>
Input Types Part 2
<!-- Telephone -->
<input type="tel">
<hr>
<!-- Search -->
<input type="search">
<hr>
<!-- Local date & time -->
<input type="datetime-local">
<hr>
<!-- Month -->
<input type="month">
<hr>
<!-- Time -->
<input type="time">
<hr>
<!-- Week -->
<input type="week">
<hr>
<!-- Hidden -->
<input type="hidden" value="webDev">
<hr>
<!-- File -->
<input type="file"><br>
<input type="file" multiple><br>
<hr>
<!-- Checkbox -->
<input type="checkbox" value="option1"><br>
<input type="checkbox" value="option2"><br>
<input type="checkbox" value="option3"><br>
<hr>
<!-- Radio -->
<input type="radio" name="value" value="option1"><br>
<input type="radio" name="value" value="option2"><br>
<input type="radio" name="value" value="option3"><br>
<hr>
<!-- Checkbox with checked element -->
<input type="checkbox" value="option1" checked><br>
<input type="checkbox" value="option2"><br>
<input type="checkbox" value="option3"><br>
<hr>
<!-- Radio with checked element -->
<input type="radio" name="value" value="option1"><br>
<input type="radio" name="value" value="option2" checked><br>
<input type="radio" name="value" value="option3"><br>
<hr>
<!-- Checkbox with label -->
<label>
<input type="checkbox" value="option1" checked>
Front-end dev
</label><br>
<label>
<input type="checkbox" value="option2">
Back-end dev
</label><br>
<label>
<input type="checkbox" value="option3">
Full-stack dev
</label>
<hr>
<!-- Radio with label -->
<label>
<input type="radio" name="value" value="option1">
Front-end dev
</label><br>
<label>
<input type="radio" name="value" value="option2" checked>
Back-end dev
</label><br>
<label>
<input type="radio" name="value" value="option3">
Back-end dev
</label>
<hr>
Video & Audio
<!-- Audio -->
<audio src="example.mp3">
Your browser does not support the audio tag.
</audio>
<hr>
<!-- Video -->
<video width="320" height="240">
<source src="example.ogg" type="video/ogg">
<source src="example.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<hr>
<!-- Audio -->
<audio controls>
<source src="example.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>
<hr>
<!-- Video -->
<video controls width="320" height="240">
<source src="example.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<hr>
<video controls loop width="320" height="240">
<source src="example.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<hr>
<video controls autoplay width="320" height="240">
<source src="example.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<hr>
<video controls muted width="320" height="240">
<source src="example.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<hr>
<video controls poster="preview.png" width="320" height="240">
<source src="example.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<hr>
Common & Useful Attributes
<!-- ID -->
<h1 id="heading">Simple text</h1>
<hr>
<!-- Class -->
<p class="text idea">Simple text</p>
<p class="text">Simple text 2</p>
<hr>
<!-- Title -->
<h2 title="HyperText Markup Language">HTML</h2>
<hr>
<!-- Inline styles -->
<h2 style="color: red;">CSS</h2>
<hr>
<!-- Contenteditable -->
<h2 contenteditable="true">This content you can change</h2>
<hr>
<!-- Spellcheck -->
<textarea spellcheck="true" rows="10" cols="45" name="text">
This text cantain a cople misstakes
</textarea>
<hr>
<!-- Hidden -->
<h2 hidden>Hidden content</h2>
<hr>
<!-- Without tabindex -->
<input type="text" placeholder="name"><br>
<input type="text" placeholder="password"><br>
<input type="button" value="Submit"><br>
<hr>
<!-- With tabindex -->
<input type="text" placeholder="name" tabindex="1"><br>
<input type="text" placeholder="password" tabindex="3"><br>
<input type="button" value="Submit" tabindex="2"><br>
<hr>
<!-- Text direction -->
<h2 dir="rtl">Hello world!</h2>
<hr>
<!-- Language -->
<h2 lang="fr"><q>Hello world!</q></h2>
<h2 lang="en"><q>Hello world!</q></h2>
<hr>
CSS
Базовый синтаксис и применение стилей (Base Syntax & CSS Applying)
h1,
h2,
h3,
h4 {
text-transform: uppercase;
font-style: italic;
font-size: 16px;
border: 1px solid #000;
}
h2 {
color: green;
}
Code on jsfiddle
Простые селекторы (Simple Selectors)
* {
color: red;
}
p {
color: green;
}
.heading1 {
text-decoration: underline;
}
.heading2 {
text-transform: uppercase;
}
p.fz20 {
font-size: 20px;
}
#heading,
#heading2 {
font-size: 40px;
border: 1px solid #000;
}
q {
color: blue;
}
q.simple {
color: aqua;
}
body q.simple {
color: fuchsia;
}
Code on jsfiddle
Составные селекторы (Composite Selectors)
h1,
h2,
span {
color: red;
}
div p {
color: green;
}
div p span {
color: blue;
}
ul li > span {
font-weight: bold;
}
ul li + li {
color: aqua;
}
br ~ p {
font-size: 30px;
}
a[target] {
background-color: yellow;
}
a[target="_blank"] {
background-color: blue;
}
a[href^="http://123"] {
background-color: aqua;
}
a[href$=".jpg"] {
background-color: teal;
}
a[href*="link"] {
background-color: rebeccapurple;
}
Code on jsfiddle
Псевдоэлементы и псевдоклассы (Pseudo-elements & Pseudo-classes)
a {
color: black;
text-decoration: none;
}
a:hover {
color: red;
}
a:visited {
color: aqua;
}
a:active {
color: green;
}
a:focus {
font-weight: bold;
}
p::first-letter {
font-size: 40px;
}
p::first-line {
text-decoration: underline;
}
p::selection {
background-color: yellow;
color: red;
font-size: 40px;
}
h1::before {
content: "This is ";
text-transform: uppercase;
}
h1::after {
content: " channel";
color: red;
}
.list1 li:first-child {
color: blue;
}
.list1 li:last-child {
color: green;
}
.list2 li:nth-child(even) {
color: blue;
}
.list2 li:nth-child(odd) {
color: green;
}
.list3 li:nth-child(2) {
color: blue;
}
.list3 li:nth-child(3) {
color: green;
}
.list3 li:nth-child(3n + 1) {
text-transform: uppercase;
}
.list3 li:nth-child(4n + 2) {
border: 1px solid black;
}
.text span:first-of-type {
color: red;
}
.text span:last-of-type {
color: green;
}
.text span:nth-of-type(2) {
border: 1px solid black;
}
.list4 li:not(.item) {
border: 1px solid blue;
}
/* Selectors test
li ===> 1
#main .item ===> 110
h1 + *[href="test"] ===> 11
#test p ===> 101
li.item.main ===> 21
#test ===> 100
ul ol li.item ===> 13
ul li ===> 2
#test:not(.main) ===> 101
ul ol+li ===> 3
a:hover ===> 11
p:first-line ===> 2
h2 strong ===> 2
span.test ul li ===> 13
*/
Code on jsfiddle
Каскадность и наследование (Cascading & Inheritance)
/*
p {
background-color: green;
color: white;
padding: 10px;
}
.style1 {
background-color: aqua;
color: black;
border: none !important;
}
#style2 {
background-color: pink;
border: 2px solid black;
}
p {
background-color: gray;
}
*/
body {
color: red;
border: 1px solid black;
margin-bottom: 30px;
}
p {
border: inherit;
margin: inherit;
}
Code on jsfiddle
Блочная модель и отступы (Box Model, Padding & Margin)
span,
div {
border: 10px solid red;
/* margin: 10px;
padding: 10px; */
margin: 10px 20px;
/* padding: 10px 20px 30px 40px; */
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
/* inline, block, inline-block */
.test {
display: inline;
}
/* Doesn't work for inline element */
span {
width: 100px;
height: 100px;
}
.mar {
margin-top: 50px;
width: 100px;
height: 100px;
display: inline-block;
box-sizing: border-box;
}
Code on jsfiddle
Позиционирование и размеры (Positioning & Sizing)
body {
height: 1000px;
}
h4 {
border: 1px solid black;
position: absolute;
bottom: 150px;
}
.test {
border: 10px solid red;
/* width: 100px; */
height: 100px;
display: inline-block;
box-sizing: border-box;
position: sticky;
top: 20px;
right: 20px;
min-width: 100px;
max-width: 300px;
}
Code on jsfiddle
Единицы, переполнение и уровни элементов (Units, Overflow & z-index)
li {
font-size: 2rem;
}
.main {
font-size: 2px;
}
html {
font-size: 10px;
}
.overlay {
background-color: rgba(0, 0, 0, 0.5);
color: white;
width: 100px;
height: 100px;
box-sizing: border-box;
position: absolute;
width: 100vw;
height: 100vh;
top: 0;
left: 0;
/* width: calc(100px + 200px + 1rem); */
z-index: 1;
}
.modal {
border: 2px solid black;
width: 300px;
height: 100px;
background-color: cornflowerblue;
font-size: 20px;
color: white;
position: absolute;
z-index: 2;
overflow: hidden;
}
Code on jsfiddle
Плавающие элементы и очистка потока (Floating Elements & Clearfix)
.wrapper,
.wrapper2,
.item {
padding: 20px;
color: white;
}
.wrapper {
background-color: grey;
}
.wrapper:after {
content: "";
display: block;
clear: both;
}
.wrapper2 {
background-color: green;
}
.item {
float: left;
width: 150px;
}
.item1 {
background-color: crimson;
}
.item2 {
background-color: cyan;
}
.item3 {
background-color: blueviolet;
}
Code on jsfiddle
Шрифты и текст (CSS Font & Text styles)
/* @font-face {
font-family: "Roboto";
src: url("/fonts/Roboto-Regular.ttf") format("truetype"),
url("/fonts/Roboto-Regular.woff") format("woff"),
url("/fonts/Roboto-Regular.woff2") format("woff2"),
url("/fonts/Roboto-Regular.otf") format("opentype");
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: "RobotoBoldItalic";
src: url("/fonts/Roboto-BoldItalic.ttf") format("truetype"),
url("/fonts/Roboto-BoldItalic.woff") format("woff"),
url("/fonts/Roboto-BoldItalic.woff2") format("woff2"),
url("/fonts/Roboto-BoldItalic.otf") format("opentype");
font-weight: 900;
font-style: italic;
} */
@font-face {
font-family: "Roboto";
src: url("/fonts/Roboto-Regular.ttf") format("truetype");
font-weight: 500;
font-style: normal;
}
body {
font-family: "Roboto", Arial, Helvetica, sans-serif;
}
h1 {
color: blueviolet;
text-decoration: underline overline line-through none;
letter-spacing: 2px;
word-spacing: 10px;
line-height: 100px;
text-transform: uppercase;
text-align: center;
}
p {
text-align: justify;
text-indent: 20px;
}
Code on jsfiddle
Границы и тени (Borders & Shadows)
.example {
width: 100px;
height: 100px;
background-color: grey;
margin: 20px;
/* border-width: 10px;
border-style: solid;
border-color: red; */
border: 10px solid red;
border-right: none;
border-right-style: none;
border-bottom-width: 20px;
border-left-color: blue;
outline: 10px solid aqua;
}
button:focus,
input:focus {
outline: 2px solid aqua;
}
h1 {
text-shadow: 1px 2px 5px red, -1px -2px 5px green;
}
.shadow {
width: 100px;
height: 100px;
background-color: grey;
margin: 20px;
box-shadow: inset 1px 2px 5px blue, inset -1px -2px 5px aqua;
}
Code on jsfiddle
Скругление углов, списки и цвета (Border Radius, Lists & Colors)
.example {
width: 100px;
height: 100px;
background-color: grey;
margin: 20px;
/* border-radius: 50px 40px 30px 20px; */
/* border-radius: 20px/40px; */
border-top-left-radius: 50px;
border-top-right-radius: 40px;
border-bottom-right-radius: 30px;
border-bottom-left-radius: 20px;
}
ul li {
list-style-type: disc;
list-style-position: inside;
/* list-style-image: url(https://image.flaticon.com/icons/png/128/66/66738.png); */
}
h1 {
/* color: red; */
/* color: #ff0000; */
/* color: rgb(255, 0, 0); */
/* color: hsl(0, 100%, 50%); */
color: rgba(255, 0, 0, 0.5);
}
Code on jsfiddle
Отображение элементов и вендорные префиксы (Display vs. Visibility, Vendor Prefixes)
.first {
display: none;
}
.second {
/* visibility: hidden; */
/* opacity: 0; */
color: transparent;
}
Code on jsfiddle
Фон (Background)
body {
padding: 0;
margin: 0;
}
.wrapper {
min-height: 100vh;
width: 100%;
/* background-color: gainsboro;
background-image: url(https://images.pexels.com/photos/691571/pexels-photo-691571.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260);
background-size: cover;
background-size: auto 300px;
background-repeat: no-repeat;
background-position: 50% 50%;
background-attachment: fixed; */
background: url(https://seeklogo.com/images/C/css3-logo-8724075274-seeklogo.com.png)
center no-repeat,
url(https://images.pexels.com/photos/691571/pexels-photo-691571.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260);
}
Code on jsfiddle
Градиенты (Gradients)
body {
padding: 0;
margin: 0;
background-color: blue;
}
.wrapper {
min-height: 100vh;
width: 100%;
/* background-image: linear-gradient(45deg, red 10%, orange 50%, yellow 70%, green, aqua, blue); */
/* background-image: repeating-linear-gradient(45deg, yellow 25px, black 25px, black 50px, yellow 50px, yellow 75px, black 75px); */
background-image: repeating-radial-gradient(circle, aqua 20px, red 80px);
}
Code on jsfiddle
Фильтры (Filters)
body {
padding: 0;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
img {
transition: all 1s ease;
}
img:hover {
/* filter: blur(2px); */
/* filter: drop-shadow(5px 6px 4px rgba(0, 0, 0, 0.5)); */
/* filter: grayscale(80%); */
/* filter: brightness(150%); */
/* filter: contrast(150%); */
/* filter: hue-rotate(180deg); */
/* filter: hue-rotate(180deg); */
/* filter: invert(100%); */
/* filter: saturate(165%); */
/* filter: sepia(100%); */
/* filter: opacity(50%); */
/* filter: url(#toSvg); */
filter: blur(2px) brightness(150%);
}
Code on jsfiddle
Трансформации (Transform)
body {
padding: 0;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.wrapper {
border: 2px solid black;
height: 169px;
/* overflow: hidden; */
}
img {
transition: all 1s ease;
transform-origin: 50px 100px;
}
img:hover {
/* transform: rotate(360deg); */
/* transform: scale(0.2, 1.2); */
/* transform: scaleX(0.2); */
/* transform: scaleY(1.2); */
/* transform: scale(1.2); */
/* transform: translate(-50px, -80px); */
/* transform: translateX(50px); */
/* transform: translateY(80px); */
/* transform: skew(0, 45deg); */
/* transform: skewX(45deg); */
/* transform: skewY(45deg); */
/* transform: rotate(10deg) scale(1.2) skew(10deg); */
transform: rotate(90deg);
}
Code on jsfiddle
Плавные переходы (Transition)
body {
padding: 0;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.example {
border: 2px solid black;
width: 200px;
height: 200px;
background-color: aqua;
/* transition-duration: 500ms, 2s;
transition-property: transform, background-color;
transition-delay: 0, 10s;
transition-timing-function: linear; */
transition: all 1s ease .5s;
}
.example:hover {
background-color: red;
transform: scale(1.2);
}
Code on jsfiddle
Анимации (Animations)
body {
padding: 0;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.example {
border: 2px solid black;
width: 200px;
height: 200px;
background-color: aqua;
/* animation-name: myAnimation;
animation-duration: 5s;
animation-timing-function: linear;
/* animation-iteration-count: infinite;
animation-direction: reverse;
animation-fill-mode: forwards;
animation-delay: 3s; */
animation: bgChange 5s linear infinite, sizeChange 5s linear infinite;
}
.example:hover {
animation-play-state: paused;
}
@keyframes bgChange {
from { background-color: aqua; }
50% { background-color: red; }
to { background-color: green; }
}
@keyframes sizeChange {
from { transform: scale(1); }
50% { transform: scale(1.2); }
to { transform: scale(1); }
}
Code on jsfiddle
Таблицы и курсор (Tables & Cursor)
body {
padding: 0;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
table,
table * {
max-width: 600px;
border: 1px solid black;
border-collapse: separate;
/* border-spacing: 10px; */
caption-side: top;
min-width: 100px;
text-align: right;
vertical-align: baseline;
empty-cells: hide;
cursor: pointer;
}
.dis,
td {
pointer-events: none;
}
Code on jsfiddle
Текстовые эффекты и многоколоночный текст (Text Effects & Multi Columns Text)
body {
padding: 0;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.example {
font-size: 30px;
border: 1px solid black;
width: 150px;
min-height: 150px;
/* overflow: hidden; */
/* text-overflow: ellipsis; */
/* white-space: nowrap; */
word-wrap: break-word;
word-break: break-all;
writing-mode: vertical-rl;
}
.container {
column-count: 3;
column-rule: 1px solid black;
column-width: 300px;
column-gap: 100px;
}
Code on jsfiddle
Медиазапросы (Media queries)
body {
padding: 10px 30px;
margin: 0;
height: 100vh;
background-color: lightgrey;
font-size: 24px;
font-family: monospace;
}
@media screen and (min-width: 992px) and (max-width: 1200px) {
body {
background-color: aqua;
}
}
@media screen and (orientation: portrait) {
h1 {
display: none;
}
}
@media print {
body {
color: blue;
}
}
Code on jsfiddle
Стилизация плейсхолдера и скролла, CSS-спрайты (Placeholder, Scrollbar & Sprites)
body {
padding: 10px 30px;
margin: 0;
background-color: lightgrey;
font-size: 24px;
font-family: monospace;
}
input {
font-size: 24px;
padding: 5px 10px;
color: red;
}
::placeholder {
/* Chrome, Firefox, Opera, Safari 10.1+ */
color: blue;
opacity: 1; /* Firefox */
}
::-ms-input-placeholder {
/* Edge */
color: blue;
}
:-ms-input-placeholder {
/* IE 10-11 */
color: blue;
}
::-webkit-scrollbar {
width: 25px;
background: #101124;
}
::-webkit-scrollbar-track {
border: 5px solid rgba(255, 255, 255, 0.25);
box-shadow: inset 0 0 2.5px 2px rgba(0, 0, 0, 0.5);
}
::-webkit-scrollbar-thumb {
background: linear-gradient(45deg, #00ffa1, #00ffff);
border-radius: 15px;
}
button {
width: 200px;
height: 79px;
background-image: url(./23.png);
background-position: top;
background-size: cover;
text-indent: -9999px;
border: none;
background-color: transparent;
outline: grey;
}
button:hover {
background-position: center;
}
button:active {
background-position: bottom;
}
Code on jsfiddle
Links flex box
Основные понятия (Base Definitions)
Направление осей (Flex-direction)
Обёртка элементов и отступы (Flex-wrap & Gap)
Выравнивание вдоль главной оси (Alignment: justify-content)
Выравнивание вдоль поперечной оси (Alignment: align-items)
Многострочное выравнивание (Alignment: align-content)
Индивидуальное выравнивание элементов (Alignment: align-self)
Размеры элементов (Flexbox Sizing)
Определение порядка элементов (Order)
Вложенность. Обёртка элементов с размерами (Nesting. Flex-basis & Flex-wrap)
Практические примеры использования Flexbox (Practical examples) 1
Практические примеры использования Flexbox (Practical examples) 2
Практические примеры использования Flexbox (Practical examples) 3
Практические примеры использования Flexbox (Practical examples) 4
Algorithms
Binary search
Fast Linear search
Interpolation search
Linear search
Bubble sort Counting sort Marge sort Quick sort Radix sort
Binary search
Bubble sort Counting sort Marge sort Quick sort Radix sort
function search(arr, x) {
let i = 0;
let j = arr.length;
while (i !== j) {
let m = Math.floor((i + j) / 2);
if (x === arr[m]) return m;
if (x < arr[m]) j = m;
else i = m + 1;
}
return null;
}
let items = [2, 3, 5, 7, 11, 13, 17];
console.log(search(items, 1));
//print null
console.log(search(items, 7));
//print 3
console.log(search(items, 19));
//print null// * simplified speed test *
let i = 0;
items = Array(null, Array(10000)).map(() => ++i);
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) search(items, 7777);
let milliseconds = new Date() - start;
console.log("milliseconds is", milliseconds);
// about 5 millisecondsTry it in Playground
Fast Linear search
function search(arr, x) {
let i = 0;
let count = arr.length;
arr.push(x);
while (true) {
if (arr[i] == x) {
delete arr[count];
return i < count ? i : null;
}
i++;
}
}
let items = [2, 3, 5, 7, 11, 13, 17];
console.log(search(items, 1)); //print null
console.log(search(items, 7)); //print 3
console.log(search(items, 19)); //print null
// *** simplified speed test ***
let i = 0;
items = Array.apply(null, Array(10000)).map(() => ++i);
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) search(items, 7777);
let milliseconds = new Date() - start;
console.log("milliseconds is", milliseconds);
// about 313 millisecondsTry it in Playground
Interpolation search
//works when the array is sorted
function search(arr, x) {
let low = 0;
let high = arr.length - 1;
while (arr[low] < x && x < arr[high]) {
let mid = low + ((x - arr[low]) *
(high - low)) / (arr[high] - arr[low]);
if (arr[mid] < x) low = mid + 1;
else if (arr[mid] > x) high = mid - 1;
else return mid;
}
if (arr[low] == x) return low;
if (arr[high] == x) return high;
return null;
}
let items = [2, 3, 5, 7, 11, 13, 17];
console.log(search(items, 1)); //print null
console.log(search(items, 7)); //print 3
console.log(search(items, 19)); //print null
// *** simplified speed test ***
let i = 0;
items = Array.apply(null, Array(10000)).map(() => ++i);
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) search(items, 7777);
let milliseconds = new Date() - start;
console.log("milliseconds is", milliseconds);
// about 7 millisecondsTry it in Playground
Linear search
function search(arr, x) {
let i = 0;
let count = arr.length;
while (i < count) {
if (arr[i] == x) return i;
i++;
}
return null;
}
let items = [2, 3, 5, 7, 11, 13, 17];
console.log(search(items, 1));
//print null
console.log(search(items, 7));
//print 3
console.log(search(items, 19));
//print null
// *** simplified speed test ***
let i = 0;
items = Array.apply(null, Array(10000)).map(() => ++i);
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) search(items, 7777);
let milliseconds = new Date() - start;
console.log("milliseconds is", milliseconds);
// about 142 millisecondsTry it in Playground
Bubble sort
// Time Complexity O(n^2)// Space Complexity O(1)
function sort(arr) {
let items = arr.slice();
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
if (items[j] < items[i]) {
let tmp = items[j];
items[j] = items[i];
items[i] = tmp;
}
}
}
return items;
}
let items = [4, 1, 5, 3, 2];
let sortItems = sort(items);
// sortItems is [1, 2, 3, 4, 5]
console.log(sortItems); // *** simplified speed test ***
let i = 0;
items = Array.apply(null, Array(200)).map(() => ++i);
let tmp = items[5];
items[5] = items[6];
items[6] = tmp;
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) sort(items);
let milliseconds = new Date() - start;
console.log("milliseconds is", milliseconds);
// about 458 millisecondsTry it in Playground
Counting sort
// Time Complexity O(n^2)// Space Complexity O(1)
function sort(arr) {
let items = new Array(arr.length);
let min = Math.min.apply(Math, arr);
let max = Math.max.apply(Math, arr);
let counts = Array(max - min + 1).fill(0);
for (let x of arr) {
counts[x - min]++;
}
let total = 0;
for (let i = min; i <= max; i++) {
let oldCount = counts[i - min];
counts[i - min] = total;
total += oldCount;
}
for (let x of arr) {
items[counts[x - min]] = x;
counts[x - min]++;
}
return items;
}
let items = [4, 1, 5, 3, 2];
let sortItems = sort(items);
// sortItems is [1, 2, 3, 4, 5]
console.log(sortItems); // *** simplified speed test ***
let i = 0;
items = Array.apply(null, Array(200)).map(() => ++i);
let tmp = items[5];
items[5] = items[6];
items[6] = tmp;
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) sort(items);
let milliseconds = new Date() - start;
console.log("milliseconds is", milliseconds);
// about 161 millisecondsTry it in Playground
Marge sort
// Time Complexity O(n log(n)))// Space Complexity O(n)
function sort(items) {
let result = [];
if (items.length === 1) return items;
let lLeft = Math.floor(items.length / 2);
let lRight = items.length - lLeft;
let left = sort(items.slice(0, lLeft));
let right = sort(items.slice(lLeft, items.length));
let l = 0;
let r = 0;
while (l < lLeft && r < lRight) {
if (left[l] < right[r]) {
result.push(left[l++]);
} else {
result.push(right[r++]);
}
}
while (l < lLeft) {
result.push(left[l++]);
}
while (r < lRight) {
result.push(right[r++]);
}
return result;
}
let items = [4, 1, 5, 3, 2];
let sortItems = sort(items);
// sortItems is [1, 2, 3, 4, 5]
console.log(sortItems);
// *** simplified speed test ***
let i = 0;
items = Array.apply(null, Array(200)).map(() => ++i);
let tmp = items[5];
items[5] = items[6];
items[6] = tmp;
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) sort(items);
let milliseconds = new Date() - start;
console.log("milliseconds is", milliseconds);
// about 589 millisecondsTry it in Playground
Quick sort
// Time Complexity from O(n log(n)) to O(n^2)// Space Complexity O(log(n))
function doSort(items, fst, lst) {
if (fst >= lst) return;
let i = fst;
let j = lst;
let x = items[Math.floor((fst + lst) / 2)];
while (i < j) {
while (items[i] < x) i++;
while (items[j] > x) j--;
if (i <= j) {
let tmp = items[i];
items[i] = items[j];
items[j] = tmp;
i++;
j--;
}
}
doSort(items, fst, j);
doSort(items, i, lst);
}
function sort(arr) {
let items = arr.slice();
doSort(items, 0, items.length - 1);
return items;
}
let items = [4, 1, 5, 3, 2];
let sortItems = sort(items);
// sortItems is [1, 2, 3, 4, 5]
console.log(sortItems);
// *** simplified speed test ***
let i = 0;
items = Array.apply(null, Array(200)).map(() => ++i);
let tmp = items[5];
items[5] = items[6];
items[6] = tmp;
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) sort(items);
let now = new Date();
let milliseconds = now - start;
console.log("milliseconds is", milliseconds);
// about 143 millisecondsTry it in Playground
Radix sort
// Time Complexity O(nk)// Space Complexity O(n+k)
function listToBuckets(items, cBase, i) {
let buckets = Array.apply(null, Array(cBase)).map(function () {
return [];
});
let pBase = Math.pow(cBase, i);
for (let x of items) {
//Isolate the base-digit from the number
let digit = Math.floor(x / pBase) % cBase;
//Drop the number into the correct bucket
buckets[digit].push(x);
}
return buckets;
}
function bucketsToList(buckets) {
let result = [];
for (let bucket of buckets) {
//add the numbers in a bucket
//sequentially to the returned array
result = result.concat(bucket);
}
return result;
}
function sort(arr, cBase = 10) {
let maxVal = Math.max(Math, arr);
let i = 0;
while (Math.pow(cBase, i) <= maxVal) {
arr = bucketsToList(listToBuckets(arr, cBase, i));
i++;
}
return arr;
}
let items = [4, 1, 5, 3, 2];
let sortItems = sort(items);
// sortItems is [1, 2, 3, 4, 5]
console.log(sortItems);
// *** simplified speed test ***
let i = 0;
items = Array.apply(null, Array(200)).map(() => ++i);
let tmp = items[5];
items[5] = items[6];
items[6] = tmp;
let count = 10000;
let start = new Date();
for (i = 0; i < count; i++) sort(items);
let milliseconds = new Date() - start;
console.log(milliseconds);
// about 405 millisecondsTry it in Playground
GIT commands
git init --------------------------------Create a new local repo
git diff --------------------------------Show changes not yet staged
git status ------------------------------List new or unmodified files
git add -------------------------------- Stage all changed files
git add <file> --------------------------Stage a file
git commit -a ---------------------------Commit all local changes in tracked files
git commit ------------------------------Commit previously staged changes
git commit --amend ----------------------Change the last commit
git log -------------------------------- Show full change history
git checkout <branch> -------------Switch to a branch and update working directory
git branch <new-branch> -----------Create a new branch
git branch -d <branch> ------------Delete a branch
git fetch <remote> ----------------Fetch all branches from remote repo
git pull <remote> <branch> --------Fetch remote version of a branch and update local branch
git push <remote> <branch> --------Push the committed changes to a remote repository
git merge <branch> ----------------Merge the specified branch into the current branch
git rebase <branch> --------------Rebase your current HEAD onto the specified branch
git revert <commit> ---------------Creates a new commit to revert the specified commit
Colors
Red Luminance
Learning
Lessons
Полный курс по JavaScript + React
1. Как проходить данный курс
2. Почему этот курс?
3. Условные обозначения и материалы
4. Настройка рабочего пространства
5. Про редакторы кода и учебники
6. Как работать с JSHint
7. Что такое JS и как его подключить к странице
8. Про упражнения и дополнительные уроки
9. Переменные и строгий режим
10. (д) Правила и типы названия переменных
11. Классификация типов данных в JavaScript
12. (д) Разница между объектами и массивами и неочевидные синтаксические возможности
13. Простое общение с пользователем
14. Интерполяция (ES6)
15. Операторы в JS
16. Учимся работать с системой контроля версий Git и с сервисом GitHub
17. Как работать с GitHub с разных компьютеров, gitignore и Git Kraken
18. (д) Сетевые протоколы. Подключение компьютера к аккаунту Github через SSH
19. Практика, ч.1. Начинаем создавать приложение
20. Условия
21. (д) Логические операторы
22. Циклы
23. (д) Цикл в цикле и метки
24. Практика, ч2. Применяем условия и циклы
25. Функции, стрелочные ф-ции (ES6)
26. (д) Еще раз про аргументы функций
27. (д) Про важность return
28. Методы и свойства строк и чисел
29. Практика , ч3. Используем функции
30. (д) Метод trim()
31. Callback- функции
32. Объекты, деструктуризация объектов (ES6)
33. Массивы и псевдомассивы
34. (*) Алгоритмы в целом и в JavaScript
35. Передача по ссылке или по значению, Spread оператор (ES6-ES9)
36. Основы ООП, прототипно-ориентированное наследование
37. Практика , ч4. Используем объекты
38. Отлавливаем ошибки в своем коде при помощи консоли разработчика. Breakpoints
39. Динамическая типизация в JS
40. Замыкание и лексическое окружение
41. Задачи с собеседований на понимание основ
42. Получение элементов со страницы
43. Действия с элементами на странице
44. Практика. Задание на отработку действий со страницей
45. События и их обработчики
46. Навигация по DOM - элементам, data-атрибуты, преимущество for/of
47. Рекурсия
48. Практика. Используем события на странице проекта
49. События на мобильных устройствах
50. Async, defer, динамические скрипты
51. Ресурсы для оттачивания навыков программирования
52. Про дополнительную информацию по основам
53. (д) Оператор нулевого слияния (Nullish, ??) ES11
54. (д) Оператор опциональной цепочки (?.) ES11
55. (д) Живые коллекции и полезные методы
56. (д) Тип данных Symbol
57. (д) Дескрипторы свойств и полезные методы объектов
58. (*) Итерируемые конструкции
59. (*) Map
60. (*) Set
61. (*) BigInt
62. Про что будет этот модуль
63. ClassList и делегирование событий
64. Создаем табы в новом проекте
65. Скрипты и время их выполнения. setTimeout и setInterval
66. (д) Сборщик мусора и утечки памяти
67. (*) WeakMap и WeakSet
68. Работа с датами
69. Создаем таймер обратного отсчета на сайте
70. (*) Обработка прошедшей даты
71. Параметры документа, окна и работа с ними
72. Создаем модальное окно
73. Модификации модального окна
74. (д) MutationObserver, ResizeObserver и contenteditable
75. Функции-конструкторы
76. Контекст вызова. This
77. Классы (ES6)
78. Где отслеживать информацию о новых стандартах
79. Используем классы в реальной работе
80. Rest оператор и параметры по умолчанию (ES6)
81. Локальные сервера
82. JSON формат передачи данных, глубокое клонирование объектов
83. AJAX и общение с сервером
84. Реализация скрипта отправки данных на сервер
85. Красивое оповещение пользователя
86. Promise (ES6)
87. Fetch API
88. Методы перебора массивов
89. Подробно про npm и проект. JSON-server
90. Получение данных с сервера. Async/Await (ES8)
91. Дополнительно: Что такое библиотеки. Библиотека axios
92. Создаем слайдер на сайте, вариант 1
93. Создаем слайдер на сайте, вариант 2
94. Создаем навигацию для слайдов
95. Как сохранить данные без БД. Работа с localStorage
96. Регулярные выражения
97. Создаем калькулятор на сайте, часть 1
98. Создаем калькулятор на сайте, часть 2
99. Геттеры и сеттеры (свойства объектов)
100. Инкапсуляция
101. Прием модуль, как и зачем его использовать
102. Webpack. Собираем наш проект
103. ES6 Modules
104. Собираем наш проект и фиксим баги
105. Формируем портфолио на GitHub
106. Ошибки. Как избежать “поломки” своего кода
107. (д) Создание своих ошибок
108. Как превратить код ES6+ в старый формат ES5. Babel, Core.js
109. Современные библиотеки и фрэймворки
110. Библиотека Jquery
111. Функции-генераторы
112. JS анимации, requestAnimationFrame
113. (*) Web Animations API
114. Event loop, подробная работа асинхронных и синхронных операций
115. Макро и микрозадачи
116. Работаем с готовым кодом
117. Какие проекты можно придумать и реализовать самостоятельно
118. Введение
119. Что такое реакт, зачем он нам и почему не обычный JS
120. Фундаментальные принципы Реакта
121. Create React App - создаем свое приложение
122. Работаем с JSX-препроцессором, ограничения в нем
123. Элементы и компоненты
124. Строгий режим
125. Strict Mode и React 18+
126. Создание нового проекта
127. Свойства компонентов
128. Практика свойств на проекте
129. Работа со списками и алгоритм согласования
130. Состояния компонентов
131. Самостоятельное задание на работу с состояниями
132. События в React и вспоминаем this
133. Практика состояний на проекте
134. Работа с формами, управляемые и неуправляемые компоненты
135. Иммутабельность состояния и собственные события
136. Практика. Подъём состояния
137. React-фрагменты
138. Практика. Реализуем поиск и фильтры
139. Семантика и доступность контента
140. Стили в React. Inline Styles
141. Стили в React. CSS и SASS/SCSS
142. Стили в React. Динамические классы и стили
143. Стили в React. Styled Components
144. Стили в React. Готовые библиотеки компонентов со стилями
145. Поля классов и static
146. Заключение модуля
147. Что такое API и как работают реальные приложения
148. Новый проект и работа с сервером
149. Трансформация данных и компонент со случайным персонажем
150. Хороший тон приложения (спиннер, ошибки...)
151. Жизненный цикл компонентов
152. Практика с жизненным циклом, componentDidUpdate
153. Предохранители (Error Boundaries)
154. Пагинация данных (дозагрузка персонажей)
155. Проверка типов с помощью PropTypes
156. Вставка элементов через props.children
157. Специализация и наследование
158. Render-props паттерн
159. Что такое ref и зачем он нужен
160. Порталы
161. “Бандлинг” и выгрузка проекта на сервер
162. Введение в хуки
163. useState
164. useEffect
165. useCallback
166. useMemo
167. useRef
168. Практика. Перепишем весь проект на хуки
169. Создание собственных хуков
170. Практика собственных хуков на проекте
171. Что такое batching и как он работает в React 18+
172. (д) useTransition, useDeferredValue и другие нововведения React 18+
173. Навигация в приложении, React Router v5+
174. React Router v6+
175. Практика создания динамических путей
176. Динамические импорты и React.lazy
177. React.memo, Pure Component и оптимизация скорости работы приложения
178. React Context и useContext
179. useReducer
180. Компоненты высшего порядка (HOC)
181. Библиотеки и экосистема React
182. React Transition Group
183. Formik, Yup и работа с формами любой сложности, часть 1
184. Formik, Yup и работа с формами любой сложности, часть 2
185. Разбор домашнего задания
186. SEO-оптимизация веб-приложений, React-helmet
187. Принцип конечного автомата (FSM, Finite-state machine) и +1 подход к состояниям
188. Разбираем ошибки сторонних библиотек и проблему с фокусом
189. Основные принципы Redux. Теория
190. Основные принципы Redux. Практика
191. Чистые функции
192. Оптимизация через actionCreators и bindActionCreator
193. Добавим React в проект
194. Соединяем React и Redux при помощи connect
195. Соединяем React и Redux при помощи хуков
196. Redux devtools
197. Правило названия action и домашнее задание (мини-экзамен)
198. Разбор самых сложных моментов
199. Комбинирование reducers и красивые селекторы. CreateSelector()
200. Про сложность реальной разработки
201. Store enhancers
202. Middleware
203. Redux-thunk
204. Redux Toolkit: configureStore()
205. Redux Toolkit: createAction()
206. Redux Toolkit: createReducer()
207. Redux Toolkit: createSlice()
208. Redux Toolkit: createAsyncThunk()
209. Redux Toolkit: createEntityAdapter()
210. Подводные камни домашнего задания
211. Про разные структуры проектов и закрепление материала
212. Redux Toolkit: RTK Query
213. Что дальше?
214. Эпилог
215. Вступление к практическому курсу
216. Настраиваем сборку проекта и разбираемся с ТЗ
217. Работа с модальными окнами
218. Работа с табами (вкладками) на странице
219. Работа с формами отправки данных
220. Работа с формой-калькулятором, часть 1
221. Работа с формой-калькулятором, часть 2
222. Работа с таймером
223. Реализуем модуль с показом изображений
224. Улучшаем наш проект (анимации, правильное поведение overflow)
42
const box = document.getElementById('box');
console.log(box);
const btns = document.getElementsByTagName('button');
console.log(btns[0]);
const circles = document.getElementsByClassName('circle');
console.log(circles);
const hearts = document.querySelectorAll('.heart');
hearts.forEach(item => {
console.log(item);
});
const oneHeart = document.querySelector('.heart');
console.log(oneHeart);
Lesson code on jsfiddle
43
const box = document.getElementById('box'),
btns = document.getElementsByTagName('button'),
circles = document.getElementsByClassName('circle'),
hearts = document.querySelectorAll('.heart'),
oneHeart = document.querySelector('.heart'),
wrapper = document.querySelector('.wrapper');
box.style.backgroundColor = 'blue';
box.style.width = '500px';
box.style.cssText = 'background-color: blue; width: 500px; '
btns[1].style.borderRadius = '100%';
circles[0].style.backgroundColor = 'red';
for (let i = 0; i < hearts.length; i++) {
hearts[i].style.backgroundColor = 'blue';
}
hearts.forEach(item => {
item.style.backgroundColor = 'blue';
});
const div = document.createElement('div');
const text = document.createTextNode('Тут был я');
div.classList.add('black');
wrapper.append(div);
wrapper.appendChild(div);
wrapper.prepend(div);
hearts[0].before(div);
hearts[0].after(div);
wrapper.insertBefore(div, hearts[1]);
hearts[0].after(div);
wrapper.insertBefore(div, hearts[1]);
circles[0].remove();
wrapper.removeChild(hearts[1]);
hearts[0].replaceWith(circles[0]);
wrapper.replaceChild(circles[0], hearts[0]);
div.innerHTML = "Hello World
";
div.textContent = "Hello World
";
div.insertAdjacentHTML("afterend", 'Hello
');
45
const btn = document.querySelectorAll('button'),
overlay = document.querySelector('.overlay');
// btn.onclick = function() { // alert('Click');
// };
// btn.onclick = function() { alert('Second click'); // };
// let i = 0;
const deleteElement = (e) => {
console.log(e.target);
console.log(e.type);
// i++;
// if (i == 1) {
// btn.removeEventListener('click', deleteElement);
// }
};
btn.addEventListener('click', deleteElement);
overlay.addEventListener('click', deleteElement);
const link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault();
console.log(event.target);
});
Lesson code on jsfiddle
46
document.head;
document.documentElement;
document.body.childNodes;
document.body.firstChild;
document.body.firstElementChild;
document.body.lastChild;
document.querySelector('#current').parentNode;
document.querySelector('#current').parentElement;
document.querySelector('[data-current="3"]').nextElementSibling;
for (let node of document.body.childNodes) {
if (node.nodeName == '#text') {
continue;
}
console.log(node);
}
Lesson code
49
// touchstart
// touchmove
// touchend
// touchenter
// touchleave
// touchcancel
window.addEventListener('DOMContentLoaded', () => {
const box = document.querySelector('.box');
box.addEventListener('touchstart', (e) => {
e.preventDefault();
console.log('Start');
});
box.addEventListener('touchmove', (e) => {
e.preventDefault();
console.log('Move');
});
box.addEventListener('touchend', (e) => {
e.preventDefault();
console.log('End');
});
});
// touches
// targetTouches
// changedTouches
Lesson code
50
function loadScript(src) {
const script = document.createElement('script');
script.src = src;
script.async = false;
document.body.append(script);
}
loadScript('js/test.js');
loadScript('js/some.js');
------------------------------------
<script async src="async-script.js"></script>
<script defer src="deferred-script1.js"></script>
<script defer src="deferred-script2.js"></script>
Lesson code
Fast cheats
CSS
JavaScript