JavaScript 101

Hi, I'm an undergraduate student majoring in computer science and engineering. I'm learning full stack development right now and trying to share my learnings here. I'm enthusiastic about exploring new technologies. Apart from that, I am a sports enthusiast and enjoy watching test cricket.
Variables
For any given program, there are 3 elements: input, processing, and output. When the user interacts with the website or application and provides some inputs we process those inputs. We need something to store that input data, and other internal data required for processing the input this is where variables come into the picture.
To use variables we need to declare them first which in layman terms is creating a variable. You can think of a variable as a box, we can put something in the box, remove it and put something else or pass the box around.
var variableName = 25;
variableName = "Hi";
This is how we create a variable in JavaScript. We use keyword var and then give a name to it. We can store numbers, strings in this variable. This process of storing something in a variable is called an assignment. We can also replace the value assigned to the variable and this process is called reassignment.
Also, while naming variables there are few rules we need to follow. We can't start a variable name with a digit however we can use them at the end or in between. The only special characters allowed anywhere in the variable name are _ and $. Words like var are reserved and we cannot declare a variable with this name.
// valid variable names.
var jack;
var jack25;
var userName;
var NAME;
var jack$Lee;
var user_name;
// in-valid variable names.
var 1jack; // digits at start are not allowed
var user-name; // special characters not allowed except $ and _
var jack&jill; // same as above
A few good practices to follow while naming variables:
- It should be readable, use very logical names, do not use abc, xyz as names. In a project, people work in a team. They should be able to figure out the purpose of the variable from the name.
- When a variable has multiple words, use the camelCase method, which means making the first letter of a new word capital. You can read more here.
For cases where we are sure that we don't want the data stored in a variable to be updated ever in the code, we can use keyword const, instead of var.
const myRollNumber = "36";
const piValue = "3.14";
myRollNumber = "55" // error, you cannot update const values.
Data Types
The data or values we store in variables are of certain types, which is why we call them data types. A variable can store data in form of numbers, strings, etc.
Here are a few commonly used data types in JavaScript:
Number: This includes basic integral numbers as well as decimal numbers which we call floating-point numbers. There are few special numeric values too like
NaN(not a number) andinfinity(when we divide the result by 0)var num = 34; var decimalNum = 23.6789;String: For assigning string values to variables, we need to use either single quotes or double quotes and both of them are the same there is no difference whatsoever
var string1 = 'Jack'; var string2 = "Jack";Boolean: It has only two values
trueandfalse. Most of the time it is used as a flag for giving a signal to process something in the code.var allAnswersCorrect = true; allAnswersCorrect = false;null: It's a unique type, it means empty or nothing. Anullvalue means the value is unknown.undefined: Again this one is a unique type, which means that no value has been assigned to the variable.var num1; var num2 = null;As we assign nothing to
num1, it has the valueundefined.num2will have the valuenullas we assign it anullvalue. When we don't assign any value to a variable it gets the default valueundefined, but if we want to give a variable no value it is better to usenullas we can differentiate whether the value was given by us, or it was a default value.
All the types discussed above are primitive data types because they can contain only 1 value either a string, number, boolean, etc.
If we want to check whether the given input is a string or number, we can use the typeof operator. It returns the data type as a string i.e. in " "
typeof 5; // "number"
typeof "hi" // "string"
typeof false // "boolean"
Basic mathematical operators
Commonly used operators in JavaScript: + , - , *** , / , % , ****
Operands: These are the values to which the operators are applied.
There are two types of operators, unary which require only 1 operand and binary which requires 2 operands.
var num = - num1; // -ve
var sum = num1 + num2;
An example of a unary operator is the negation of a number which can be seen in the first line. The second line is a binary operation where we are adding two numbers.
Difference between / and %: Both are binary operators but / returns the quotient value and % is used to return the remainder value.
var numCube = (5 ** 3); // 5³
var numSquareRoot = (9 ** (1/2)); // which is same as 9 to the power 1/2 = 3
** operator is used for adding exponents to a number.
String concatenation: It basically means adding 2 strings. It only works with operator +. The rest of the operators when used with strings convert the string to numbers.
var string1 = "user";
var string2 = "Name";
sum = string1 + string2; // sum = userName
Conditional statements
There are frequent situations in coding, where while solving a problem we need to do certain specific processing based on different conditions. In such cases, we need to use conditional statements. In JavaScript, we use the if-else statements when we have only 2 conditions, and for multiple conditions, we use the if - else if statements.
if (condition1) {
//processing
}
else if (condition2) {
//processing
}
else if (condition3) {
//processing
}
else {
//processing
}
Whenever the condition in ( ) becomes true, the { } block is processed. If not true, else block is processed. Even when 2 or more conditions are true in if - else if only the first true condition block will be processed, others will be skipped.
Else if statement can be used any number of times, the if and else statements can be used only once. The else statement is an optional statement, we can skip it if we do not need it in some cases.
Logical operators
We generally use these operators in conditional statements that we covered above.
- Logical AND ( && ): This is a binary operator, it requires 2 operands or we can say it requires 2 conditions. It returns the value as
trueonly if all conditions aretrue, even if 1 condition isfalseit will return the value asfalse. - Logical OR ( | | ): This is a binary operator too, it requires 2 operands. It returns the value as
falseonly if all conditions arefalse, even if 1 condition istrueit will return the value astrue. - Logical NOT ( ! ): This is a unary operator, it requires only 1 operand or condition. What it does is, it negates the value. Example, 0 = false and 1 = true, then !0 = true.
if (condition1)
//processing
}
else if (condition2) {
//processing
}
else if (condition3) {
//processing
}
else {
//processing
}
Few more operators:
- Assignment operator: We already saw and used this while we learnt the topic variables, when we store some value or data in a variable, we use = operator.
Increment-Decrement operators: As the same suggests, we use these to increment or decrement the value stored in variables. It increases the value as well as assigns it to the variable which means it updates it basically.
counter++; // is same as counter = counter + 1;There are other operators too like bitwise operators ( &, ~, ^, >>, <<, | ) which I won't be covering in this blog.
Looping Statements
Imagine if someone asks you to print a statement 100 times, without loops, you will probably have no solution but to write the statement once and paste it 100 times. Not only is this pretty boring, but it is also inefficient and time-consuming.
That is the reason why we study looping statements, common ones are the while loop and the for loop.
- While loop: It has simple logic, the code block { } which is called the loop body will keep getting processed or we say iterated until the condition in the parentheses ( ) is
true. As soon as the condition isfalse, the loop is terminated. So the cycle of events followed is condition check(true), the loop body executes, condition check(true), the loop body executes, condition check(false), the loop terminates. - For loop: This one is the most used loop in JavaScript. Again the same logic as above, the only difference here is we use
forloop when we need a counter. We initialize a counter as per need, then we write the condition, and then the counter is incremented or decremented. Here the flow of events is counter initialized, condition check(true), the loop body executes, counter updated, condition check(true), the loop body executes, counter updated, condition check(false), the loop terminates. - There's another loop called the do-while loop which is rarely used. It is the same as while loop only difference being the condition is checked after the loop body is executed once. So it is used when we want the loop to be executed at least once even if the condition is false.
Make sure that the condition will become false at some point, or else the loop will never terminate and it becomes an infinite loop.
Check the syntax for all loops here:
while(condition) {
// loop body
}
for(var counter; condition; counter++) {
// loop body
}
do {
// loop body
} while(condition); //notice the semi-colon here
Sometimes during the loop body execution, if we want further parts to not be executed, we can use continue and break statements, along with conditional statements.
- Break statement: To end the loop directly without checking the condition again we use a break statement. Syntax:
break; - Continue statement: To start the loop body execution again without executing further parts of the loop body, we use the continue statement. Syntax:
continue;

