JavaScript Functions and Objects
Key Concepts
- Functions
- Objects
- Methods
- Properties
Functions
Functions in JavaScript are blocks of code designed to perform a particular task. They are executed when something invokes or calls them. Functions can take parameters and return values. Functions are defined using the function
keyword, followed by a name, a list of parameters in parentheses, and a block of code in curly braces.
Example:
function greet(name) { return "Hello, " + name + "!"; } console.log(greet("Alice")); // Output: Hello, Alice!
Objects
Objects in JavaScript are collections of key-value pairs. Each key is a property, and each value can be a primitive data type, another object, or even a function. Objects are defined using curly braces {}
, with each property separated by a comma.
Example:
let person = { firstName: "John", lastName: "Doe", age: 30 }; console.log(person.firstName); // Output: John
Methods
Methods are functions stored as object properties. They are defined within the object and can be called using the object's name followed by the method name. Methods are useful for performing actions related to the object.
Example:
let car = { brand: "Toyota", model: "Camry", start: function() { console.log("The car has started."); } }; car.start(); // Output: The car has started.
Properties
Properties are the values associated with a JavaScript object. They can be accessed using dot notation or bracket notation. Properties can be added, modified, or deleted from an object.
Example:
let book = { title: "JavaScript Basics", author: "Jane Smith" }; console.log(book.title); // Output: JavaScript Basics book.year = 2023; console.log(book.year); // Output: 2023
Examples and Analogies
Functions Example
Think of a function as a recipe. The recipe has ingredients (parameters) and instructions (code block). When you follow the recipe (call the function), you get a dish (return value).
Objects Example
Consider an object as a car. The car has properties like color, model, and year. Each property provides specific information about the car.
Methods Example
Imagine a method as an action that a car can perform, like starting the engine. The car object has a method called start
that performs this action.
Properties Example
Think of properties as the characteristics of a car, such as its color or model. These characteristics can be accessed and modified as needed.