Definition: A function is a reusable block of code that performs a specific task. Functions help in writing cleaner and more organized code by allowing developers to define a set of instructions that can be executed multiple times with different inputs.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log(sum); // Output: 8
Create a function called calculateArea that takes two parameters (width and height) and returns the area of a rectangle. Call the function with different values and display the output in the console.
Definition: JavaScript Object Notation (JSON) is a lightweight format used to store and exchange structured data. It is commonly used for transmitting data between a client and a server.
let person = {
"name": "John",
"age": 30,
"isStudent": false
};
console.log(person.name); // Output: John
console.log(person.age); // Output: 30
let jsonString = '{"name": "Emma", "age": 25}';
let personObj = JSON.parse(jsonString);
console.log(personObj.name); // Output: Emma
let car = { brand: "Toyota", model: "Camry", year: 2022 };
let jsonCar = JSON.stringify(car);
console.log(jsonCar);
// Output: {"brand":"Toyota","model":"Camry","year":2022}
Create a JSON object representing a book with properties such as title, author, and year. Convert the object to a JSON string and log it to the console.
function createStudent(name, age, course) {
return JSON.stringify({
"name": name,
"age": age,
"course": course
});
}
let studentJson = createStudent("Mike", 22, "Computer Science");
console.log(studentJson);
function displayStudent(jsonData) {
let student = JSON.parse(jsonData);
console.log(student.name + " is enrolled in " + student.course);
}
let studentInfo = '{"name": "Lily", "age": 21, "course": "Mathematics"}';
displayStudent(studentInfo);
1. Create a function called createMovie that accepts title, director, and year as parameters and returns a JSON object. Convert this object into a JSON string and log it.
2. Create a function called parseMovie that takes a JSON string representing a movie and logs the title and director.
Functions provide a structured way to write reusable code, improving efficiency and readability. JSON is a widely used data format that facilitates data storage and exchange. Combining functions and JSON enables dynamic data generation and processing, making it an essential technique in modern web development.