In our previous post, we’ve discussed, why you should learn JavaScript ,Cool facts about JavaScript and 3 unique ways to run JavaScript. In this post, we’ll discuss basic Concepts of JavaScript. So, Lets get started.
Building Blocks of JavaScript:
For any programming language these concepts are like building blocks but the only thing that differentiates is syntax. If you are familiar to any programming language then you can take a quick look.
Statements:
Statements are syntax constructs and commands that perform actions. In our previous post, we’ve discussed alert() function which alerts the user with an given value.
For example:
alert('Hello World');
Delimiter:
A semicolon may be omitted in most cases when a line break exists. This is done by a mechanism known as automatic semicolon insertion.
Let’s see one example
alert("Hello")
alert("JavaScript")
In some cases the JavaScript does not assume semicolon at that time you need to specify the semicolon explicitly. One of the case is square brackets […]
alert("Hello World")
[1,2].forEach(alert)
We recommend you to put semicolons between statements even if they are separated by newlines. It’s safer – especially for a beginner to use them.
Comments:
As time goes on, programs become more and more complex. It becomes necessary to add comments which describe what the code does and why.
One-line comments start with two forward slash characters //.
alert("Hello World") //This code shows the message Hello World
Multiline comments start with a forward slash and and an asterisk /* and end with an asterisk and a forward slash */.
/* This is an examples with two messages and a multiline comment.
*/
alert("Hello");
alert("world");
Variables:
A JavaScript application needs to work with information.Here is an example.
An online shopping- the information might include clothes being sold and a shopping cart. Here variables are used to store this information.
Inorder to create a variable use let keyword.
let message;
message="Horray, i know about let variable"; // the string is saved into the memory area associated to the variable.We can access it by variable name.
alert(message);
We can define variables in this multiline style:
let name='Charishma'
, gender='girl'
,age=20
Alternatively we can use var keywords to create a variable.
var message = 'Hello';
var is also used to store information but the only thing that differentiates is the variables created using let are bound to a block in which they are defined where as variables created using var keyword are global.
var x=3;
let y=1;
for(i=0;i<3;i++){
var x=2;
let y=2;
x=x+i;
y=y+i;
}
console.log(x)//4
console.log(y)//1
You can create a constant variable by using Const keyword. The data stored in constant variable cannot be manipulated.
const gender="female";
Variable naming :
The proper name declaration is very important. There are two limitations in JavaScript:
- The name must contain only letters,digits or the symbols $ and _.
- The first character must not be a digit.
Now, lets take one example problem that covers every basic concept-Palindrome.What are the variables required for this problem? yes, you’re right a const variable to store string and a var variable.
str1='malayalam';
const str=str1;
let count=0,i;
let len=str.length;
Ooh wait, what is the type of data we are storing in a variable.If you don’t know then don’t worry here comes the concept of datatypes.
Data Types:
JavaScript variables can hold many data types like-numbers,strings,objects and more. To operate on variables,it is important to know about the type.
JavaScript types are Dynamic:
Dynamic…what is that?-it means that same variable can be used to hold different data types.Let’s see an example.
let x; // Now x is undefined
x = 6; // Now x is a number
x = "Madhuri"; //Now x is a string
1.Strings: A string is a series of characters.You should declare a string with single or double quotes.
const str = 'malayalam';
2.Numbers: A number can be written with or without decimals.
let y = 5.88;
What happens when you combine int and string ?- It converts integer to string and performs string concatenation .Thus, you’ll get a string.
let x = 10 + 2 + "Manasa" //output-12Manasa
let y = "Manasa" + 10 + 2 //output-Manasa102
The above code produces different outputs because JavaScript evaluates the expression from left to right.
3.Booleans: It can have only two values: true or false.
let x = 6;
let y = 7;
if (x == y)
return true;
else
return false;
4.Arrays:
An array is an object that can store a collection of items. For suppose you want to store the details of 1000 employees. If you are using variables,you’ll have to create 1000 variables that is very complex to imagine whereas you can do the same with a single array. You can access the items by referring to its index number. In arrays index of the first element start from zero.Let’s see one example.
let employees = ["Tarun", "Vamsi", "Surya"];
console.log(employees[0]);
If you want to add more elements to the employees array,you can do it like this:
employees[3] = "Charishma";
You can also create an array using Array constructor like this:
let employees = new Array("Tarun", "Vamsi", "Surya");
5.Objects:
Many times, variables or arrays are not sufficient to stimulate real-life situations. JavaScript allows you to create objects that act like real life objects. A student or a home can be an object that have many unique characteristics of their own. You can create properties and methods to your object to make programming easier. If your object is a student,it will have properties like first name, last name, id etc and methods like changeAddress ,calculateRank etc. Let’s see one example.
let person = {
firstName:"Charishma",
lastName:"Prathipati",
age:20,
changeAddress: function() {//lines of code}
};
You can access properties and methods of an object like this:
person.firstName;
person.changeAddress();
Conditionals:
Sometimes, we need to perform different actions based on different conditions.To do that, we can use conditional statements.If a condition is true, you can perform one action and if the condition is false, you can perform another action.

1.If Statement:
You can use if statement if you want to check only a specific condition. Let’s see one example.
//Malayalam
if(count == len)
{
console.log("The string is a palindrome");
}
As we mentioned earlier about palindrome problem . If statement is used to compare the count number and length of the string if both are equal it prints the string is palindrome.
2.If-Else Statement:
You can use If-Else statement if you have to check two conditions. Let’s see one example.
As we had discussed earlier let’s see how conditional statements are used in palindrome problem.
//str=Malayalam
for ( i=0; i<len/2; i++){
if(str[i] !== str(len-1-i){
console.log("The string is not a palindrome")
}
else{
count++;
}
}
First of all let’s not bother about for loop ,coming to if and else statements here i’m comparing each and every letter. If the letter at index 0 and index -1 is same it increments count variable or else it prints ‘the string is not a palindrome‘ and the process goes on until the for loop exits.
3.If-Else If-Else statement:
You can use If…Else If….Else statement if you want to check more than two conditions. Let’s see one example.
let marks=50;
if(marks>=80)
{
console.log("You are passed with high score");
}
else if(marks>40 && marks<80)
{
console.log("You are passed");
}
else
{
console.log("You are failed");
}
//output-You are passed
4.Switch Statement:
- You can use the switch statement to execute one of many code blocks based on expression’s value. The switch expression is evaluated once. The comparison value will match either a statement value or trigger a default code block.
let grade='A';
switch(grade)
{
case 'A': document.write("Good job");
break;
case 'B': document.write("Pretty good");
break;
case 'C': document.write("Passed");
break;
case 'D': document.write("Not so good");
break;
case 'F': document.write("Failed");
break;
default: document.write("Unknown grade");
}
//output-Good job
The break and the default keywords:
The break statements indicate the end of a particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.
If there is no case match in the switch block then the interpreter automatically execute the statement present inside the default keyword. The default keyword does not need a break because it is used as the last statement in the switch block.
Loops:
Loops are useful when you have to execute the same lines of code repeatedly,for a specific number of times or as long as specific condition is true. For suppose, you want to type a “Hello World” message for 1000 times in your webpage. Of course, you will have to copy and paste same line 1000 times. Instead of that, if you use loops, you can complete this task in just 3 or 4 lines.

1.For Loop:
For loop execute a block of code a number of times. Let’s see how for loop is used in palindrome problem.
// str='Malayalam'
for ( let i=0; i<len; i++)
{
if (str[i] !== str[len - 1 - i])
{
console.log("The string is not a palindrome");
}
else
{
count++;
}
}
//Here the above given string is palindrome so the count will incremented.
Here, for loop is used to check whether the word is palindrome or not. It checks each and every letter ,if one letter does not match the required output then it prints the statement present in if block or else it iterates the count value.
2.For/In Loop:
The for-in loop is used to loop through an object’s properties. Let’s see one example.
let property;
let person = { firstName : "Charishma", lastName : "Prathipati", age : 20};
for (property in person)
{
console.log(property);
console.log("<br/>");
}
/* output-firstName
lastName
age */
Here the properties are printed line by line.
3.For/Of Loop:
The for..of loop is used to loop through the values of an iterable objects. It lets you loop over data structures that are iterable such as Arrays, Strings, Maps and more.
let languages = ['C', 'Python', 'Java', 'JavaScript'];
let x;
for(x of languages)
{
console.log(x + "<br/>");
}
/*C
Python
Java
JavaScript*/
4.ForEach:
You can use forEach() method on Arrays,Maps,and Sets datatype. This method executes a provided function once for each array element. You can pass a method / callback or write logic with in forEach method. It does not execute the function for empty array. Let’s see one example.
let numbers = [1,2,3];
numbers.forEach((item) =>
{
console.log(item);
});
//123
5.While Loop:
The while loop loops through a block of code as long as a specified condition true. Let’s see an example.
num=1
while(num<5){
console.log(num);
num++;
}
/*1
2
3
4*/
6.Do-While Loop:
The do-while loop is a variant of the while loop. This loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested. Let’s see one example.
var num=1
do{
console.log(num);
num++;
}
while(num<5)
/*1
2
3
4*/
Functions:
Functions are very important and useful in any programming language as they make the code reusable. A function is a block of code which will be executed only if it is called. If you have a few lines of code that needs to be used several times, you can create function including the repeating lines of code and then call the function wherever you want. Let’s see one example.
function palindrome (strvar)
{
//Lines of code to be executed
}
Upto now, we have seen the palindrome example in separate parts now we will see the entire logic of palindrome problem .
function palindrome(str1) {
const str=str1;
var count=0;
let len = str.length;
for (let i = 0; i < len; i++) {
if (str[i] !== str[len - 1 - i]) {
console.log("The string is not a palindrome.");
break;
}
else{
count++;
}
}
if(count==len)
console.log("The string is a palindrome.");
}
palindrome('malayalam');
//output-The string is a palindrome.
Here we are sending a string ‘malyalam’ as a input in function call. You can download the whole code from github repo.
Conclusion:
In this blog, we have discussed the basics of JavaScript – statements, delimiters, variables, datatypes, conditionals, loops and functions. In the next post, we’ll discuss error handling, maps, filters and many more. Until then, Stay home. Stay safe. Cheers✌️.
2 responses to “Basics of JavaScript”
[…] our previous post , we’ve discussed, basic Concepts of JavaScript like, statements, delimiter, comments, […]
LikeLike
Very useful information!
LikeLike