DEV Community

Bipon Biswas
Bipon Biswas

Posted on

Programming Fundamentals using JavaScript

Programming Fundamentals using JavaScript

Today we will learn about the origin of the fundamentals of programming languages. If we know about the origin, we don't have to worry about these things anymore. The fundamentals of programming languages ​​are:

  • Variables
  • Operators
  • Conditions
  • Loops
  • Arrays
  • Objects
  • Functions
  • Expression vs Statement

Variables

We know variable means variable. Beginners have a problem where to take variables and where not to take them. There are some tricks for this. Before that we need to know what is the function of the variable? Simply put, variables help us make anything dynamic. That's the only job. Apart from this, the variable has no other function. It's more like a pot. The larger the container, the more space it will take. It means more memory is needed. So what is the need for extra memory? It is possible to take variables less. Then our application will be much lighter. But still we have to take variables. As if we will drink water. How will this water come to us? First, the water from below the ground is stored in a tank under the house through pipes and pumps. Then through another pump it goes on the roof and is stored in another tank. From there it is distributed from house to house through piping. Tap at home Through that water we accumulate in the filter. After filtering, we take that water in a jug or bottle. Then when we need to drink water, we drink water from a jug or bottle into a glass. Our purpose is to drink water, so it is necessary to store water in the middle? If we could not keep the tank, it would not be possible to distribute it to everyone's house. If I didn't put it in the filter, I couldn't purify the water. So variables are also like that. They store data. If we don't take the variable then we can't use the data a second time. It was not possible. If I didn't put it in the filter, I couldn't purify the water. So variables are also like that. They store data. If we don't take the variable then we can't use the data a second time. It was not possible. If I didn't put it in the filter, I couldn't purify the water. So variables are also like that. They store data. If we don't take the variable then we can't use the data a second time.

console.log('Bipon Biswas', 'Bipon Biswas'.length); // Bipon Biswas 12
Enter fullscreen mode Exit fullscreen mode

In the above example if we want to do it with any other name then it is not possible. To do that, you have to drop the current name. Because in case of static code nothing can be changed at runtime. Now the question may come runtime and compile time?

console.log('Bipon Biswas', 'Bipon Biswas'.length); // Bipon Biswas 12 
throw new Error('Something wrong'); // Error
Enter fullscreen mode Exit fullscreen mode

There is nothing wrong with the program here. But while running the program it shows an error. This is called runtime error. The time the program runs is called runtime.

console.log('Bipon Biswas', 'Bipon Biswas'.length); // Bipon Biswas 12
121354644dsfsdf
Enter fullscreen mode Exit fullscreen mode

In this case the first code will not execute. will show error directly. Means he got error in code while compiling. This is called a compile time error.

Now we can change many things dynamically at runtime. Like can give some input, can fetch something from internet, can click with mouse. All this happens at runtime. But when we work with static data like in the first example, we cannot change the data inside the log in any way. For that we need to take variables. Whenever we look at the data we will take a variable.

let name = 'Bipon Biswas';
console.log(name, name.length); // Bipon Biswas 12
Enter fullscreen mode Exit fullscreen mode

Variables have some advantages. The first benefit is that we took this data for Bipon Biswas. Now I want to take for Mehdi Hasan, or take for Mead Ahmed Fahim. In that case, only name the data in it is changed. Another advantage is that it is used name in only two places. It could have been two thousand or two hundred thousand. Now if I want to change the data for some reason, is it possible for me to change two lakh places? In that case, if we take variables, we will change only one place. No need to run to the remaining two lakh places.

Another example will make it clear how to dynamically change data at runtime through variables.

const names = [
    'Bipon Biswas',
    'Aditya Chakraborty',
    'Abu Rayhan',
    'Shaker Hossain',
    'Akib Ahmad',
    'Alvi Chowdhury',
];
let index = -1;
let person = names[++index];

setInterval(() => {
    person = names[index++];
    console.log(person, person.length);

    if (index === names.length) {
        index = 0;
    }
}, 1000);
Enter fullscreen mode Exit fullscreen mode

Now if you run the program you will see that the names will change one after the other after 1 second. When it is finished, it will start again from the beginning. There will be no end to it. Now if we just set a name without using variables, then only that name will be printed repeatedly. Dynamic is no more. And we program to make everything dynamic. So wherever we see the data we will assume the variable. Let's go to the extra memory.

Now let's take two important terms let and const. When let and when const to use. We will use it when we see that no data is being updated in the const future. Then we can't update that data whether we want to or by mistake. If you try to do it, an error will appear. And we will use the data which has a chance to be updated later let. names Now here updating in the example above . So we const used But index and person we updated later. So we let used there. The rule is that we assume everything first const. After that if any data update is seen we will do it later let. By doing this, we will have less chance of making mistakes.

So it appears that variables are used to dynamically update data at runtime.

Operators

We are all familiar with the operator. From childhood we add, subtract, multiply, divide. There we used some mathematical operators. Operators in programming are also the same. Operators are used in programming languages ​​to perform mathematical calculations. There is no more work. Operators are basically functions. In languages ​​that have operator overloading, we create functions to perform operator operations. such as

add();
mod();
lessThan();
Enter fullscreen mode Exit fullscreen mode

add We can create and use functions to add . mod Using the function we can perform modulus operation, lessThan we can check if our value is small or not. But there is no operator overloading in JavaScript. So we don't need to create functions. JavaScript has already created these functions through some symbolic representation, so that our work is much easier. add()Instead of we + use , mod() instead of %, lessThan instead of we < use . When it comes to operators, there is not much to say about the details.

Conditions

The condition is called the brain of the computer. Based on this condition the computer decides what action to take. Although the computer has no power to take decisions. We write various logics to make the computer take a decision. Now to write logic we need condition. We are constantly using the condition in our daily life. For example, if the sky is cloudy then I will go out with an umbrella, otherwise I will not go out with an umbrella. It is a condition. Again suppose my office is at 9 o'clock. Now if I can leave the house by 8 o'clock then I will go by bus or take CNG. It is also a kind of condition. Again, since today's class will teach basic, I will not join today's class, if advanced will be taught then I will join. Now let's see how we can convert this condition into code.

if (studyBasic) {
    wontJoin();
}

if (studyAdvanced) {
    join();
}

if (teacherSpeaks) {
    silent();
}

if (!teacherSpeaks) {
    shout();
}
Enter fullscreen mode Exit fullscreen mode

We try to understand it a little. I will not join today's class if basic is taught. I will join if advanced teaching. If the teacher speaks, we will all be silent. If he doesn't talk we all talk together. This is how we find conditioning in our daily activities. Everything is frozen except the condition. 50% of programming language is condition, and 50% is loop.

Now the condition can be written in 3 ways. That is, it has 3 scenarios. Let's look at the following code a little earlier. I will explain later.

// Scenario 1 - Single branch
// if condition
if (hasMoney) {
    buyPhone();
}

// Scenario 2 - Two branches
// if else condition
if (toss === 'head') {
    win();
} else {
    loss();
}

// Scenario 3 - Multiple branches
// else if
let a = 1,
    b = 2;
if (a > b) {
    big();
} else if (a < b) {
    small();
} else {
    same();
}
Enter fullscreen mode Exit fullscreen mode
  • Scenario - 1: It is single branch. There cannot be more than one case here. In that case we will use this scenario. if condition It is called It is said here that I will buy a phone if I have money. If not, it will go as it is. More than one case is not needed here. So here we if condition will just use

  • Scenario - 2: It basically depends on two branches, i.e. it will have maximum two outcomes. if else condition It is called In such a scenario, more than two conditions will never be possible. Like if the toss comes head then I win the toss or lose. There is no possibility of more than these two results.

  • Scenario - 3: It is multiple branches. If there is more than two possible outcomes then we will use it. This type of scenario is else if condition called ie if a > b a is greater than b. If a < b so then a will be smaller than b. Otherwise both will be equal. There are more than two outcomes here. So here we used multiple branches.

The condition depends mainly on the outcome. I have to write the condition in such a way that how many outcomes can occur.

Loop

The loop has only one function. Doing the same thing over and over again. For example, one of our clients came and said that Bangladesh is now 51 years old. We will do something in our application that says 'We love Bangladesh' 51 times. We are very smart, we wrote 51 times in 1 hour and console.log('We love Bangladesh')showed it to the client. The client said no bro 51 times. Since Bangladesh became independent in 1971 we want 1971 times. Now I wrote the same code over and over again for 3 days and showed it to the client in a broken state. The client said, no. Not like this. We will print it 30 lakh times in honor of 30 lakh martyrs. I went and researched and found that there is repeat()a function in JavaScript called Now it's easy. I can write as many times as the client wants by writing just one line of code. I also wrote the following code and took it to the client with great pride in just 10 minutes.

console.log('We love Bangladesh\n'.repeat(10));
Enter fullscreen mode Exit fullscreen mode

I am flying in the sky. Thank you JavaScript for this function. This time the client was very happy. But after a while he said, Well, 30 million times have been printed. How will the user understand it has been done 3 million times. It is better if you give a number before each one. Now it's a hand on the head. How to dynamically do so many numbers? Programming languages ​​have come up with simple solutions for that. That is the loop. With loops we can easily repeat the same task as many times as we want.

for (let i = 1; i <= 3000000; i++) {
    console.log(i, 'We love Bangladesh');
}
Enter fullscreen mode Exit fullscreen mode

Now all problems are solved. Loops make our repetition work a lot easier. Assume that the Carly Brackett block in the loop is a new js file. We can write any valid js code here. But remember that the code inside this block will be executed multiple times.

There are mainly 3 types of loops in JavaScript. Then the number of loops increased to facilitate various tasks. Even if there are multiple IP loops, the problem can be solved by using any one loop.

for loop

  • range
  • for in
  • for of

while loop
do while loop

For Loop

With the for loop, we can do two types of work, while and do while. Why did the for loop come now, what is its function? Let's take our previous example. Here the client asked to print 3 million times. That means I know my range. I know my starting point, and I know where to stop. In this case we will always use a for loop. That means we will use for loop in cases where we know the starting point and ending point. Again there are 3 types of loops within the for loop. One is range related that I saw. Another for in that we can use on arrays or objects. We can work with using in which doesn't have to give a range. We will see that later. Another is the for loop. It came to work easily after iterators. It is also used to work with arrays or any iterator, We will discuss that later. This will be very useful when we work with asynchronous data.

While Loop

We can also do for, do while with while loop. Now why did it come, what is its function? Suppose the client tells us to run the loop randomly. There is no such thing as having to run from 1. There will be just a random number and the words 'We love Bangladesh' will be next to it. There is no description of how long to run. Again the infinite loop cannot be executed. The client said you do a job. My printing will stop whenever the number continuously reaches 71. The following example will be more clear to you:

while (true) {
    let num = Math.ceil(Math.random() * 100);
    console.log(num, 'We love Bangladesh');
    if (num === 71) break;
}
Enter fullscreen mode Exit fullscreen mode

The difference with the for loop is that the for loop had 3 parts. Initialize, condition, increment/decrement. But the while loop has only one part, that is the condition. And condition means either true or false. That means we will use a while loop when I don't know the range, just the condition.

Do While Loop

But with Do While we cannot do for or do while. It is a special type of loop. Why is it used? Suppose in the while loop example the condition is false instead of true. Then it won't show the output even once. I want the output to show true or false at least once. In that case we will use do while loop. This is also possible with a while loop. But it can be done a little better with doo while. Let's see an example.

do {
    console.log('It will run at least once');
} while (false);
Enter fullscreen mode Exit fullscreen mode

Although its condition is false, it will show the output at least once. This is the concept of this loop.

Array

One of the most neglected data structures and one of the most powerful data structures. Using arrays we can create many complex data structures. Like graph, heap, stack, queue. Array is very powerful and perfect data structure to work with 2/3 lakh data. The question is why the array is coming and what is the function of the array? We want to store the names of some people. We can do that with variables.

const name1 = 'Rayhan';
const name2 = 'Alvi';
const name3 = 'Anik';
const name4 = 'Arjun';
const name5 = 'Ayman';
Enter fullscreen mode Exit fullscreen mode

Now I want to convert these names to lowercase. For that we need to capture and convert each one.

console.log(name1, name1.toLowerCase());
console.log(name2, name2.toLowerCase());
console.log(name3, name3.toLowerCase());
console.log(name4, name4.toLowerCase());
console.log(name5, name5.toLowerCase());
Enter fullscreen mode Exit fullscreen mode

Now, instead of 5 names, there could have been 5 lakh names. If you have to capture and convert each of them, then it is an impossible matter. For that we need a way to put all the names in a variable. Now put it in a variable.

const persons = 'Rayhan, Alvi, Anik, Arjun, Ayman';
Enter fullscreen mode Exit fullscreen mode

Now the problem here is that they all become one big string. How to distinguish from here? Let's store separately.

const persons = 'Rayhan', 'Alvi', 'Anik', 'Arjun', 'Ayman';
Enter fullscreen mode Exit fullscreen mode

But now when we want to run the program, we will get a very big error. To solve this problem we have a data structure called array. [] Just putting something before and after the example above will make an array.

const persons = ['Rayhan', 'Alvi', 'Anik', 'Arjun', 'Ayman'];
Enter fullscreen mode Exit fullscreen mode

How to extract data from here? Each array element has a position number. This is called index. Index starts from 0. Then the index of the 1st position is 0, the index of the 2nd position is 1, and the index of the 3rd position is 2. Then we get a name of the array and get a number. The advantage of getting numbers is that we can easily calculate here. And that's the power of arrays. Now let's see how to extract the data from the array.

const persons = ['Rayhan', 'Alvi', 'Anik', 'Arjun', 'Ayman'];
console.log(persons[0]);
console.log(persons[1]);
console.log(persons[2]);
console.log(persons[3]);
console.log(persons[4]);
Enter fullscreen mode Exit fullscreen mode

This way we can extract all the names. Now here it looks all the same except the index is different. It means the same work is going on again and again. So here we can execute a loop.

const persons = ['Rayhan', 'Alvi', 'Anik', 'Arjun', 'Ayman'];

for (let i = 0; i < 5; i++) {
    console.log(persons[i]);
}
Enter fullscreen mode Exit fullscreen mode

Now if the program is run then it will be seen that all the names will be printed nicely. There is a problem here. We add two more names to understand the problem.

const persons = ['Rayhan', 'Alvi', 'Anik', 'Arjun', 'Ayman', 'Ayuub', 'Bidyut'];

for (let i = 0; i < 5; i++) {
    console.log(persons[i]);
}
Enter fullscreen mode Exit fullscreen mode

Now if the program is run Ayman the loop will stop as soon as it is seen. Because the range of my loop is given index must be less than 5. To solve this problem we persons.length can replace 5 dynamically. Then the array will be dynamically updated as the length increases. Now if we do the first example with an array and a loop, what will it look like?

const persons = ['Rayhan', 'Alvi', 'Anik', 'Arjun', 'Ayman', 'Ayuub', 'Bidyut'];

for (let i = 0; i < 5; i++) {
    console.log(students[i], students[i].toLowerCase());
}
Enter fullscreen mode Exit fullscreen mode

Then you can understand how powerful the array is. Loops are closely related to arrays. With these arrays and loops we can do many tasks easily and in less time.

What type of data can we store in array? Almost all programming languages ​​have some limitations to storing data in arrays. And only one data type can be stored in an array. In this respect JavaScript has given complete freedom. Any data type can be stored in JavaScript. Even data of different data types can be stored in an array. We can understand if we look down a little.

const nums = [1, 2, 3, 4, 5, 6];
const bools = [true, true, false, false];
const nulls = [null, null, null];
const undefineds = [undefined, undefined, undefined];
const arrayOfArray = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
const mixed = [true, null, 'Str', 5, [12, 2, 4]];
Enter fullscreen mode Exit fullscreen mode

Objects and functions can also be stored in arrays. Since we haven't discussed objects and functions yet, we haven't shown them here. An array can store data of different data types, but we will store only data of the same data type in an array. The reason is suppose you created an array of student names. Now if you put their address, phone number there then it will be difficult to find the name. So data of the same type should be stored in an array.

Arrays have some functionalities. We can think of an array as a database. In memory database. Where we can create data, read it, update it if necessary and delete data if we want. This whole operation is called CRUD - Create, Read, Update, Delete operation. CRUD is the function of all the data structures in the world. There is some more discussion about arrays. But to discuss arrays we need to talk about objects first.

Object

In the array we have entered the names of some students. But now if we want to store the information like their email, age and whether they are present in the current class then there is a problem with array. We try to see what the problem is.

const student = ['Abu', 'Rayhan', 'rayhan@example.com', 25, true];
sendEMail(students[0]);

function sendEmail(email) {
    console.log('Sending Email to ', email);
}
Enter fullscreen mode Exit fullscreen mode

Now we see what could be the problem here. At first glance there is no way to tell which is which type of information. It means that the code has no readability. When we go to email someone, we need to remember how many numbers index that information. Now, here are 5 data that can be remembered somehow. If it is 5000 then it will be very difficult to remember. To overcome this problem we try to write it differently.

const student = {
    firstName: 'Abu',
    secondName: 'Rayhan',
    email: 'rayhan@example.com',
    age: 25,
    attend: true,
};

sendEMail(students.email);

function sendEmail(email) {
    console.log('Sending Email to ', email);
}
Enter fullscreen mode Exit fullscreen mode

Even if some texts are written more, the code can be easily read to understand which information is which. Now I don't need to remember the index anymore. Just put a dot (.) at the end of the variable name. It is much more readable, much more informative than before.

Now we can store the information of many students in an array if we want. how can i let's see

const student1 = {
    firstName: 'Abu',
    secondName: 'Rayhan',
    email: 'rayhan@example.com',
    age: 25,
    attend: true,
};

const student2 = {
    firstName: 'Alvi',
    secondName: 'Chowdhury',
    email: 'alvi@example.com',
    age: 25,
    attend: true,
};

const student3 = {
    firstName: 'Akib',
    secondName: 'Ahmad',
    email: 'akib@example.com',
    age: 25,
    attend: true,
};

const allStudents = [student1, student2, student3];

for (let i = 0; i < allStudents.length; i++) {
    sendEmail(allStudents[i].email);
}

function sendEmail(email) {
    console.log('Sending email to', email);
}
Enter fullscreen mode Exit fullscreen mode

We will create different objects for each student. We will then store each object in an array. You have also proven that objects can be stored in arrays through this example. Now I want to send the same email to all students together. In that case we can easily send email to all at once as per above code by looping over our array. By running the loop, first we need to grab that data with the index number of the array. After that, according to the rules of the object, put (.) and then give the property name and the work is done. You saw a small example of how we can make programs dynamic by combining arrays and objects. Do this over and over again as you build larger applications.

Functions

The function we make works a lot like a loop. We use loops to do the same thing over and over again. We will also use functions to do the same thing over and over again. So why do we use functions to have loops?

Functions we can use in different places as we like. I can call the function as I like. We can reuse functions because functions have a name. But the loop has no name. So I can't use the loop wherever I want. If the loop starts again, I need to either break it, or let it continue until the loop ends. We have no control over the loop. But we can use the function in different places according to our needs. We can control according to our needs. If I take a few lines from the previous example

for (let i = 0; i < allStudents.length; i++) {
    // sendEmail(allStudents[i].email);
    console.log('Sending email to', allStudents[i].email);
}

// function sendEmail(email) {
//     console.log('Sending email to', email);
// }
Enter fullscreen mode Exit fullscreen mode

We could do the same thing without writing functions. But the line inside the loop will not work anywhere outside the loop. But functions can be called anywhere. Again suppose I need the full name in another place, should I continue that loop again. No, we'll do it with functions. In this case we use a build in function.

allStudents.forEach((item) => console.log('Email ', item.email));
allStudents.forEach((item) =>
    console.log('Full Name ', item.firstName, item.secondName)
);
Enter fullscreen mode Exit fullscreen mode

forEach In this case we used the function instead of repeating the loop . The biggest advantage of the function is that it can be used multiple times anywhere.

When to use function and loop when? Functions when we do the same work in two different places. And if in one place then loop. For example if we are sending an email, and we need the full name in the email, we can do this with a loop. But if we send email in one place, and in other place need full name to create student list then loop will not work. We need to use the function It will be very difficult to understand at first. If you practice slowly, it will get stuck in your head.

The rules for writing functions are given below:

function nameOfFunction() {
    console.log('Hello', 'Bipon');
}

nameOfFunction(); // Hello Bipon
nameOfFunction(); // Hello Bipon
nameOfFunction(); // Hello Bipon
Enter fullscreen mode Exit fullscreen mode

Now every time I call here it gives the same output. If we need this same output in different places then we will create function like this. Now I want to set the name dynamically. The name I input will be there. For this we need to take a variable inside the parenthesis. This is called a parameter. Let's look at that.

function nameOfFunction(name) {
    console.log('Hello', name);
}

nameOfFunction('Bipon'); // Hello Bipon
nameOfFunction('Fahim'); // Hello Fahim
nameOfFunction(); // Hello undefined
Enter fullscreen mode Exit fullscreen mode

When we call the function, we will put our name as an argument in place of that parameter. Parameters are the variables that you pass while writing the function. And argument is what you pass in the form of value when calling the function. If you don't sit now, it undefined will show. Here we can do a simple task if user doesn't give name then we can show him a message to give name. Means can handle an error.

function nameOfFunction(name) {
    if (!name) {
        console.log('Please provide your name');
    } else {
        console.log('Hello', name);
    }
}

nameOfFunction('Bipon'); // Hello Bipon
nameOfFunction('Fahim'); // Hello Fahim
nameOfFunction(); // Please provide your name
Enter fullscreen mode Exit fullscreen mode

Hope everyone can understand this example. See another example of why we need functions. Suppose we want to generate a random number between 1 and 10. Then write a formula to generate random numbers.

const randomNumber = Math.floor(Math.random() * 10);
Enter fullscreen mode Exit fullscreen mode

Now if you want between 1 and 100

const randomNumber = Math.floor(Math.random() * 100);
Enter fullscreen mode Exit fullscreen mode

It should be written like this. Now instead of writing so many times we make it a function.

function generateRandomNumber(max) {
    const randomNumber = Math.floor(Math.random() * max);
    return randomNumber;
}

console.log(generateRandomNumber(10));
console.log(generateRandomNumber(100));
console.log(generateRandomNumber(1000));
Enter fullscreen mode Exit fullscreen mode

Now I can generate random numbers as many times as I want. Now I want to generate a random number between two numbers.

function generateRandomNumber(min, max) {
    const randomNumber = Math.floor(Math.random() * min + (max - min));
    return randomNumber;
}

console.log(generateRandomNumber(5, 10));
console.log(generateRandomNumber(85, 100));
Enter fullscreen mode Exit fullscreen mode

Then understand how functions make our work easier.

Expression vs Statement

Before we understand this, let's look at some examples

const name1 = 'Rayhan'; // Statement
const name2 = 'Alvi'; // Statement
const name3 = 'Anik'; // Statement
const name4 = 'Arjun'; // Statement
const name5 = 'Ayman'; // Statement

const students = [
    'Rayhan',
    'Alvi',
    'Anik',
    'Arjun',
    'Ayman',
    'Ayuub',
    'Bidyut',
]; // Statement

console.log(students[0]); // Expression
console.log(students[1]); // Expression
console.log(students[2]); // Expression
console.log(students[3]); // Expression
console.log(students[4]); // Expression

for (let i = 0; i < students.length; i++) {
    console.log(students[i], students[i].toLowerCase()); // Expression
} // Statement

name1.sendEmail(); // Expression
name2.sendEmail(); // Expression
name3.sendEmail(); // Expression
name4.sendEmail(); // Expression
name5.sendEmail(); // Expression

const nums = [1, 2, 3, 4, 5, 6]; // Statement
const bools = [true, true, false, false]; // Statement
const nulls = [null, null, null]; // Statement
const undefineds = [undefined, undefined, undefined]; // Statement
const arrayOfArray = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]; // Statement
const mixed = [true, null, 'Str', 5, [12, 2, 4]]; // Statement

const student1 = {
    firstName: 'Abu',
    secondName: 'Rayhan',
    email: 'rayhan@example.com',
    age: 25,
    attend: true,
}; // Statement

const student2 = {
    firstName: 'Alvi',
    secondName: 'Chowdhury',
    email: 'alvi@example.com',
    age: 25,
    attend: true,
}; // Statement

const student3 = {
    firstName: 'Akib',
    secondName: 'Ahmad',
    email: 'akib@example.com',
    age: 25,
    attend: true,
}; // Statement

const allStudents = [student1, student2, student3]; // Statement

for (let i = 0; i < allStudents.length; i++) {
    sendMail(allStudents[i].email); // Expression
} // Statement

function sendMail(email) {
    console.log('Sending email to', email);
} // Statement

allStudents.forEach((item) => console.log('Email ', item.email)); // Expression
allStudents.forEach((item) =>
    console.log('Full Name ', item.firstName, item.secondName)
); // Expression

function nameOfFunction(name) {
    if (!name) {
        console.log('Please provide your name');
    } else {
        console.log('Hello', name);
    }
} // Statement

nameOfFunction('Murshed'); // Expression
nameOfFunction('Fahim'); // Expression
nameOfFunction(); // Expression

function generateRandomNumber(min = 1, max) {
    const randomNumber = Math.floor(Math.random() * min + (max - min)); // Statement
    return randomNumber; // Expression
} // Statement

console.log(generateRandomNumber(5, 10)); // Expression
Enter fullscreen mode Exit fullscreen mode

The basic difference between Expression and Statement is that Expression returns something at the end of the day, produces data, and stores it somewhere. As such function call is a type of expression. And the statement does not produce any data, cannot be stored anywhere, does not return anything. Function writing is statement, and function call is expression. Because write function doesn't return anything until it is called. Again if the arrow function is written as an expression it is being stored in a variable.

Where to use array and where to use object

Where the terms are singular we will use object. Where Plural we will use Array. Like one phone - object, many phones - array, person - object, people - array, member - object, members - array. Objects where information about someone or something. Where there is more than one person or more than one object, we will use array. Just keep this in mind. Don't confuse arrays with objects in life anymore.

There are certain points to emphasize to get a good grip on JavaScript

  • Arrays
  • Objects
  • Functions and Functional Programming
  • Basic OOP

Top comments (0)