JavaScript Basics
One of the most widely used and well-known languages in the software sector is JavaScript. Today, JavaScript can run on any device that has a specialized application called the JavaScript engine, including servers, browsers, and other devices.
The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
Different engines have different “codenames”. For example:
- V8 – in Chrome, Opera, and Edge.
- SpiderMonkey – in Firefox.
- “JavaScriptCore”, “Nitro” and “SquirrelFish” for Safari, etc.
- Chakra for IE.
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
JavaScript is known as the backbone of the browser, it is responsible for all the functionality of a website. It can be used to manipulate styling with CSS and update dynamic content with HTML.
Syntax
We can write and execute JavaScript in two ways
- Internal – we can add JS code inside the
<script>
tag in
HTML file.
<script>
console.log("Hello world");
</script>
- External – we can attach the external file in the
<script>
tag using thesrc
attribute in the HTML file (recommended).
In index.js file
console.log("Hello world");
In HTML file
<body>
<script scr="../index.js" />
</body>
//Here ../index.js is the location of js file
//script tag should be given at the end of body tag
Whitespace and Line Breaks
Programs written in JavaScript don’t consider newlines, tabs, and spaces. You are free to format and indent your programs in a fashion that is orderly and consistent, making the code simple to read and comprehend. This includes using spaces, tabs, and newlines freely throughout your program.
Semicolons are Optional
Similar to C, C++, and Java, simple statements in JavaScript are typically followed by a semicolon character. But if you separate each of your statements into its own line, JavaScript will let you do away with the semicolon. The following code, for instance, might be written without semicolons.
But when formatted in a single line as follows, you must use semicolons −
<script type = "text/javascript">
var a = 10
var b = 10; var c = 20;
</script>
Note − It is a good programming practice to use semicolons.
Case Sensitivity
A case-sensitive language is JavaScript. This necessitates consistent letter capitalization when typing the language’s keywords, variables, function names, and any other identifiers.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE − Care should be taken while writing variable and function names in JavaScript.
Comments: We can make comments in the JS by using
inline: //code
block: /* code */
<script>
// This is a comment. It is similar to comments in C++
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
</script>
Output:
To check the output of the console.log you need to inspect the browser and open up the console tab.
Let’s examine in depth some of JavaScript’s fundamental concepts.
Variables
There are 4 ways to declare a JavaScript Variable:
- Using
var
- Using
let
- Using
const
- Using nothing
Var: Var is one of the variable declarations that we can declare without initialization and can also access it. This is Functional-scoped which means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program.
Example 1
var a;
a = 10+6;
console.log(a);
Example 2
const Fun = () =>{
var b = 10;
b=15; //re-declared
console.log(b) //prints 15
}
Fun()
console.log(b) //Uncaught reference b is not defined
Let: Let is the variable used in replacement of var, after ES6 introduced let variables it has become the most used variable declaration. It is Block scoped. Here variables can be updated but not re-declared.
Example 1
const letFun = () =>{
let c= 15
let c = 10; //re-declared
console.log(c)
}
letFun()
console.log(c)
//Uncaught SyntaxError: Identifier 'c' has already been declared
Example 2
for(let i=0; i<5; i++){
console.log(i); //here is updated
}
console.log(i); //Uncaught reference b is not defined
//i inside the loop prints 1,2,3,4,5.
Const
Variables declared with the const
maintain constant values. const
declarations share some similarities with let
declarations. It is also Block-scoped.
We can’t update or re-declare the variables.
const greet = "say Hi";
greet = "say Hello instead";
// error: Assignment to constant variable.
const greet = "say Hi";
const greet = "say Hello instead";
// error: Identifier 'greeting' has already been declared
But with the help of const
, we can manipulate the data-types like String, Array, Objects.
We can also declare a variable using no var, let, or const and perform the operations
Example
x =5; //declared without var/let/const
y = 6;
z = x+y;
console.log("z value is:" z, typeof(z));
// z value is: 11, number.
Overview
var | let | const |
The scope of a var variable is functional scope. | The scope of a let variable is block scope. | The scope of a const variable is block scope. |
It can be updated and re-declared into the scope. | It can be updated but cannot be re-declared into the scope. | It cannot be updated or re-declared into the scope. |
It can be declared without initialization. | It can be declared without initialization. | It cannot be declared without initialization. |
It can be accessed without initialization as its default value is “undefined”. | It cannot be accessed without initialization otherwise it will give a ‘reference error’. | It cannot be accessed without initialization, as it cannot be declared without initialization. |
hoisting is done, with initializing as ‘default’ value | Hoisting is done, but not initialized (this is the reason for error when we access the let variable before declaration/initialization | Hoisting is done, but not initialized (this is the reason for error when we access the const variable before declaration/initialization |
Functions
One of the core components of JavaScript are functions. A procedure is a group of statements that carry out an action or calculate a value, however in order for a procedure to be considered a function, it must take an input and produce an output with an evident connection between the input and the output. A function must be defined someplace in the scope from which it will be called in order to be used.
There are two types of Functions, they are:
- User-defined Functions.
- Nested Functions
- Predefined Functions.
User-defined
As the name suggests these functions are declared and defined by the User. They can frame the functionality according to their usage.
Example 1
function square(n) { //function declaration
return n * n;
}
console.log(square(5));
// Here n is the parameter
// square(5) - calling or invoking the function
Function can't works unless you call it.
Nested functions
These are functions that are inside of other functions. when we call the functions both the functions are invoked.
Example
function addSquares(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
addSquares(2, 3); //calling the function
//return 13
// Here first parameters goes to square function then next to addSquare function.
2*2 + 3*3 -> 4+9 = 13
Predefined
In JavaScript, we have some functions which are already defined which make it easier for users.
Let’s check out a few of the predefined functions
The parseInt()
function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
The eval()
method evaluates JavaScript code represented as a string.
The string()
converts an object’s value to a string.
The Number()
converts an object’s value to a Number.
There are 3 ways to write a function. let’s check them out
- Function Declaration
- Function Expression
- Arrow Function
Example of Function Declaration
function fac(n) { //Functional Declaration
return n < 2 ? 1 : n * fac(n - 1);
}
console.log(fac(3))
Example of Function Expression
const factorial = function fac(n) { //Functional expression
return n < 2 ? 1 : n * fac(n - 1);
}
console.log(factorial(3))
// factorial is the functional expression
Example of Arrow Function
const fac = (n) => { //Arrow function
return n <2 ? 1 : n * fac(n-1);
}
or even we can write in one line if function is short
const fac = (n) => return n <2 ? 1 : n * fac(n-1);
console.log(fac(3))
Loops
Loops are used to check for certain conditions and then repeatedly execute a block of code as long as those conditions are met.
There are different kinds of loops Let’s examine them one by one.
For loop
For loop allows the body of the loop to know the exact sequencing of each iteration.
Syntax
The for
statement creates a loop with 3 optional expressions:
for (initialize; condition; iteration) {
// code block to be executed
}
Example 1
for (let i = 0; i < 5; i++) {
console.log(i);
}
Example 2
const arr = ["orange","apple","mango","banana","kiwi"];
for (let i = 0; i < arr.length; i++) {
console.log(i);
}
//length of arr is 5, so it iterates 5 times.

While loop
The while
loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
Example
let i=0;
while (i < 6) {
console.log(i);
i++;
}
Do While Loop
The do while
loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Example
let i=0;
do {
console.log(i);
i++;
}
while (i < 4);

The For In Loop
The JavaScript for in
statement loops through the properties of an Object.
Syntax
for (key in object) {
// code block to be executed
}
Example
const person = {fname:"John", lname:"Doe", age:25};
for (let x in person) {
console.log(person[x]);
}
//In this example we have used Onject same goes with Array also.
The For Of Loop
The JavaScript for of
statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings, Maps, Node Lists, and more:
Syntax
for (variable of iterable) {
// code block to be executed
}
variable – For every iteration, the value of the next property is assigned to the variable. Variable can be declared with const
, let
, or var
.
iterable – An object that has iterable properties.
const cars = ["BMW", "Volvo", "Mini"];
for (let x of cars) {
console.log(x);
}
Conditional Statements
These are the statements that, depending on whether they are true or false, will cause the code to run.
if Statement
Use the if
statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Example
let hour =7
if (hour < 18) {
greeting = "Good day";
}
//Good day
The else Statement
Use the else
statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening"
hour = 20
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
//Good evening
else if Statement
Use the else if
statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
time = 15
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Switch Statement
Use the switch
statement to select one of many code blocks to be executed.
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the default code block is executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example: The getDay()
method returns the weekday as a number between 0
and 6
.(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
//Wednesday
break Keyword
The switch block is exited by JavaScript when it reaches the break keyword. In the switch block, this will halt execution.
In a switch block, breaking the final case is not required. There is where the block breaks (ends) regardless.
JavaScript reaches a break
keyword, it breaks out of the switch block. This will stop the execution inside the switch block.
Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.
default Keyword
The default
keyword specifies the code to run if there is no case match
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
// Looking forward to Weekend will be output by default if the case doesn't meet the conditions.