· Jan 2023 · 1 min read

Functions & Objects in JavaScript

In JavaScript, a function is a block of code that can be reusable. Functions can accept input (called parameters) and return output (called return value).

Functions

In JavaScript, a function is a block of code that can be reusable. Functions can accept input (called parameters) and return output (called return value).

To define a function in JavaScript, you use the function keyword, followed by the name of the function, a list of parameters (enclosed in parentheses), and the function body (enclosed in curly braces).

Here is an example of a function in JavaScript:

function greet(name) {  console.log("Hello, " + name + "!");}

To call a function in JavaScript, you simply use its name followed by the list of arguments (enclosed in parentheses).

Here is an example of how to call the greet function:

greet("John"); // Output: "Hello, John!"

You can also define a function that returns a value using the return statement.

Here is an example of a function that returns a value:

function add(num1, num2) {  return num1 + num2;}console.log(add(10, 5)); // Output: 15

Objects

In JavaScript, an object is a collection of key-value pairs. You can use objects to store data in a structured way.

To create an object in JavaScript, you use the {} curly braces and define the key-value pairs inside the braces.

Here is an example of an object in JavaScript:

var person = {  name: "John",  age: 30,  occupation: "Developer"};

To access the values in an object, you use the . dot notation followed by the key.

Here is an example of how to access the values in the person object:

console.log(person.name); // Output: "John"console.log(person.age);  // Output: 30console.log(person.occupation); // Output: "Developer"

You can also update the values in an object by simply reassigning them.

person.name = "Jane";person.age = 25;console.log(person.name); // Output: "Jane"console.log(person.age);  // Output: 25

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Interested in scaling your software startup? Check out Circuit.


Functions & Objects in JavaScript was originally published in JavaScript in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.

More articles
6 Use Cases for Javascript Proxies
Streamlining Your Dependencies with ni: A Beginner’s Tutorial to the Package Manager of the Future.
Using CSS to Implement a Dark Mode Theme for Your Websites