var variable = 10 //global let letvariable = 100 //available only inside curly braces const COLOR = 'blue' //the value cannot be changed. You can change obj and array by referring to the element inside
array = [1,1,2,4,8] array.push(12)
obj = {a: 42} obj.name = "Name" let job = 'Fullstack' let person1 = { age: 30, 'name': 'Имя', [a + b]: '', //dynamic key job, //name of key = value print: () => 'Person', //no this // toString: function(){ in new version world "function" can be delete toString(){ // return `${this.age} ${this.name}` return Object .keys(this) //array keys .filter( key => key != 'toString') //filter by key, not include function .map(key => this[key]) .join(' ') } } const first = {a: 1} const second = {b: 1} // Methods // determines if two values are the same type Object.is(10, 10) // join, firste parametr {} for not to change "first" and "second" Object.assign({},first, second, {new: 'new'}) // conver to array Object.entries(person) // array keys Object.keys(person) //array value Object.values(person)
// function function summ(a, b){ return a + b } // arrow function let sum = (a, b) => { return a + b } function cube(a){ return a ** 3 //exponentiation } // arrow function. The quotes in the passed variables are optional if there is one parameter. If only one returned line of executable code, you can shorten the syntax let cub = a => a ** 3 // default parameters function compute(a, b = 10){ console.log(a + b) }
function log(){ a = 10 console.log(this) } // The arrow function does not have its own context, she does not create it. She have context level up let arrowLog = () => console.log(this) const person = { age: 20, weight: 72, log: log, arrowLog: arrowLog, delayLog: function () { let self = this //In this way, you can pass the this context if you do not use an arrow function setTimeout(function() { console.log(self.age) }, 500) }, delayLog2: function () { setTimeout(() => console.log(this.age), 500) } } // output object person person.log() // output window person.arrowLog() // this will be the context of the Timeout function, so we defined the constant self person.delayLog() // Using an arrow function the context of the person object person.delayLog2()
let title = "Main page" // when using back brackets, you can embed a variable and use functions through $ {}, you can use other quotes inside, gaps are not removed let isVisible = () => Math.random() > 1 let template = ` ${isVisible ? 'Visible' : ''} ${title}` // Method const str = 'Hello' // What characters does the string start with str.startsWith('He') // What characters does the string end str.endsWith('lo') // search in string str.includes('llo') // remove spaces around str.trim()
Visible
//Rest // an array of all passed arguments function average(){ Array.from(arguments) } function averageRest(a, ...args){ args } // Spread let arrayS = [1, 1, 2, 3, 5] // converts the array to individual elements Math.max(...arrayS) // used to be written like this Math.max.apply(null, arrayS) // example of adding an element to an array arrayS = [...arrayS, 8]
// for array // let a = arrayS[0] // let b = arrayS[1] let [a, b = 1, , ...c] = arrayS // for object let adress = { country: 'Russia', street: 'Street', city: 'City', get: function(){ return this.country; } } // you need the names to match, you can set your name through : let {country, street = 'Street', city: cityNewName, get,...all} = adress // you can also pass a function, but it uses this, so we additionally pass the adress object get.call(adress) // copy of the object with changing one of the fields and adding new ones let newAdress = {...adress, street: 'Street', code: 17}
// files in js it is modules // file module.js export const COLOR = "#FFF" export function compute (a, b) { return a + b } export default { Log(){ console.log('log'); } } // file index.js import {COLOR, compute} from './module.js' // to import export default, you need not specify variables in brackets import Logger,{COLOR, compute} from './module.js' // import everything from the module import * as LoggerModule from './moule.js'
user = new Person('Name') console.log(user.__proto__ === Person.prototype) class Programmer extends Person { constructor (name, job) { super(name) //accessing a variable from the parent class this._job = job } greet () { super.greet() //calling the parent method from the parent class console.log(`Hi ${this.name}`) } //getter get job() { return this._job.toUpperCase() } //setter is used for validation set job(job) { if(job.length < 2){ throw new Error('String less 2 symbol') } this._job = job } } user = new Programmer('Имя', 'Проф') console.log(user.job) user.job = 'Работа' console.log(user.job) // Static class Util { static average(...args){ return args.reduce((acc, i) => acc += i, 0) / args.length } }
let symbol = Symbol('demo') https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Symbol
// li by object for (let key in obj) { }
// Iterator //Iterators can be used in loops "for of" const array11 = [1,2,3,4,5] const iter = array11[Symbol.iterator]() // console.log(iter.next()) for (let item of array11) { // console.log(item) } for (let key in array11) { } const country2 = { values: ['ru', 'en'], [Symbol.iterator] () { let i =0 return { next: () => { const value = this.values[i] i++ return { done: i > this.values.length, value } } } } } // Generator // Creating an iterator function *gen (num = 4) { for(let i = 0; i < num; i++){ try{ yield i } catch (e){ console.log(e) } } } const iter2 = gen(3) console.log(iter2.next()) console.log(iter2.throw('Error')) for(let i of gen(5)){ console.log(i) }
// convenient tools that allows you to work with asynchronous code const promise = new Promise ( (resolve, reject) => { setTimeout( () => { resolve('ok') //success reject('no') //error }, 500) }) promise.then(data => console.log(data)) //will work after executing the code //dynamic delay const delay = ms => new Promise( (resolve, reject) =>{ setTimeout( (data) => { resolve(`Done ${ms}`) reject(`Error ${ms}`) //f an error needs to be thrown, it is caught in the catch. To work, you need to put before resolve }, ms) } ) delay(1000) .then(data => console.log(data)) //works after execution .then(data => delay(2000)) .then(data => console.log(data)) .catch( err => console.log(err)) //catch error .finally( data => console.log('Final')) //Called anyway at the end // New syntax // asynchronous function // await delay(1000) the same delay(1000).then(data => ) We work at a flat level, there is no immersion in internal callbacks async function asyncDelay () { try{ //for error handling const data = await delay(1000) console.log(data) } catch(e) { console.log('Error', e) } } asyncDelay() // global promis // Waits for all promises to complete Promise.all([ delay(1000), delay(500), delay(1000) ]).then(data => console.log(data)) //Waiting for the fastest to finish Promise.race([ delay(1000), delay(500), delay(1000) ]).then(data => console.log(data))
// map object analog but more advanced const map = new Map( [['a',1]] //type of entries passed in, array in array ) // console.log(map.get('a')) //accessing elements via get method map.set('b', 2).set('c', 10) //addition map.clear() //clear map.has() //checking if there is a key map.delete() //delete by key map.size //amount of elements map.entries() //entries map.keys() //keys map.values() // values // Set it is array analog //emoves duplicates const set = new Set([1, 1, 2, 3, 5, 8, 8]) set.add() //addition set.clear() //clear set.has() //checking if there is a key set.delete() //delete by key set.size //amount of elements set.entries() //entries set.keys() //keys set.values() // values console.log(set)
class Student{ constructor(name){ this.name = name } greet () { console.log(`Hi ${this.name}`) } } class ProtoStudent{ university = 'Oxford' } // the third parameters are passed what prototype the object will have let student = Reflect.construct(Student, ['Name'], ProtoStudent) console.log(student.__proto__ === ProtoStudent.prototype) let student2 = Reflect.construct(Student, ['Name']) // method launch Reflect.apply(student2.greet, {name: 'tester'}, []) // list keys console.log(Reflect.ownKeys(student2)) // Block modification of an object Reflect.preventExtensions(student2) // Checking whether the object is blocked or not console.log(Reflect.isExtensible(student2))
// This is a class that allows you to add traps to objects. // For example, you can make a validator for getters and setters and then use it for any objects const validator = { get(target, prop) { return prop in target ? target[prop] : `Prop ${prop} no in object` }, set(target, prop, value){ if(value.length > 2){ Reflect.set(target, prop, value) }else{ console.log(`The length must be more than 2 characters. Now $ {value.length} characters`) } } } const form = { login: 'tester', password: '12345' } // the first parameter is the object to be monitored const formProxy = new Proxy(form, validator) console.log(formProxy.login) function log(message){ console.log('[log]', message) } const proxy = new Proxy(log, { // target - the function we want to call // thisArg - context // argArray - params apply(target, thisArg, argArray){ if(argArray.length === 1){ Reflect.apply(target, thisArg, argArray) }else{ console.log('The number of arguments does not match') } } }) // Call proxy, identical to log proxy('1')
Get special offers on the latest developments from Front.
Be the lucky user to earn 100$ bonus now!