DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

JavaScript Learning: Loops, Functions, Strings, Arrow Functions and Objects

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;
}
Enter fullscreen mode Exit fullscreen mode
output: 1 1 1 1 1
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode
output:4 3 2 1 0
Enter fullscreen mode Exit fullscreen mode

Printing Even Numbers

Let's print even numbers from 2 to 10.

let count = 2;

while (count <= 10) {
    console.log(count);
    count = count + 2;
}
Enter fullscreen mode Exit fullscreen mode
output: 2 4 6 8 10
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
output: Hello 6
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
Output: Fail
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode
Output: Monday
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode
Output:

Biryani ready
Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode
Output:

20
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
Output:

Biryani ready
Biryani
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode
Output:

basmati undefined
Enter fullscreen mode Exit fullscreen mode

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');

Enter fullscreen mode Exit fullscreen mode
Output:

basmati chicken
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
Output:

Sum: 390
Average: 78
C Grade
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

Arrow Function:

const display = () => "Hello";
Enter fullscreen mode Exit fullscreen mode

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'));
Enter fullscreen mode Exit fullscreen mode
Output:

Hello Vanitha
Enter fullscreen mode Exit fullscreen mode

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'));
Enter fullscreen mode Exit fullscreen mode
Output:

Hello Vanitha
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode
Output:

H
o
Enter fullscreen mode Exit fullscreen mode

Objects in JavaScript

For example, let's create a bike object.

const bike1 = {
    brand: "Yamaha",
    model: "R15",
    price: 20000
};

console.log(bike1.price);
Enter fullscreen mode Exit fullscreen mode
Output:

20000
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode
Output:

Driving at 100 kmph
Enter fullscreen mode Exit fullscreen mode

CRUD Operations in Objects

We can perform basic operations on objects.

1. Create / Add a property


bike.stand = "Center Stand";

console.log(bike);
Enter fullscreen mode Exit fullscreen mode

This adds a new property called stand.

2. Read a property

console.log(bike.brand);
Enter fullscreen mode Exit fullscreen mode
Output:

TVS
Enter fullscreen mode Exit fullscreen mode

3. Update a property

bike.petrol = "25L";

console.log(bike.petrol);
Enter fullscreen mode Exit fullscreen mode

Output:

25L
Enter fullscreen mode Exit fullscreen mode

4. Delete a property

delete bike.model;

console.log(bike);
Enter fullscreen mode Exit fullscreen mode

This removes the model property from the object.

Top comments (0)