The .reduce() method iterates through an array and returns a single value, which is accumulated as it processes each element.
const arrayOfNumbers = [1, 2, 3, 4]; const sum = arrayOfNumbers.reduce((accumulator, currentValue) => { return accumulator + currentValue; }); console.log(sum); // 10
The .forEach() method executes a provided function once for each array element.
const numbers = [28, 77, 45, 99, 27]; numbers.forEach(number => { console.log(number); });
The .filter() method creates a new array with all elements that pass the test implemented by the provided function.
const randomNumbers = [4, 11, 42, 14, 39]; const filteredArray = randomNumbers.filter(n => { return n > 5; }); console.log(filteredArray); // [11, 42, 14, 39]
The .map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const finalParticipants = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby']; const announcements = finalParticipants.map(member => { return member + ' joined the contest.'; }); console.log(announcements); // ['Taylor joined the contest.', 'Donald joined the contest.', 'Don joined the contest.', 'Natasha joined the contest.', 'Bobby joined the contest.']
Functions in JavaScript can be assigned to variables, which can then be used to invoke the function.
let plusFive = (number) => { return number + 5; }; let f = plusFive; console.log(f(9)); // 14
A callback function is a function passed into another function as an argument and is executed after some operation has been completed.
const isEven = (n) => { return n % 2 == 0; }; let printMsg = (evenFunc, num) => { const isNumEven = evenFunc(num); console.log(`The number ${num} is an even number: ${isNumEven}.`); }; printMsg(isEven, 4); // Prints: The number 4 is an even number: true.
A higher-order function is a function that either takes one or more functions as arguments or returns a function as its result.
const originalFunc = (num) => { return num + 2; }; const newFunc = originalFunc; console.log(newFunc.name); // 'originalFunc' console.log(newFunc.toString()); // '(num) => { return num + 2 }'
In JavaScript, functions are first-class objects, meaning they can be stored in variables, passed as arguments to other functions, and returned by other functions.
Destructuring assignment is a shorthand syntax that allows object properties to be unpacked into distinct variables.
const rubiksCubeFacts = { possiblePermutations: '43,252,003,274,489,856,000', invented: '1974', largestCube: '17x17x17' }; const {possiblePermutations, invented, largestCube} = rubiksCubeFacts; console.log(possiblePermutations); // '43,252,003,274,489,856,000' console.log(invented); // '1974' console.log(largestCube); // '17x17x17'
Shorthand property names allow you to create objects more concisely by omitting the key when it matches the variable name.
const activity = 'Surfing'; const beach = { activity }; console.log(beach); // { activity: 'Surfing' }
The this keyword refers to the object that is currently executing the function and is commonly used to access properties of the object.
const cat = { name: 'Pipey', age: 8, whatName() { return this.name; } }; console.log(cat.whatName()); // Output: Pipey
Arrow functions do not have their own this context and instead inherit it from the surrounding scope.
const myObj = { data: 'abc', loggerA: () => { console.log(this.data); }, loggerB() { console.log(this.data); } }; myObj.loggerA(); // undefined myObj.loggerB(); // 'abc'
Getters and setters allow you to define how to access and mutate properties of an object while providing additional control.
const myCat = { _name: 'Snickers', get name() { return this._name; }, set name(newName) { if (typeof newName === 'string' && newName.length > 0) { this._name = newName; } else { console.log('ERROR: name must be a non-empty string'); } } };
Factory functions are functions that return an object, allowing you to create multiple instances of similar objects.
const dogFactory = (name, age, breed) => { return { name: name, age: age, breed: breed, bark() { console.log('Woof!'); } }; };
Object property names must be valid JavaScript identifiers or strings. Invalid names include those with spaces or special characters.
const trainSchedule = { 'platform num': 10, // Invalid without quotes '40 - 10 + 2': 30, // Expressions cannot be keys '+compartment': 'C' // Valid when enclosed in quotes };
Dot notation is used to access properties of an object by specifying the object and the property name separated by a dot.
const apple = { color: 'Green', price: { bulk: '$3/kg', smallQty: '$4/kg' } }; console.log(apple.color); // 'Green' console.log(apple.price.bulk); // '$3/kg'
Accessing a non-existent property of an object returns undefined.
const classElection = { date: 'January 12' }; console.log(classElection.place); // undefined
JavaScript objects are mutable, meaning their properties can be changed even if the object itself is declared with const.
const student = { name: 'Sheldon', score: 100, grade: 'A', }; delete student.score; student.grade = 'F'; console.log(student); // { name: 'Sheldon', grade: 'F' }
The for...in loop allows you to iterate over the properties of an object.
let mobile = { brand: 'Samsung', model: 'Galaxy Note 9' }; for (let key in mobile) { console.log(`${key}: ${mobile[key]}`); } // Output: // brand: Samsung // model: Galaxy Note 9
The in operator allows you to check if a specific property exists in an object.
const dog = { name: 'Dog', breed: 'Dalmatian' }; console.log('name' in dog); // true console.log('color' in dog); // false
The hasOwnProperty method returns true if the specified property is a direct property of the object, not inherited.
const dog = { name: 'Dog', breed: 'Dalmatian' }; console.log(dog.hasOwnProperty('name')); // true console.log(dog.hasOwnProperty('color')); // false
Methods such as Object.keys(), Object.values(), and Object.entries() are useful for manipulating object properties.
const myObject = { name: 'Joe', age: 30 }; console.log(Object.keys(myObject)); // ['name', 'age'] console.log(Object.values(myObject)); // ['Joe', 30] console.log(Object.entries(myObject)); // [['name', 'Joe'], ['age', 30]]
Classes in JavaScript are a template for creating objects. They encapsulate data with code to work on that data.
class Dog { constructor(name, breed) { this.name = name; this.breed = breed; } bark() { console.log('Woof!'); } } const myDog = new Dog('Buddy', 'Golden Retriever'); myDog.bark(); // Woof!
The constructor method is a special method for creating and initializing objects created with a class.
class Dog { constructor(name) { this.name = name; } } const myDog = new Dog('Buddy'); console.log(myDog.name); // Buddy
Instance methods are functions defined inside a class and can be called on instances of the class.
class Dog { constructor(name) { this.name = name; } bark() { console.log(`${this.name} says Woof!`); } } const myDog = new Dog('Buddy'); myDog.bark(); // Buddy says Woof!
Static methods are defined on the class itself rather than on instances of the class.
class Dog { static info() { console.log('Dogs are loyal pets.'); } } Dog.info(); // Dogs are loyal pets.
Inheritance is a feature that allows a class to inherit properties and methods from another class using the extends keyword.
class Animal { constructor(name) { this.name = name; } eat() { console.log(`${this.name} is eating.`); } } class Dog extends Animal { bark() { console.log('Woof!'); } } const myDog = new Dog('Buddy'); myDog.eat(); // Buddy is eating. myDog.bark(); // Woof!
The super keyword is used to call the constructor of a parent class and access its properties and methods.
class Animal { constructor(name) { this.name = name; } } class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; } } const myDog = new Dog('Buddy', 'Golden Retriever'); console.log(myDog.name); // Buddy console.log(myDog.breed); // Golden Retriever
Getter and setter methods are used to get and set the value of an object's properties in a more controlled way.
class Dog { constructor(name) { this._name = name; } get name() { return this._name; } set name(newName) { this._name = newName; } } const myDog = new Dog('Buddy'); console.log(myDog.name); // Buddy myDog.name = 'Max'; console.log(myDog.name); // Max
Private fields and methods are denoted by a # symbol and are only accessible within the class they are defined in.
class Dog { #secret; constructor(name) { this.name = name; this.#secret = 'I love bones'; } revealSecret() { console.log(this.#secret); } } const myDog = new Dog('Buddy'); myDog.revealSecret(); // I love bones
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!