JavaScript allows you to quickly grab specific pieces of information from an object and store them in variables using a feature called destructuring assignment.
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'
You can create objects more easily by using the same name for both the property and the value. JavaScript automatically assigns the property name to match the variable name.
const activity = 'Surfing'; const beach = { activity }; console.log(beach); // { activity: 'Surfing' }
In JavaScript, the 'this' keyword is used inside methods to refer to the object that owns the method, allowing you to access its properties.
const cat = { name: 'Pipey', age: 8, whatName() { return this.name; } }; console.log(cat.whatName()); // Output: Pipey
In JavaScript, 'this' refers to the object that calls the method, making it useful for accessing other properties within the same object.
const restaurant = { numCustomers: 45, seatCapacity: 100, availableSeats() { // 'this' refers to the restaurant object // and is used to access its properties return this.seatCapacity - this.numCustomers; } }
Arrow functions in JavaScript don't have their own 'this' context. Instead, they inherit 'this' from the surrounding code, which can lead to unexpected behavior.
const myObj = { data: 'abc', loggerA: () => { console.log(this.data); }, loggerB() { console.log(this.data); }, }; myObj.loggerA(); // undefined myObj.loggerB(); // 'abc'
JavaScript getters and setters allow you to control how object properties are accessed and modified, adding extra logic when needed.
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"); } } };
A factory function is a regular JavaScript function that returns a new object every time it's called. It's a simple way to create multiple objects with similar properties.
// A factory function that creates dog objects. const dogFactory = (name, age, breed) => { return { name: name, age: age, breed: breed, bark() { console.log('Woof!'); } }; };
Getters and setters provide a way to add additional checks or transformations when getting or setting a property on an object.
const myCat = { _name: 'Dottie', get name() { return this._name; }, set name(newName) { this._name = newName; } }; console.log(myCat.name); // 'Dottie' myCat.name = 'Yankee'; console.log(myCat.name); // 'Yankee'
Property names in JavaScript must follow certain rules: they can't contain spaces, they can't start with a number, and they shouldn't include special characters unless they are inside quotes.
// Invalid key names example const trainSchedule = { "platform num": 10, // Valid because the key is inside quotes. 40 - 10 + 2: 30, // Invalid because expressions cannot be keys. "+compartment": 'C' // Valid because the key is a string. }
Dot notation is a simple and common way to access the properties of an object in JavaScript.
const apple = { color: 'Green', price: { bulk: '$3/kg', smallQty: '$4/kg' } }; console.log(apple.color); // 'Green' console.log(apple.price.bulk); // '$3/kg'
If you try to access a property that doesn't exist in a JavaScript object, it will return undefined instead of throwing an error.
const classElection = { date: 'January 12' }; console.log(classElection.place); // undefined
JavaScript objects can be changed even after they are created. This means you can add, change, or delete properties.
let mobile = { brand: 'Samsung', model: 'Galaxy Note 9' }; for (let key in mobile) { console.log(`${key}: ${mobile[key]}`); }
The for...in loop allows you to iterate over all the properties of an object, making it useful for checking or manipulating object data.
const classOf2018 = { students: 38, year: 2018 }; for (let key in classOf2018) { console.log(`${key}: ${classOf2018[key]}`); }
Object properties store data values, and these values can be accessed or modified using the property's name.
const person = { firstName: "Matilda", age: 27, hobby: "knitting", goal: "learning JavaScript" }; delete person.hobby; console.log(person); /* { firstName: "Matilda", age: 27, goal: "learning JavaScript" } */
You can remove properties from a JavaScript object using the delete operator, which permanently deletes the property from the object.
const origNum = 8; const origObj = {color: 'blue'}; const changeItUp = (num, obj) => { num = 7; obj.color = 'red'; }; changeItUp(origNum, origObj); console.log(origNum); // 8 (integers are passed by value) console.log(origObj.color); // 'red' (objects are passed by reference)
When you pass an object to a function in JavaScript, any changes made to the object inside the function affect the original object outside the function.
const engine = { start(adverb) { console.log(`The engine starts up ${adverb}...`); }, sputter: () => { console.log('The engine sputters... '); } };
Ensuring that your JavaScript code works across different browsers is crucial for providing a consistent user experience.
function useThis() { console.log(this); } let newObject = {func: useThis, prop: "value"}; newObject.func(); function useThis() { console.log(this); } newObject.func();
Polyfills are pieces of code that add support for features that are not natively supported in some browsers, helping to standardize your code.
if (!Object.assign) { Object.assign = function(target) { // polyfill code here }; }
JavaScript modules allow you to organize and reuse code more efficiently by breaking it down into smaller, manageable parts.
import { add, subtract } from './math.js';
Modules help to keep your JavaScript code clean and maintainable by separating functionality into different files that can be imported when needed.
export const add = (a, b) => a + b; import { add } from './math.js';
Not all browsers support JavaScript modules out of the box, so it's important to check compatibility or use tools like bundlers to ensure your code works everywhere.
import { add, subtract } from './math.js'; console.log(add(2, 3));
ES6 modules are a way to structure your JavaScript code more cleanly, making it easier to manage and reuse.
export const myFunction = () => {}; import { myFunction } from './myModule.js';
Transpilation converts your modern JavaScript code into a version that older browsers can understand, ensuring compatibility.
let myVariable = 'Hello'; // Transpiled into var myVariable = 'Hello';
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!