Sitemap
Waruni Gunasena

Waruni Gunasena

Undergraduate | Software Developer | Netball Player | University of Moratuwa

JavaScript

Functions / Objects

4 min readAug 16, 2025

--

Functions in JavaScript

A function is a block of code designed to perform a specific task. Functions allow programmers to reuse code, which means you can write the code once and run it whenever you need. This makes your code cleaner, easier to read, and easier to update in the future.

Example:

function greet() {
console.log('Hello, welcome!');
}
greet(); // Output: Hello, welcome!

Rules for Function Names

When naming functions in JavaScript:

  1. You cannot use reserved keywords (like function, let, return).
  2. You cannot start with a number.
  3. You cannot use special characters except $ and _.
  4. Best practice → Use camelCase for function names.

Example:

function calculateTotal() { } // Good
function $priceUpdate() { } // Valid but uncommon
function 2sum() { } // Invalid - starts with a number

Parameters

A function can take parameters, which are placeholders for values that you pass into the function. They allow the function to work with different inputs.

Example:

function greetUser(name) {
console.log(`Hello, ${name}!`);
}
greetUser('Waruni');  // Output: Hello, Waruni!
greetUser('Menura'); // Output: Hello, Menura!

Rules for Parameter Names

  • Same rules as function names:
  1. Cannot use reserved words.
  2. Cannot start with a number.
  3. Cannot use special characters except $ and _.
  4. Best practice → Use camelCase for parameter names.

Example:

function calculateArea(width, height) {
return width * height;
}
console.log(calculateArea(5, 10)); // Output: 50

The Return Statement

The return statement allows a function to send a value back to the part of the code where it was called.

Example:

function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log(sum); // Output: 8

If you don’t use return, the function will still run, but it won’t give back a value — it will just perform an action.

  • Use functions to avoid repeating yourself.
  • Keep function names descriptive so it’s easy to understand what they do.
  • Always follow naming rules to avoid syntax errors.

Objects in JavaScript

In JavaScript, an object is a special data structure that allows us to group multiple values together. Instead of working with many separate variables, we can store related information inside an object and access it easily.

Creating an Object

An object is written using curly braces {}, with properties and their values separated by colons.

const product = {
name: 'socks',
price: 1090
};

Here, name and price are properties of the product object.

Updating Object Properties

Objects allow us to change values after they are created.

product.name = 'cotton socks';
console.log(product.name); // cotton socks

Accessing Object Properties

We can access values in two ways:

  1. Dot notation (default and most common):
console.log(product.price); // 1090

2. Bracket notation (used when property names include characters not supported in dot notation).

const product2 = {
"delivery-time": "1 day"
};
console.log(product2["delivery-time"]); // 1 day

Values Inside Objects

Objects can store different data types:
1. Numbers
2. Strings
3. Booleans
4. Other objects (nested objects)
5. Functions (methods)

Get Waruni Gunasena’s stories in your inbox

Join Medium for free to get updates from this writer.

Example:

const user = {
name: 'Waruni',
age: 25,
isMember: true,
address: {
city: 'Colombo',
country: 'Sri Lanka'
},
greet: function() {
console.log('Hello, ' + this.name);
}
};
user.greet(); // Hello, Waruni

Built-in Objects

JavaScript comes with many built-in objects that make programming easier.

  • console.log() → here, console is a built-in object.
  • Math.random() → Math is a built-in object.
  • JSON and localStorage are also built-in objects.

JSON (JavaScript Object Notation)

JSON is a syntax similar to JavaScript objects, but with fewer features.

  • Uses double quotes "" only.
  • Cannot store functions.
  • Works across almost all programming languages.

Example JSON:

{
"name": "shirt",
"delivery-time": "1 day",
"rating": {
"stars": 4.5,
"count": 87
}
}

Why JSON?

  • JavaScript objects can only be used in JavaScript.
  • JSON is universal — can be used across different languages for data exchange.
Press enter or click to view image in full size

Converting Between JSON and JavaScript

const product = { name: 'shirt', price: 1500 };
// Convert JS object → JSON
const jsonString = JSON.stringify(product);
// Convert JSON → JS object
const jsObject = JSON.parse(jsonString);

localStorage

Variables in JavaScript are temporary — they disappear when the page reloads. If we want to save values permanently, we use localStorage.

localStorage.setItem('cartQuantity', 5);
console.log(localStorage.getItem('cartQuantity')); // 5

Objects Are References

Objects in JavaScript are stored by reference, not by value.

const object1 = { message: 'hello' };
const object2 = object1;
object2.message = 'hello';
console.log(object1.message); // hello

Both object1 and object2 point to the same object.

When comparing objects, JavaScript checks the reference, not the content:

const a = { x: 1 };
const b = { x: 1 };
console.log(a === b); // false

Conclusion

Objects are one of the most powerful features in JavaScript.
They allow us to :

  • Group related values together.
  • Store functions as methods.
  • Work with built-in tools like JSON and localStorage.
  • Pass data efficiently between programs.

Mastering objects is the key to writing scalable, maintainable, and professional JavaScript code.

--

--

Waruni Gunasena
Waruni Gunasena

Written by Waruni Gunasena

Undergraduate | Software Developer | Netball Player | University of Moratuwa