JavaScript
Functions / Objects
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:
- You cannot use reserved keywords (like
function,let,return). - You cannot start with a number.
- You cannot use special characters except
$and_. - Best practice → Use camelCase for function names.
Example:
function calculateTotal() { } // Good
function $priceUpdate() { } // Valid but uncommon
function 2sum() { } // Invalid - starts with a numberParameters
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:
- Cannot use reserved words.
- Cannot start with a number.
- Cannot use special characters except
$and_. - Best practice → Use camelCase for parameter names.
Example:
function calculateArea(width, height) {
return width * height;
}console.log(calculateArea(5, 10)); // Output: 50The 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: 8If 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 socksAccessing Object Properties
We can access values in two ways:
- Dot notation (default and most common):
console.log(product.price); // 10902. 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 dayValues 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, WaruniBuilt-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.JSONandlocalStorageare 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.
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')); // 5Objects 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); // helloBoth 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); // falseConclusion
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
JSONandlocalStorage. - Pass data efficiently between programs.
Mastering objects is the key to writing scalable, maintainable, and professional JavaScript code.








