Loading...
Loading...
Write JavaScript code with deep understanding of the language fundamentals as envisioned by Brendan Eich, creator of JavaScript. Emphasizes first-class functions, prototypes, and the dynamic nature of the language. Use when leveraging JavaScript's unique characteristics.
npx skill4agent add copyleftdev/sk1llz eich-language-fundamentals"Always bet on JavaScript."
"JavaScript has first-class functions and closures. That's a big deal."
undefinednull// Functions as values
const greet = function(name) {
return 'Hello, ' + name;
};
// Functions as arguments
function map(array, transform) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(transform(array[i]));
}
return result;
}
const doubled = map([1, 2, 3], function(x) { return x * 2; });
// Functions returning functions
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
double(5); // 10
triple(5); // 15// Closures capture their lexical environment
function createCounter() {
let count = 0; // Private state
return {
increment: function() { return ++count; },
decrement: function() { return --count; },
value: function() { return count; }
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.value(); // 2
// count is not directly accessible// Objects inherit from objects
const animal = {
speak: function() {
return this.sound;
}
};
const dog = Object.create(animal);
dog.sound = 'Woof!';
dog.speak(); // 'Woof!'
const cat = Object.create(animal);
cat.sound = 'Meow!';
cat.speak(); // 'Meow!'
// The prototype chain
dog.hasOwnProperty('sound'); // true
dog.hasOwnProperty('speak'); // false (inherited)// Objects are dynamic property bags
const obj = {};
// Add properties anytime
obj.name = 'Dynamic';
obj['computed-key'] = 'Works too';
// Delete properties
delete obj.name;
// Check existence
'computed-key' in obj; // true
// Iterate properties
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]);
}
}