function createCounter() {
let count = 0;
return {
increment() {
return ++count;
},
reset() {
const oldCount = count;
count = 0;
return oldCount;
}
};
}
const counterA = createCounter();
const counterB = createCounter();
counterA.increment();
counterA.increment();
counterB.increment();
const result = counterA.reset() + counterB.reset();
console.log(result);
Ответ:
Please open Telegram to view this post
VIEW IN TELEGRAM
const user = {
profile: {
settings: {
theme: 'dark',
notifications: null
}
}
};
const result1 = user?.profile?.settings?.theme;
const result2 = user?.profile?.settings?.notifications?.email;
const result3 = user?.profile?.preferences?.language ?? 'en';
const result4 = user?.profile?.settings?.notifications?.push?.('test');
console.log(result1, result2, result3, result4);
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
const original = {
name: 'Sarah',
hobbies: ['reading', 'coding'],
address: { city: 'Portland', zip: 97201 }
};
const shallow = { ...original };
const deep = JSON.parse(JSON.stringify(original));
shallow.name = 'Emma';
shallow.hobbies.push('hiking');
shallow.address.city = 'Seattle';
deep.hobbies.push('swimming');
deep.address.zip = 98101;
console.log(original.hobbies.length, original.address.city);
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
var str="My name is John";
var words1=str.split(" ",3);
console.log("words1:",words1);
var words2=str.split(" ",5);
console.log("words2:",words2);
Ответ:
words1:[ 'My', 'name', 'is' ]
words2:[ 'My', 'name', 'is', 'John' ]
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
class SimpleObservable {
constructor(subscribeFn) {
this.subscribeFn = subscribeFn;
}
subscribe(observer) {
return this.subscribeFn(observer);
}
}
const obs = new SimpleObservable(observer => {
observer.next('first');
observer.next('second');
observer.complete();
});
const results = [];
obs.subscribe({
next: val => results.push(val),
complete: () => results.push('done')
});
console.log(results.join('-'));
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
❗️Что будет на выходе:
Ответ:Script Start, Async Start, Script End, Timeout 1, Async End, Timeout 2
JavaScript test | #JavaScript
async function asyncFunc() {
console.log('Async Start');
await new Promise(resolve => setTimeout(resolve, 100));
console.log('Async End');
}
console.log('Script Start');
asyncFunc();
setTimeout(() => console.log('Timeout 1'), 50);
setTimeout(() => console.log('Timeout 2'), 150);
console.log('Script End');
Ответ:
const numbers = [1, 2, 3, 4, 5];
const result = numbers
.map(n => n * 2)
.filter(n => n > 5)
.reduce((acc, n, index) => {
acc.sum += n;
acc.indices.push(index);
return acc;
}, { sum: 0, indices: [] });
console.log(result.sum);
console.log(result.indices);
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
const user = {
name: 'Sarah',
age: 25,
getName() { return this.name; },
getAge: () => this.age
};
const methods = {
regular: user.getName,
arrow: user.getAge
};
console.log(methods.regular());
console.log(methods.arrow());
console.log(user.getName());
console.log(user.getAge());
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
const data = '{"users": [{"name": "Sarah", "age": 25}, {"name": "Mike", "age": null}]}';
try {
const parsed = JSON.parse(data);
const result = parsed.users.map(user => {
return user.age ?? 'unknown';
});
console.log(result.join(' - '));
} catch (error) {
console.log('Parse error occurred');
}
const invalidJson = '{"name": "John", age: 30}';
try {
JSON.parse(invalidJson);
console.log('Success');
} catch {
console.log('Invalid');
}
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
❗️Что будет на выходе:
Ответ:[ 1, 3, 5, 7, 9 ]
15
[ 1, 2, 3 ]
JavaScript test | #JavaScript
var arr=[1,2,3,4,5];
console.log(arr.map((prev,curr)=>prev+curr));
console.log(arr.reduce((a,b)=>a+b));
console.log(arr.filter((a,b)=> (a + b) <= 5));
Ответ:
15
[ 1, 2, 3 ]
JavaScript test | #JavaScript
class Logger {
log(msg) {
return `[LOG]: ${msg}`;
}
}
class Formatter {
format(text) {
return text.toUpperCase();
}
}
class Service {
constructor(logger, formatter) {
this.logger = logger;
this.formatter = formatter;
}
process(data) {
const formatted = this.formatter.format(data);
return this.logger.log(formatted);
}
}
const service = new Service(new Logger(), new Formatter());
console.log(service.process('hello world'));
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
try {
try {
// Creating a custom error type
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
const fn = () => {
throw new CustomError("Something went wrong");
};
try {
fn();
} catch (e) {
throw new TypeError("Type error occurred");
}
} catch (e) {
console.log(e instanceof Error, e.name, e instanceof TypeError);
}
} catch (e) {
console.log("Outer catch", e.message);
}
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
function X() {}
X.prototype.getValue = function() {
return this.value;
};
function Y() {
this.value = 42;
}
Y.prototype = Object.create(X.prototype);
Y.prototype.constructor = Y;
var y = new Y();
console.log(y.getValue());
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
function mystery() {
try {
throw new Error('Oops');
return 'A';
} catch (err) {
return 'B';
} finally {
return 'C';
}
}
function wrapper() {
try {
return mystery();
} finally {
console.log('D');
}
}
console.log(wrapper());
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] ? `<span>${values[i]}</span>` : '';
return result + str + value;
}, '');
}
const language = 'JavaScript';
const years = 10;
const result = highlight`I have been coding in ${language} for ${years} years`;
console.log(result);
Ответ:
Please open Telegram to view this post
VIEW IN TELEGRAM
let a = 1;
let b = new Number(1);
let c = '1';
console.log(a == b);
console.log(a === b);
console.log(b == c);
Ответ:
Please open Telegram to view this post
VIEW IN TELEGRAM
This media is not supported in your browser
VIEW IN TELEGRAM
Новая сетка Telegram-каналов CodeGuard — собрана для твоего роста в IT!
📱 Front и топ инсайды IT-сферы
t.me/CodeGuard_SciencePop
🖥 Книги, курсы, утилиты и гайды
t.me/CodeGuard_Academy
📱 Обучение и задачи по Python
t.me/CodeGuard_Python
🤔 InfoSec & Хакинг
t.me/CodeGuard_PySec
👩💻 Знания и навыки Linux & Bash
t.me/CodeGuard_Linux
💼 Фриланс, карьера и работа IT
t.me/CodeGuard_VacancyIT
📌 Инструменты, гайды, шпаргалки, тренажеры и практические гайды.
t.me/CodeGuard_SciencePop
t.me/CodeGuard_Academy
t.me/CodeGuard_Python
t.me/CodeGuard_PySec
t.me/CodeGuard_Linux
t.me/CodeGuard_VacancyIT
Please open Telegram to view this post
VIEW IN TELEGRAM
class EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
this.events[event] = this.events[event] || [];
this.events[event].push(callback);
return this;
}
emit(event, data) {
if (this.events[event]) {
this.events[event].forEach(cb => cb(data));
}
return this;
}
}
const emitter = new EventEmitter();
emitter.on('test', x => console.log(x * 2))
.on('test', x => console.log(x + 5))
.emit('test', 10);
Ответ:
JavaScript test | #JavaScript
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
JavaScript test
Javascript и все что с ним связано
Ссылка: @Portal_v_IT
Сотрудничество: @oleginc
Ссылка: @Portal_v_IT
Сотрудничество: @oleginc
const weakMap = new WeakMap();
const obj1 = {};
const obj2 = { key: 'value' };
weakMap.set(obj1, obj2);
const result = weakMap.get(obj1).key.split('').reverse().join('');
console.log(result);
Ответ:
Please open Telegram to view this post
VIEW IN TELEGRAM
function Person(name) {
this.name = name;
this.sayName = () => console.log(this.name);
}
const person1 = new Person('David');
const person2 = { name: 'Not David', sayName: person1.sayName };
person2.sayName();
Ответ:
Please open Telegram to view this post
VIEW IN TELEGRAM