Functions and classes (JavaScript)
Learn Functions and classes (JavaScript) step by step with clear examples and exercises.
Title: Mastering Functions and Classes in JavaScript
Why This Matters
Functions and classes are fundamental concepts in JavaScript, essential for organizing code, reusing functionality, and creating objects with properties and methods. Understanding these concepts prepares you to write cleaner, more efficient, and maintainable code—skills that can make a significant difference in real-world projects, interviews, and debugging complex issues.
Prerequisites
Before diving into functions and classes, it's important to have a good understanding of the following:
- Basic JavaScript syntax (variables, data types, operators)
- Control structures (if-else statements, loops)
- Callbacks and higher-order functions
- Understanding the concept of objects
- Familiarity with ES6 features like arrow functions and classes
- Comprehension of common JavaScript error handling techniques
Core Concept
Functions
A function in JavaScript is a reusable block of code that performs a specific task. You can create functions using the function keyword or arrow functions (ES6 syntax). Here's an example of a simple function:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('John'); // Output: Hello, John!
Arrow Functions (ES6 syntax)
Arrow functions provide a more concise way to define functions and are especially useful for anonymous functions or one-liner functions. Here's the same example using an arrow function:
const greet = (name) => {
console.log(`Hello, ${name}!`);
};
greet('John'); // Output: Hello, John!
Function Scope and Hoisting
It's important to understand the function scope and hoisting in JavaScript. Functions are hoisted to the top of their containing scope, but they are not executed until called. This means that you can call a function before it is defined, but it will throw an error if you try to access its variables before they are declared.
myFunction(); // Outputs: Uncaught ReferenceError: myFunction is not defined
function myFunction() {
console.log('Hello from myFunction!');
}
Classes
Classes in JavaScript are used to define blueprints for objects, which can have properties and methods. To create a class, use the class keyword followed by the class name and curly braces. Here's an example of a simple class:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, I am ${this.name} and I am ${this.age} years old.`);
}
}
const john = new Person('John', 25);
john.greet(); // Output: Hello, I am John and I am 25 years old.
Class Prototypes and Inheritance
JavaScript classes also have a prototype-based inheritance system. By default, every object in JavaScript has a prototype property that points to an empty object. You can add methods to the prototype of a class to make them accessible to all instances of that class. Here's an example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
const cat = new Animal('Cat');
cat.speak(); // Output: Cat makes a sound.
// Now let's create a subclass for a specific type of animal (Dog)
class Dog extends Animal {
bark() {
console.log(`${this.name} barks!`);
}
}
const dog = new Dog('Dog');
dog.bark(); // Output: Dog barks!
Worked Example
Let's create a simple calculator class with addition, subtraction, multiplication, and division methods, as well as a method to find the greatest common divisor (GCD):
class Calculator {
constructor() {}
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero');
}
return a / b;
}
gcd(a, b) {
// Euclidean algorithm for finding the GCD
while (b !== 0) {
const temp = b;
b = a % b;
a = temp;
}
return Math.abs(a);
}
}
const calculator = new Calculator();
console.log(calculator.add(5, 3)); // Output: 8
console.log(calculator.subtract(10, 4)); // Output: 6
console.log(calculator.multiply(3, 7)); // Output: 21
console.log(calculator.divide(15, 3)); // Output: 5
console.log(calculator.gcd(20, 8)); // Output: 4
Common Mistakes
- Forgetting to return a value from a function
function add(a, b) {
console.log(a + b); // This will only print the result, not return it
return a + b;
}
- Not using
thiscorrectly in classes
class Person {
constructor(name) {
this.name = name;
this.age = 0; // This will not update the age property
}
incrementAge() {
this.age++;
}
}
const john = new Person('John');
john.incrementAge();
console.log(john.age); // Output: 0, not 1
- Misunderstanding function scope and hoisting
myFunction(); // Outputs: Uncaught ReferenceError: myFunction is not defined
var myFunction = function() {
console.log('Hello from myFunction!');
};
- Not understanding the difference between
let,const, andvar
// Using `var` will create a function-scoped variable, while using `let` or `const` creates a block-scoped variable
function test() {
var x = 10; // Function-scoped
let y = 20; // Block-scoped (only accessible within the curly braces)
const z = 30; // Block-scoped (only accessible within the curly braces)
console.log(x); // Output: 10
console.log(y); // Output: ReferenceError: y is not defined
console.log(z); // Output: ReferenceError: z is not defined
}
Practice Questions
- Write a function that takes an array of numbers and returns the sum of all even numbers.
- Create a class for a bank account with properties
balanceandownerName. Add methods for depositing money, withdrawing money, and checking the balance. - Modify the Calculator class from the worked example to include a method for finding the factorial of a number.
- Write a function that takes an array of numbers and returns the second-highest number in the array (assuming the array contains at least two unique numbers).
- Create a class for a car with properties
make,model,year, andspeed. Add methods to increase and decrease the speed, as well as a method to check if the car is moving (i.e., its speed is greater than 0).
FAQ
- What is the difference between a function and a method in JavaScript?
A function is a standalone piece of code that can be called anywhere, while a method belongs to an object and has access to that object's properties and methods.
- Can I use arrow functions with classes in JavaScript?
Yes, you can use arrow functions within class methods for a more concise syntax. However, the constructor should still use the traditional function syntax.
- Why do we need to bind
thisin JavaScript?
When using callbacks or event listeners, this may not refer to the expected object. To solve this issue, you can use methods like bind, call, or apply.
- What is hoisting in JavaScript and how does it affect variable declarations?
In JavaScript, variables are hoisted to the top of their containing scope at compile time. However, assignments are not hoisted, which means that if you try to access a variable before it is assigned a value, you will get undefined. To avoid this, always declare your variables with either var, let, or const at the beginning of their respective scopes.
- What is the difference between
let,const, andvarin JavaScript?
In JavaScript, var creates function-scoped variables that can be reassigned, while both let and const create block-scoped variables that cannot be redeclared or reassigned (for const). This makes let and const more suitable for modern JavaScript development due to their more restrictive scopes and improved performance.