javascript | Unsorted

Telegram-канал javascript - JavaScript

31615

A resourceful newsletter featuring the latest and most important news, articles, books and updates in the world of #javascript 🚀 Don't miss our Quizzes! Let's chat: @nairihar

Subscribe to a channel

JavaScript

CHALLENGE

const weakSet = new WeakSet();

const obj1 = { name: 'First' };
const obj2 = { name: 'Second' };
const obj3 = obj1;

weakSet.add(obj1);
weakSet.add(obj2);

let result = '';
result += weakSet.has(obj1) + ', ';
result += weakSet.has(obj3) + ', ';

obj2.name = 'Modified';
result += weakSet.has(obj2) + ', ';

weakSet.delete(obj1);
result += weakSet.has(obj3);

console.log(result);

Читать полностью…

JavaScript

CHALLENGE

function createCounter() {
let count = 0;

const counter = {
increment() {
count++;
return count;
},
getCount() {
return count;
}
};

return counter;
}

let c1 = createCounter();
c1.increment();
c1.increment();

let c2 = c1;
c1 = null;

console.log(c2.getCount());

Читать полностью…

JavaScript

CHALLENGE

const scores = [85, 92, 78, 90];  
const student = {
name: 'Jordan',
grade: 'A',
...{ courses: ['Math', 'Science'] },
scores,
average: function() { return this.scores.reduce((a, b) => a + b) / this.scores.length }
};

const { name, ...details } = student;
const [first, ...rest] = scores;

console.log(details.scores[0], rest[0]);

Читать полностью…

JavaScript

CHALLENGE

function getOrder() {
console.log('1');

setTimeout(() => console.log('2'), 0);

Promise.resolve().then(() => {
console.log('3');
Promise.resolve().then(() => console.log('4'));
});

Promise.resolve().then(() => console.log('5'));

console.log('6');
}

getOrder();

Читать полностью…

JavaScript

CHALLENGE

function Vehicle(wheels) {
this.wheels = wheels;
}

Vehicle.prototype.getWheels = function() {
return this.wheels;
};

function Car() {
Vehicle.call(this, 4);
this.doors = 4;
}

Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car;

const myCar = new Car();
console.log(myCar.getWheels(), myCar instanceof Vehicle);

Читать полностью…

JavaScript

CHALLENGE

const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);

const addTwo = num => num + 2;
const multiplyByThree = num => num * 3;
const subtractTen = num => num - 10;

const calculate = compose(subtractTen, multiplyByThree, addTwo);

console.log(calculate(5));

Читать полностью…

JavaScript

CHALLENGE

function mystery() {
try {
console.log('A');
throw new Error('Oops');
console.log('B');
} catch (err) {
console.log('C');
return 'D';
} finally {
console.log('E');
return 'F';
}
console.log('G');
return 'H';
}

console.log(mystery());

Читать полностью…

JavaScript

CHALLENGE

const users = [
{ id: 1, name: 'Sarah' },
{ id: 2, name: 'Miguel' },
{ id: 3, name: 'Jordan' }
];

const activeUsers = new WeakSet();
activeUsers.add(users[0]);
activeUsers.add(users[2]);

users.splice(1, 1); // Remove Miguel

let count = 0;
for (const user of users) {
if (activeUsers.has(user)) count++;
}

console.log(count);

Читать полностью…

JavaScript

CHALLENGE

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);

Читать полностью…

JavaScript

🟠Vercel Acquires NuxtLabs

Vercel has acquired the company that caretakes the Nuxt project and employs some of its core team – a move Vue creator Evan You is quite optimistic about. Vercel now manages, or at least supports, several key projects like Next.js, Turborepo, Svelte, and shadcn/ui. Nuxt itself remains open source and has a promising future. Vercel’s Guillermo Rauch shares a little more about the move here.

NuxtLabs / Vercel

Читать полностью…

JavaScript

CHALLENGE

const obj = {
name: 'Taylor',
greet() {
return `Hello, ${this.name}!`;
},
delayedGreet() {
setTimeout(function() {
console.log(this.greet());
}, 100);
}
};

obj.delayedGreet();

Читать полностью…

JavaScript

CHALLENGE

function outer() {
console.log(innerVar);
console.log(typeof innerFunc);

var innerVar = 42;

function innerFunc() {
return innerVar;
}

let anotherVar = 100;
console.log(typeof anotherVar);
}

outer();

Читать полностью…

JavaScript

CHALLENGE

async function fetchData() {
return 'Data loaded';
}

async function processData() {
console.log('Starting...');
try {
const result = fetchData();
console.log(result);
console.log(await result);
return 'Processing complete';
} catch (error) {
return 'Error occurred';
} finally {
console.log('Cleanup');
}
}

processData().then(result => console.log(result));

Читать полностью…

JavaScript

CHALLENGE

const cache = new WeakMap();

function expensiveOperation(obj) {
if (cache.has(obj)) {
console.log('Cache hit!');
return cache.get(obj);
}

console.log('Computing result...');
const result = obj.value * 2;
cache.set(obj, result);
return result;
}

const user = { value: 42 };
expensiveOperation(user);
expensiveOperation(user);
expensiveOperation({ value: 42 });

Читать полностью…

JavaScript

😆

Читать полностью…

JavaScript

🤨 Laravel and Node.js: PHP in Watt Runtime

In June we featured php-node, a new way to ‘bridge the gap’ between PHP and Node.js by being able to embed PHP into Node apps. Now they’ve gone a step further by using php-node and the Watt app server to enable the running of Laravel apps too. A curious meeting of ecosystems!

Stephen Belanger (Platformatic)

Читать полностью…

JavaScript

CHALLENGE

function* createCounter() {
let count = 0;
while (true) {
const reset = yield ++count;
if (reset) {
count = 0;
}
}
}

const counter = createCounter();
console.log(counter.next().value);
console.log(counter.next().value);
console.log(counter.next(true).value);
console.log(counter.next().value);

Читать полностью…

JavaScript

🎹 A collection of JavaScript tools written in Rust.

The Oxidation Compiler is creating a collection of high-performance tools for JavaScript and TypeScript.

Читать полностью…

JavaScript

✌️ The Nginx HTTP server has a module (njs) for extending its functionality using JavaScript, but it only supported ES5. Now, njs uses QuickJS for a more modern, powerful experience with full ES2023 support.

Читать полностью…

JavaScript

😏 CSS conditionals with the new if() function

From Chrome 137 you can try out CSS inline conditionals with the if() function. if() enables a cleaner developer interface for dynamic styles like style queries and media queries, with some key differences, which you can learn about in this post.

Читать полностью…

JavaScript

🌲 You Don’t Know Node.js EventLoop

The Ultimate Guide to Understanding EventLoop in Node.js

This comprehensive guide is going to take some time to cover every detail that you need to know, so grab a cup of coffee and settle in for an exciting journey to the fascinating world of Node.js. Let’s get started!

nairihar

Читать полностью…

JavaScript

✌️ Driver.js: Tours, Highlights, Contextual Help, and More

A vanilla JS library for making on-page tours and contextual help systems. It’s been around for several years, but is still maintained, and there are lots of examples to check out – it’s really smooth.

Kamran Ahmed

Читать полностью…

JavaScript

✌️ What’s the Difference Between Ordinary Functions and Arrow Functions?

This sounds like basic stuff, but James always does a good job of digging in and explaining things in a way that gives you a more nuanced way to think about a concept, even if it’s just “Which function declaration syntax should I use?”

James Sinclair

Читать полностью…

JavaScript

CHALLENGE

const memoryLeak = () => {
const cache = new Map();
const weakCache = new WeakMap();

const objKey = { id: 123 };
const data = { name: 'User data', value: 42 };

cache.set(objKey, data);
weakCache.set(objKey, data);

// Simulate removing reference to key
const result = { map: cache.has(objKey), weakMap: weakCache.has(objKey) };
// objKey = null; // This would be an error, as const can't be reassigned

return result;
};

console.log(memoryLeak());

Читать полностью…

JavaScript

CHALLENGE

function createCounter() {
let count = 0;

function increment() {
count += 1;
return count;
}

function decrement() {
count -= 1;
return count;
}

return { increment, decrement, value: () => count };
}

const counter = createCounter();
counter.increment();
counter.increment();
counter.decrement();

console.log(counter.value() + counter.increment());

Читать полностью…

JavaScript

CHALLENGE

function* rangeGenerator(start, end, step = 1) {
let current = start;
while (current <= end) {
yield current;
current += step;
}
}

const numbers = rangeGenerator(1, 10, 2);

numbers.next();
numbers.next();

const values = [...numbers];
console.log(values);

Читать полностью…

JavaScript

🤩 Bruno: An IDE for Exploring and Testing HTTP APIs

An open source (though a commercial version is available) Node and Electron-based desktop app for crafting and testing HTTP requests, complex and simple. Think of it as a lightweight alternative to something like Postman.

Anoop M D, Anusree P S and Contributors

Читать полностью…

JavaScript

✌️ jsonrepair: Repair Invalid JSON Documents

This has lots of possible use cases, including dealing with weird JSON coming back from LLMs or non-compliant JSON spat out by poorly built software. You can use it from Node, as a CLI tool, or try a basic version online.

Jos de Jong

Читать полностью…

JavaScript

CHALLENGE

function processUserData(data) {
try {
if (!data) {
throw new Error('No data provided');
}

if (!data.name) {
throw new TypeError('Name is required');
}

return { success: true, user: data.name };
} catch (err) {
if (err instanceof TypeError) {
return { success: false, reason: 'validation-failed' };
}
return { success: false, reason: 'unknown-error' };
}
}

console.log(processUserData({}));

Читать полностью…

JavaScript

CHALLENGE

function createCounter() {
let count = 0;

function increment() {
count++;
return count;
}

function decrement() {
count--;
return count;
}

return { increment, decrement, reset: () => count = 0 };
}

const counter = createCounter();
counter.increment();
counter.increment();
counter.decrement();

const { increment, reset } = counter;
increment();
reset();
increment();

console.log(counter.increment());

Читать полностью…
Subscribe to a channel