25. Occurrences of Each Char
Lesson 26 of 31 in Coddy's 30 Days of Logic Building in Javascript course.
Understand object in js -
1. Creating an Object: You can create an object using curly braces <strong>{}</strong> and defining key-value pairs inside.
let person = {
name: 'John',
age: 25,
city: 'New York'
};2. Accessing Object Properties: You can access the values of an object using dot notation or square brackets.
console.log(person.name); // Output: John
console.log(person['age']); // Output: 253. Adding and Modifying Properties: You can add new properties or modify existing ones.
person.job = 'Developer';
person.age = 26;4. Object Methods: You can include functions as values in an object, and these are called methods.
let person = {
name: 'John',
greet: function() {
console.log('Hello, my name is ' + this.name);
}
};
person.greet(); // Output: Hello, my name is John5. Deleting Properties: You can delete properties from an object using the <strong>delete</strong> keyword.
delete person.city;6. Object Iteration: You can loop through the keys or values of an object using <strong>for...in</strong> loop.
for (let key in person) {
console.log(key + ': ' + person[key]);
}Challenge
EasyWrite a function that takes a string and returns an object with the count of occurrences of each character.
- Input:
<strong>"hello"</strong> - Expected Output:
<strong>{"h": 1, "e": 1, "l": 2, "o": 1}</strong>
Try it yourself
function countCharacters(str) {
// write your code below
}All lessons in 30 Days of Logic Building in Javascript
1Introduction
What is here for you?43rd Mile Stone
21. Calculate GCD22. Fizz Buzz23. Two Sum24. Validate Email25. Occurrences of Each Char26. Count Words27. Reverse an Integer28. Subarray Sum Equals K 29. Largest Rectangle in Histo30. Count And Say