In this article, I'm sharing what I learned with simple examples. This might be helpful for anyone who is just starting with JavaScript.
While Loop
A while loop is used when we want to execute a block of code repeatedly as long as a given condition is true.
Let's start with a simple example.
let count = 0;
while (count < 5) {
console.log(1);
count = count + 1;
}
output: 1 1 1 1 1
Here, the loop starts with count = 0.
- It checks whether count < 5.
- If the condition is true, it prints 1.
- Then the count increases by 1.
- This continues until the condition becomes false.
Decrementing a Value
We can also use a while loop to decrease a value.
let count = 4;
while (count >= 0) {
console.log(count);
count = count - 1;
}
output:4 3 2 1 0
Printing Even Numbers
Let's print even numbers from 2 to 10.
let count = 2;
while (count <= 10) {
console.log(count);
count = count + 2;
}
output: 2 4 6 8 10
What should we check when writing a loop?
Whenever I write a loop, I try to remember these three things:
- Initial Value: Where should the loop start?
- Condition: When should the loop stop?
- Increment or Decrement: How should the value change?
These three things help us avoid infinite loops.
Do-While Loop
The do-while loop is slightly different from the while loop.
In a while loop, the condition is checked first.
But in a do-while loop, the code executes at least once before checking the condition.
Let's understand with an example.
do-while:
let i=5;
do{
console.log('Hello');
i++;
}while(i<5)
console.log(i);
output: Hello 6
Why does this happen?
- Initially, i = 5.
- The do block executes and prints Hello.
- Then i++ changes the value to 6.
- Now the condition i < 5 is false.
- The loop stops. Even though the condition is false, the code inside do executes once
Ternary Operator
The ternary operator is a shorter way of writing a simple if-else condition.
Syntax:
condition ? expression1 : expression2;
Let's see an example.
let mark = 9;
let result = mark >= 35 ? "Pass" : "Fail";
console.log(result);
Output: Fail
Here:
- If the mark is greater than or equal to 35, the result is Pass.
- Otherwise, the result is Fail.
Switch Statement
A switch statement is used when we need to compare one value against multiple possible cases.
let day = 1;
switch (day) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
default:
console.log("Invalid");
break;
}
Output: Monday
Understanding the keywords:
- switch – Checks the given expression.
- case – Defines a possible matching value.
- break – Stops execution of the switch statement.
- default – Executes when no case matches.
Functions in JavaScript
A function is a reusable block of code that performs a particular task.
Instead of writing the same code again and again, we can create a function and call it whenever required.
Simple Function
function biryani() {
console.log('Biryani ready');
}
biryani();
Output:
Biryani ready
Here, biryani() is the function call.
Function with Parameters
We can also pass values to a function.
function add(n1, n2) {
console.log(n1 + n2);
}
add(5, 15);
Output:
20
Here:
- n1 and n2 are parameters.
- 5 and 15 are arguments.
Parameters are variables defined in the function declaration, while arguments are the actual values passed when calling the function.
Function with Return Statement
The return keyword sends a value back from a function.
Let's take a biryani example.
function biryani(container1, container2) {
console.log('Biryani ready');
let container = 'Biryani';
return container;
}
let plate = biryani('basmati rice', 'chicken');
console.log(plate);
Output:
Biryani ready
Biryani
Here, the function returns the value 'Biryani', which is stored in the plate variable.
One important thing to understand is that console.log() displays a value, whereas return sends a value back to the caller.
Understanding Parameters and Arguments
Let's see what happens when we pass only one argument.
function biryani(container1, container2) {
console.log(container1, container2);
}
biryani('basmati');
Output:
basmati undefined
Why?
We defined two parameters but passed only one argument.
So:
- container1 gets 'basmati'.
- container2 gets undefined.
Default Parameters
We can provide default values to function parameters.
function biryani(container1, container2 = 'chicken') {
console.log(container1, container2);
}
biryani('basmati');
Output:
basmati chicken
Since we didn't pass the second argument, JavaScript uses the default value 'chicken'.
Practical Example: Student Marks Calculation
function add(tamil,english,maths,science,social){
let add= tamil+english+maths+science+social;
console.log(`sum: ${add}`);
return add;
}
function Average(addition){
let avg=addition/5;
console.log(`Average: ${avg}`);
return avg;
}
function Grade(avg){
if(avg>90){
console.log("A Grade")
}
else if(avg>80){
console.log("B Grade");
}else if(avg>70){
console.log("C Grade");
}
}
let addition=add(78,67,100,56,89);
let avg=Average(addition);
Grade(avg);
Output:
Sum: 390
Average: 78
C Grade
In this example, we created three separate functions:
- add() – Calculates the total marks.
- Average() – Calculates the average.
- Grade() – Displays the grade based on the average.
This example helped me understand how multiple functions can work together.
Arrow function
Arrow functions provide a shorter way to write functions in JavaScript.
Let's compare a normal function with an arrow function.
Normal Function:
function display() {
return "Hello";
}
Arrow Function:
const display = () => "Hello";
Both return the same value.
Arrow Function with Parameters
Normal function:
function display(name) {
return "Hello " + name;
}
Arrow function:
const display = name => "Hello " + name;
console.log(display('Vanitha'));
Output:
Hello Vanitha
When an arrow function has only one parameter, we can omit the parentheses around that parameter.
Function Expression
We can also assign a normal function to a variable.
const display = function(name) {
return "Hello " + name;
};
console.log(display('Vanitha'));
Output:
Hello Vanitha
This is called a function expression.
Strings in JavaScript
A string is used to store text.
For example:
let message = "Hello World";
JavaScript provides many built-in string methods that help us work with text.
One important thing I learned is that string methods return a new string or value rather than changing the original string.
charAt()
The charAt() method returns the character at a specified index.
let message = "Hello World";
console.log(message.charAt(0));
console.log(message.charAt(4));
Output:
H
o
Objects in JavaScript
For example, let's create a bike object.
const bike1 = {
brand: "Yamaha",
model: "R15",
price: 20000
};
console.log(bike1.price);
Output:
20000
Here:
- brand, model, and price are properties.
- "Yamaha", "R15", and 20000 are their values.
Objects with Methods
We can also define a function inside an object. This is called a method.
const bike = {
brand: "TVS",
model: "Apache RR 310",
price: 250000,
petrol: "20L",
drive: function() {
console.log("Driving at 100 kmph");
}
};
bike.drive();
Output:
Driving at 100 kmph
CRUD Operations in Objects
We can perform basic operations on objects.
1. Create / Add a property
bike.stand = "Center Stand";
console.log(bike);
This adds a new property called stand.
2. Read a property
console.log(bike.brand);
Output:
TVS
3. Update a property
bike.petrol = "25L";
console.log(bike.petrol);
Output:
25L
4. Delete a property
delete bike.model;
console.log(bike);
This removes the model property from the object.
Top comments (0)