WT Unit 2
WT Unit 2
JavaScript is a high-level interpreted programming language initially created to make web pages
interactive.
In a web page, HTML is used to structure the page, CSS is used to add styling like colors, fonts, etc but a
web page with only HTML and CSS is static, meaning a user cannot really interact with the page, here is
where Javascript comes in.
It is used to make web pages interactive(for example if the user clicks a button then the theme of the
website changes, or after scrolling the page a pop-up message may be displayed).
JavaScript has a standard library of objects, such as Array, Date, and Math, and a fundamental set of
language elements such as operators, control structures, and statements.
Javascript can be used for both client and server side programming.
Applications of JavaScript
Excellent user interactivity: When you search for something you see that the search suggestions
appear, when you fill a form and click submit, the form is submitted all these are because of Javascript,
it allows users to interact with the webpage allowing us to build amazing websites and web apps.
Web and Mobile app creation: Javascript based frameworks like React, Angular, Vue allow us to build
robust web applications. Example: Facebook, Netflix have been built using React.Upwork, Paypal with
Angular, and so on. We can also use a JS based framework called React Native to build mobile
applications. Example: Uber eats, Discord, Pinterest, etc.
Server-side development: We can also use Javascript to develop the back end infrastructure of a web
application by using Node.js.Example: Netflix, Medium, Trello, etc. use Node.js on the server side.
Game development: Javascript can also be used to develop browser based games some of them are
HexGL, CrossCode, etc.
Art: We can also make digital art on the HTML5 canvas by using javascript based libraries.Example.js
library
Javascript Variables
In JavaScript, a variable is a name given to a memory location that is used to store any type of data. As
the name suggests, variables mean it can vary, i.e., data stored in a variable can be changed or updated
later in the program if required. In short, a variable is a symbolic name for (or reference to) a data or a
piece of information.
Highlight: A Javascript variable is a container, not a value, this means that variables aren’t themselves
values; they are a container for values.
Example: Think of a box named Age which stores the age of a person. So, the name is the variable name,
and the age stored in it is the value.
To declare a Javascript variable, one must know the rules to follow, as one can mess up the code while
declaring a variable. If one doesn't follow the rules, he/she may end up getting an error.
Variables are case-sensitive in Javascript. This means that schoolName and schoolname are
considered different variables.
We can use letters, digits, symbols like dollar sign ($) and underscore ( _ ) in a variable name.
We cannot start a variable name with a digit (0-9).
We cannot use any of the reserved keywords (function, return, typeof, break, etc.) of Javascript
as a variable name.
Important Points
Javascript allows multiple white spaces and even line breaks in a declaration of a variable.
Examples:
1. Declaring a JavaScript variable using line breaks and spaces:
var a = 25;
2. Declaring two variables in a single line separated by comma:
var b=1, c=2;
3. Using reserve keywords while declaring a variable:
var return = 5; //Will give error, as return is a keyword in Javascript
4. Valid variable name examples:
var my_school; //using underscore
var one$23; //using digit and dollar sign
5. Invalid variable name examples:
var 123name ; //variable cannot start with a digit
var variable@ ; //variable cannot contain '@' symbol
var break; //break is a reserved keyword in JS, so we can't use it as a
variable
Declaring a Variable
One must create a variable before using it. In programming terms, we call this declaring a variable. In
Javascript, we can declare a variable using either let, var, or const keywords.
var schoolName;
let address;
Here we are creating two variables, one using let and another using var.
Currently, these variables do not store any value, they are just declared. In other words, we have an
empty box named schoolName and address.
If you want to see the value of schoolName, the output will be undefined. We will see what is meant by
undefined in later part.
We have seen how to declare a variable with var. Now we will see how we can declare a variable
without using neither var nor let.
To declare a variable without using any keyword, we have to just write the variable name and must
assign a value to that variable. On doing this, the variable becomes a global variable (this line means
that the scope of the variable is global. The Scope of the variable is described later in this article.).
age = 25; //declaring a variable without using var
console.log(age); //output: 25
However, it is not recommended to declare a variable without using var as it may alter the value of an
already existing global variable.
Undefined vs. Undeclared Variables
Undefined variables
After learning initialization and declaration of variables, you have seen that when we declare a variable
without initializing it, then the variable is said to be undefined. That is, the variable is declared but not
initialized with any value.
Example:
var new_variable; //by default its value is undefined.
Undeclared variables
Suppose you want to use a variable in a statement, but the variable is not declared before. In this case,
the code will throw a ReferenceError as the variable is not declared using var keyword. In short, if we
access any undeclared variable, the code will cause runtime error.
Example:
console.log(xyz);
Try running the above line in the console, and you will get an error showing that ==ReferenceError: xyz
is not defined==. This indicates that xyz is not declared earlier you are trying to access an undeclared
variable.
The most important and unique feature in JavaScript is Variable Hoisting or var Hoisting. In JavaScript,
all variable declarations are processed before any other part of the code is executed. Thus declaring all
the variables at the top of the code. This feature is called hoisting in JavaScript. The declarations are
moved to the top of the global code or to the top of a function, depending on where it is declared. This
movement of declarations to the top of the function or global code is done automatically by the JS itself
internally. We don't actually see the change. This will be cleared by the examples below. Hoisting also
initializes the variable with "undefined".
Example:
hoistedVariable = 1;
var hoistedVariable;
The above code is same as :
var hoistedVariable;
hoistedVariable = 1;
Note: Hoisting only moves the declaration to the top of the scope(either global or function). It never
moves the assignment lines.
Example:
console.log(x); //output: undefined
var x = 2;
console.log(x); //output: 2
Though hoisting helps to, by default, declare variables at the top, it is highly recommended to declare
variables at the top of a function or global manually because one may get confused if he/she uses a
variable before declaring it.
Note: Variables declared using let and const are also hoisted but they are not initialized with undefined.
So, if someone tries to use variables before the declaration, then it will throw an exception.
You might be wondering what is let, as we haven't discussed it in detail. Here we will explain the
difference between var and let. First of all, both keywords are used to declare variables in JavaScript.
The main difference between var and let is that the scope of the variable that is defined by let is
limited to the block in which it is declared, whereas the variable declared using var has the
global scope, i.e., can be used throughout the code.
If we declare a variable using var outside of any block (i.e., in the global scope), then the variable
gets added to the window object, whereas variables declared with let will never get added to it.
We cannot declare the same variable multiple times if one of them is declared using let,
whereas we can declare the same variable any number of times using var.
Variable hoisting can be done using var, but hoisting cannot be done using let.
Try the below codes in your browser's console and you will understand it better.
Example 1:
Example 2:
function scopes(){
var x = 2;
let y = 3;
}
console.log(x); // will result in a referenceError.
console.log(y); // will result in a referenceError.
In this case, the scope of the variables x and y is only limited to the function, that’s why we cannot find
the reference to the variables x and y outside the function, thus resulting in the reference error. We will
describe the Variable Scope in the later part of this article.
Once a variable is declared or initialized, we can change its value anytime and anywhere within its
scope. It is similar to re-initializing the variable. We can update/change the value by just typing the
variable name followed by an equals sign and then followed by the new value we want it to store.
Example:
Scope of a variable means, the visibility of a variable. That is, the parts of our program where you can
use a variable.
1. Local Scope
2. Global Scope
A Local Variable is only visible inside a function where it is defined. We cannot use a local variable
outside the function where it is defined. On doing so, it will result in reference error.
function prints()
{
var local_var = 2;// a local variable with value 2
console.log(local_var);
//the local_var can be used anywhere inside this function
}
console.log(local_variable);//this line will result in ReferenceError,
//as local_variable is not visible in this line
A Global Variable has a global scope which means that it can be used and viewed anywhere throughout
the program.
For example: We can use a globally declared variable inside a function.
var global_var = 1;
function prints()
{
console.log(global_var); //output: 1
}
console.log(global_var); //output: 1
Since the global_var is declared globally, it can be used inside the function as well as outside the
function (i.e. in the global scope).
You might have heard that JavaScript is called "a dynamically typed language". This means that the data
type of a variable is not fixed. A variable can store any type of data, and the user can achieve this
without specifying the type of data he/she wants to store(eg: number, string, objects, arrays, etc).
Also, one can change the stored value to any type of data, anytime freely.
Examples:
JavaScript Constants
You have seen that variables are those, whose values could be changed if required. Now, JavaScript also
lets you declare constants. We declare a constant using the keyword const;
Syntax:
These constants are similar to variables but have some properties which are different from variables,
such as:
The constant must be initialized when you declare it, otherwise, it will throw a " SyntaxError: Missing
initializer in const declaration ".
Once assigned a value to a constant, you can’t re-assign values afterward. That is, a value is fixed to a
constant.
Example 1:
Example 2:
const pi = 3.142;
pi = 5; // This line will throw a TypeError: Assignment to constant variable.
The following table briefs the difference between let and var and const in javascript:
Data types in JavaScript refer to the attribute associated with the kind of data we are storing or working
on. It associates the declared variable (or item) with a particular type so that the compiler can perform
operations in an organized manner.
Primitive data types in javascript refer to those data types that are defined on the most basic level of the
language. These Javascript data types cannot be destructured further, nor do they have any pre-defined
properties or methods. They are only used to store items of their type.
There are 7 primitive data types in JavaScript:
1. Numbers
2. BigInt
3. String
4. Boolean
5. Undefined
6. Null
7. Symbol
Following is the table for all the primitive data types in javascript with their descriptions and examples.
1. Numbers Type
In javascript, the integers, float values (or decimals), and all the other numeric values are represented by
the number datatype.
Unlike other languages (like C++), javascript doesn't define separate data types for integers, decimals,
long integers, etc.
Numbers can be declared by using var, let, or const keyword followed by the variable name, and the
number is assigned to it.
Example:
let num1 = 10; //number with integer of value 10
var num2 = 9753123568; //number with integer of value 9753123568
const num3 = 3.14; //number with decimal of value 3.14
2. BigInt Type
The BigInt data type in javascript is used to represent numeric values that exceed the largest safe
integer limit. It is basically used to represent numbers greater than 253−1.
Note: Unlike number, the BigInt data type doesn't represent decimal values. It only represents whole
numbers.
Declaration:
Example:
3. String Type
String type is used to store elements in a textual form. The elements are stored in 16-bit integer form.
Declaration:
Strings are declared by assigning the text to the declared literals. The literal can be declared by
either const, var, or let. In Javascript, a string can be declared in the following three ways:
a. Single tick declaration: Strings are declared by enclosing the text between two single ticks ('')
b. Double tick declaration: Strings are declared by enclosing the text between two double ticks ("")
c. Backticks declaration: Strings are declared by enclosing the text between two backticks ticks (``)
Example:
4. Boolean Type
In javascript, the boolean data type is used to check the truthy or falsy condition. It is also known
as logical data type.
5. Undefined Type
In javascript, undefined is a primitive data type in javascript that gets assigned to variables or function
arguments when their values aren't initialized.
Declaration:
undefined data types in JavaScipt can be declared by simply declaring a literal by using var, let,
or const keyword. We don't assign anything to the literal.
Syntax:
var undefinedValue;
Example:
function example(x){
console.log('The user has entered: ' + x);
}
var a;
var b = 10;
var c = 'Javascript';
example(a);
//output: The user has entered: undefined
example(b);
//output: The user has entered: 10
example(c);
//output: The user has entered: Javascript
6. Null Type
The null type in javascript refers to an empty object pointer. It holds only one value. It is used to
represent intentional absence of any object.
Declaration: It is declared by declaring a variable using var, let or const keyword and it is assigned the
value null.
Syntax:
var a = null;
Example:
function example(x){
console.log(x);
}
var a = 10;
var b = null;
example(a);
//output: 10
example(b);
//output: null
7. Symbol Type
The symbol is a primitive data type in javascript that returns a unique symbol upon being called.
Symbols do not have a literal form and are unique.
Declaration:
The symbol is declared by calling the Symbol() function. The parameter field doesn't default; thus it can
be called either by passing an argument or empty.
Note: the Symbol() isn't a constructor thus, if it is called with the new keyword, it will throw an error.
Syntax:
let s1 = Symbol();
let s2 = Symbol('javascript');
The Symbol() creates a new symbol everytime it is called and the symbol has nothing to do with
the key passed.
Example:
let s1 = Symbol('x');
let s2 = Symbol('x');
console.log(s1===s2);
// output: false
In the above example, even though the key passed is same still the symbols s1 and s2 will be different.
Non-primitive data types are those data types that aren't defined at a basic level but are complex data
types formed upon operations with the primitive data types. The non-primitive data types in javascript
refer to objects and can perform multiple functions using their methods.
There are mainly 3 types of non-primitive (or complex) data types in JavaScript:
Object
Array
RegExp
Following is the table for all the non-primitive data types in javascript with their descriptions and
examples.
Object Type
Declaration:
1. Literal method
2. By calling the constructor
Example:
Array Type
Arrays in javascript are abstract data types that are used to store a set of elements. These can be
multiple elements of the same or different types. Arrays are basically containers in javascript.
Declaration:
1. By array literal
2. Constructor method
Example:
// By literal
let X = ['Red', 'Yellow', 'Orange'];
//By constructor
let Y = new Array('Apple', 'Orange', 'Grapes', 'Banana');
console.log(X);
// 'Red', 'Yellow', 'Orange'
console.log(Y);
// 'Apple', 'Orange', 'Grapes', 'Banana'
Example:
RegExp Type
We all have seen detective movies; remember how words are decoded and read using patterns? Even in
real life, we encounter many instances where we need to validate the texts with particular patterns.
The RegExp in javascript is an object which is used to match a string with a particular pattern.
Declaration:
Example:
//constructor declaration
let p2 = new RegExp('/javascript/i');
Ternary Operator in Javascript is a special operator which has three operands. In JavaScript, there is only
one such operator, and that is the Conditional Operator or the Question Mark Operator( ?: )
This operator is used to write a conditional block in a simpler form and also can be written inside an
expression or a statement; that’s why this operator is also known as the inline-if operator.
Syntax
The ternary operator is basically a combination of a question mark and a colon. To use this operator, you
need to write a conditional expression, followed by a question mark (?).
Then you need to provide two statements or expressions separated by a colon. The first expression
( expression_if_true ) evaluates when the condition results in a true value, and the second expression
( expression_if_false ) evaluates when the condition results in a false value.
Using the Ternary Operator, we can write the above block in just one line.
Passed
Note: if statement can be executed independently, i.e. without any else statement.
Syntax:
if(condition){
//code to be executed
}
Example 1:
function example(x){
if(x){
console.log('If statement is executed');
}
}
example(flag1);
//output: If statement is executed
example(flag2);
//This won't produce any output
example(a==b);
//This won't produce any output
example(a==c);
//output: If statement is executed
Example 2:
function checkEligibility(age){
if(age<18){
console.log('Sorry! You are not eligible for voting');
}
if(age>=18){
console.log('You are eligible for voting');
}
}
checkEligibility(11);
// Sorry! You are not eligible for voting
checkEligibility(34);
// You are eligible for voting
We have already discussed how the if statement executes only when the condition is true. But
what if the if statement fails? In such cases, we can use the else statement.
else statement in javascript is used to execute a block when all if conditions fail. In order to write an else
block, it is mandatory to declare an if statement, although the vice versa is not true.
Note: In if else in Javascript, the else statement can not be executed independently, i.e. it is mandatory
to write an if statement before an else statement.
Syntax:
if(condition){
//code to be executed
}else{
//code to be executed
}
Example:
function example(x){
if(x){
console.log('If statement is executed');
}else{
consoel.log('Else statement is executed');
}
}
example(flag1);
//output: If statement is executed
example(flag2);
//output: Else statement is executed
example(a==b);
//output: Else statement is executed
example(a==c);
//output: If statement is executed
Example 2:
function checkEligibility(age){
if(age<18){
console.log('Sorry! You are not eligible for voting');
}else{
console.log('You are eligible for voting');
}
}
checkEligibility(11);
// Sorry! You are not eligible for voting
checkEligibility(34);
// You are eligible for voting
Switch case in javascript can be defined as an equivalent of an if-else statement. The switch statement
takes an expression and evaluates it with respect to other cases, and then outputs the values associated
with the case that matches the expression.
If no case passes the expression, then the switch statement will execute the default code.
Switch case in javascript can be used at places where our output needs to be dependent on the value an
expression holds.
Syntax
switch (expression) {
case caseValue1:
//code a
break;
case caseValue2:
//code b
break;
default:
//code c
break;
}
Examples
function groceryPrice(exp){
switch (exp) {
case 'Cookies':
console.log('Cookies cost 100 rupees');
break;
case 'Milk':
console.log('Milk cost 60 rupees');
break;
case 'Fruits':
console.log('Fruits cost 300 rupees');
break;
case 'Corn Flakes':
console.log('Corn Flakes cost 150 rupees');
break;
default:
console.log(exp + ' is not available right now');
}
}
groceryPrice('Cookies');
//output: Cookies cost 100 rupees
groceryPrice('Fruits');
//output: Fruits cost 300 rupees
groceryPrice('Peanut');
//output: Peanut is not available right now
Break Statement
In the switch case, the break keyword is used associated with the cases to terminate the switch case
once the expression matches that particular case.
Switch vs if…else
If else Switch case
Its input is an expression that can be a It's input is an expression that can be an
specific condition or a range enumerated value of a string object
It has less readable syntax It has more readable syntax
Multiple if blocks can not be processed Multiple cases can be processed if we
unless each condition is true remove the break statement
It tests equality as well as logical It tests only equality.
expressions
It is relatively slow for large values It works fast for large values because the
compiler creates a jump table
Loops in JavaScript
While loops in JavaScript
A while loop executes the respective statements as long as the conditions are met. As soon as the
condition becomes false, the loop is terminated, and the control is passed on to the statement outside
the loop. It is important to note that while is an entry-controlled loop in JavaScript.
while (condition) {
// code block
}
A do...while loop is an exit-controlled loop. This means that the do...while loop executes the block of
code once without checking the condition. After the code has been executed once, the condition is
checked. If the condition is true, the code is executed further. If the condition is false, the loop is
terminated.
The do...while statement is used when you want to run a loop at least one time.
do {
//code block to be executed
}
while (condition);
let i = 1;
do {
console.log(i);
i++;
} while(i <= 10);
For loops in JavaScript are one of the most commonly used loop constructs.
A for loop is an entry-controlled loop that repeats a block of code if the specified condition is met. A for
loop in JavaScript is typically used to loop through a block of code multiple times.
Syntax
Let us write a simple program to print the numbers 1 to 10 in JavaScript using for loops.
for (var i=1;i<=10;i++){
console.log(i)
}
For...in Statements
A for...in the statement is used to iterate over those properties of objects that have been keyed. We can
say in crude terms that they have been 'indexed.' This means that each time the loop iterates, a key is
assigned to a variable named key. This key is used to display the properties of the object it is linked to.
This is like a for loop, but it only iterates over enumerable properties keyed by strings or arrays.
const patient = {
name: 'Isabel',
height: 164, //in cm
weight: 60, //in kg
disease: 'hypertension'
}
for ( let key in patient) {
console.log(`${key} => ${patient[key]}`);
}
The a bove code is used to print the details of the patient Isabel by viewing her health record.
The for...in statement iterates over the object patient and displays the records in it. The object
key is assigned the variable 'key'. The value of the key could be accessed by the patient[key]
A for...of statement is like a counterpart of the for...in statement. Except iterating through the
properties of the enumerable object, it loops through its values.
The above code is used to print the patients linked to a hospital's health records.
Here, patients is the iterable object (array, in our case). Element is an item in the iterable
object. For every element in the iterable object 'patients', the body of the loop is executed.
Function declarations
In JavaScript, functions are blocks of reusable code that can be defined and invoked for performing
specific tasks. There are two common ways to declare functions in JavaScript: function declarations
and function expressions.
Function declarations are hoisted in JavaScript, which means they can be called before they are
defined in the code. This behavior can be helpful, but it's still a good practice to define your
functions before invoking them to improve code readability.
Remember that in addition to function declarations, you can also use function expressions, arrow
functions, and various other approaches to define functions in JavaScript. Each has its own use cases
and syntactic differences.
Function parameters
Function parameters are placeholders for values that you can pass to a function when you invoke it.
Parameters allow you to make your functions more flexible and reusable by allowing them to work
with different inputs. Here's how you can use function parameters with examples:
// Function declaration with parameters
function addNumbers(a, b) {
return a + b;
}
// Function invocation with arguments
var sum = addNumbers(5, 3);
console.log(sum); // Output: 8
You can have any number of parameters in a function declaration, separated by commas:
function multiply(a, b, c) {
return a * b * c;
}
var product = multiply(2, 3, 4);
console.log (product); // Output: 24
It's worth noting that JavaScript is a dynamically typed language, so you don't need to specify the
types of parameters when declaring functions. You simply use the parameter names in the function
body, and their values will be automatically assigned when the function is called.
Default Parameters:
You can also provide default values for parameters, which are used when no value is passed for that
parameter during function invocation:
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
Rest Parameters:
Rest parameters allow you to pass a variable number of arguments to a function as an array:
function calculateSum(...numbers) {
let sum = 0;
for (const number of numbers) {
sum += number;
}
return sum;
}
console.log(calculateSum(1, 2, 3)); // Output: 6
console.log(calculateSum(10, 20, 30)); // Output: 60
In this example, the calculateSum function uses the rest parameter ...numbers to capture all the
provided arguments as an array. It then calculates and returns the sum of those numbers.
These are some common ways to use function parameters in JavaScript. Parameters make your
functions more flexible and adaptable to different inputs, improving code reuse and organization.
Functions as Objects
In JavaScript, functions are first-class objects, which mean they can be treated like any other value or
object. This property enables you to assign functions to variables, pass them as arguments to other
functions, and even store them in data structures like arrays and objects. Here's an example of using
functions as objects:
Anonymous functions
Anonymous functions, also known as "function expressions," are functions that are defined without
a name. They are often used when you need a function for a specific task but don't necessarily need
to reuse it elsewhere. Here's an example of using anonymous functions in JavaScript:
// Anonymous function assigned to a variable
var greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("Nirmith")); // Output: Hello, Nirmith!
In this example, the anonymous function is assigned to the variable greet. You can then invoke the
function using the greet variable.
Anonymous functions are commonly used when passing functions as arguments to other functions.
For instance, with the Array.prototype.map function:
var numbers = [1, 2, 3, 4, 5];
var squaredNumbers = numbers.map(function(number) {
return number * number;
});
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
In this example, the anonymous function is used as an argument to the map function. The
anonymous function calculates the square of each number in the numbers array, and the result is
stored in the squaredNumbers array.
You can also use arrow functions as a more concise syntax for anonymous functions:
var numbers = [1, 2, 3, 4, 5];
var squaredNumbers = numbers.map(number => number * number);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
Arrow functions are a shorthand for writing anonymous functions, and they automatically capture
the surrounding this value.
Anonymous functions are useful when you have a simple task that you want to define inline, without
giving the function a permanent name. They're often used for callback functions, array methods, and
other situations where a short-lived function is needed.
Arrow functions
Arrow functions are a concise way to write anonymous functions in JavaScript. They provide a
shorter syntax and automatically capture the value of this from the surrounding context. Here are
some examples of using arrow functions:
Variable scopes
In JavaScript, variable scopes determine where a variable is accessible and where it's not. There are
two main types of variable scopes: global scope and local scope (also known as function scope or
block scope). Let's explore these concepts with examples:
Global Scope:
Variables declared outside of any function or block have global scope. They can be accessed from
any part of the code.
var globalVariable = "I'm global";
function printGlobal() {
console.log(globalVariable);
}
printGlobal(); // Output: I'm global
In this example, the variable globalVariable is accessible both inside the function printGlobal and
outside it, because it's declared in the global scope.
Variables declared inside a function are limited to that function's scope. They are not accessible from
outside the function.
function localScopeExample() {
var localVariable = "I'm local";
console.log(localVariable);
}
localScopeExample(); // Output: I'm local
// Trying to access localVariable outside its scope
console.log(localVariable); // Output: ReferenceError: localVariable is
not defined
In this example, the variable localVariable is declared inside the localScopeExample function, so it's
accessible only within that function.
Variables declared using let and const have block scope, which means they are limited to the block in
which they are defined (e.g., within loops or conditional statements).
if (true) {
var x = 10; // Not block-scoped
let y = 20; // Block-scoped
const z = 30; // Block-scoped
}
console.log(x); // Output: 10
console.log(y); // Output: ReferenceError: y is not defined
console.log(z); // Output: ReferenceError: z is not defined
In this example, the variable x is accessible outside the block, while y and z are only accessible within
the block.
Nested Scopes:
Scopes can be nested; meaning a variable declared in an outer scope is accessible in inner scopes,
but not the other way around.
function outer() {
var outerVariable = "I'm outer";
function inner() {
var innerVariable = "I'm inner";
console.log(outerVariable); // Accessible
}
inner();
console.log(innerVariable); // Not accessible
}
outer();
In this example, the outerVariable declared in the outer function is accessible within the inner
function, but the innerVariable declared in the inner function is not accessible outside its scope.
Understanding variable scopes is crucial for writing organized and maintainable code in JavaScript. It
helps you manage variable visibility, prevent accidental name collisions, and control access to data.
Built in functions
JavaScript provides a variety of built-in functions that offer useful functionality without needing to
create them from scratch. These functions cover a wide range of tasks, from manipulating strings
and arrays to performing mathematical calculations and working with dates. Here are some
examples of built-in functions in JavaScript:
String Functions:
var text = "Hello, world!";
console.log(text.length); // Output: 13
console.log(text.toUpperCase()); // Output: HELLO, WORLD!
console.log(text.indexOf("world")); // Output: 7
console.log(text.substring(0, 5)); // Output: Hello
Array Functions:
var numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
console.log(numbers.length); // Output: 10
console.log(numbers.sort()); // Output: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
console.log(numbers.indexOf(5)); // Output: 4
console.log(numbers.reduce((a, b) => a + b, 0)); // Output: 39
Math Functions:
console.log(Math.sqrt(25)); // Output: 5
console.log(Math.random()); // Output: Random decimal between 0 and 1
console.log(Math.floor(5.7)); // Output: 5
console.log(Math.ceil(5.2)); // Output: 6
console.log(Math.round(5.5)); // Output: 6
Date Functions:
var currentDate = new Date();
console.log(currentDate.getFullYear());// Output: Current year
console.log(currentDate.getMonth()); // Output: Current month (0-11)
console.log(currentDate.getDate()); // Output: Current day of the month
console.log(currentDate.getDay()); // Output: Current day of the week
(0-6, where 0 is Sunday)
Regular Expression Functions
var regex = /\d+/;
console.log(regex.test("123abc")); // Output: true (matches digits)
console.log("Hello 123 World".match(regex)); // Output: ["123"] (array of
matches)
console.log("Hello".replace("e", "a")); // Output: Hallo
These are just a few examples of the many built-in functions available in JavaScript. The built-in
functions save you time and effort by providing pre-built solutions to common programming tasks.
Arrays in JavaScript
In JavaScript, an array is a user-defined or non-primitive data type used to store a collection of elements
in a single variable.
Creating Arrays :-
Different ways to create arrays are
1. Array literals
2. The ... spread operator on an iterable object
3. The Array() constructor
4. The Array.of() and Array.from() factory methods
1. Array literals :-
Using an array literal is the easiest way to create a JavaScript Array. which is simply acomma-separated
list of array elements within square brackets.
Syntax:
let array_name = [item1, item2, ...];
For example:
let empty = []; // An array with no elements
let primes = [2, 3, 5, 7, 11]; // An array with 5 numeric elements
let misc = [ 1.1, true, "a", ]; // 3 elements of various types + trailing
comma
The values in an array literal need not be constants; they may be arbitraryexpressions:
let base = 1024;
let table = [base, base+1, base+2, base+3];
2. Spread Operator
Without spread syntax, to create a new array using an existing array as one part of it, the array literal
syntax is no longer sufficient , With spread syntax this becomes much more easy
The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into
another array or object.
const parts = ["shoulders", "knees"];
const lyrics = ["head", ...parts, "and", "toes"];
// ["head", "shoulders", "knees", "and", "toes"]
The spread operator works on any iterable object.
3. The Array() Constructor
Another way to create an array is with the Array() constructor. You can invoke this constructor in three
distinct ways:
• Call it with no arguments:
let a = new Array();
This method creates an empty array with no elements and is equivalent to the array literal [].
• Call it with a single numeric argument, which specifies a length:
let a = new Array(10);
• Explicitly specify two or more array elements or a single non-numeric element
for the array:
let a = new Array(5, 4, 3, 2, 1, "testing, testing");
4. Array.of()
The Array.of() function addresses this problem of Array() constructor ,it is a factory method that
creates and returns a new array, using its argument values (regardless of how many ofthem there are) as
the array elements:
Array.of() // => []; returns empty array with no arguments
Array.of(10) // => [10]; can create arrays with a single numeric argument
Array.of(1,2,3) // => [1, 2, 3]
5. Array.from()
The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-
like object. The JavascriptArray.from() method is used to create a new array instance from a given array.
It is also a simple way to make a copy of anarray:
let copy = Array.from(original);
Example :-
let text = "web technology"
const myArr = Array.from(text);
console.log(myArr);
// output: w,e,b, ,t,e,c,h,n,o,l,o,g,y
Array: length Property
The length data property of an Array instance represents the number of elements in that array.
Example :-
const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];
console.log(clothing.length);
// output: 4
Reading and Writing Array Elements
An item in a JavaScript array is accessed by referring to the index number of the item in square brackets.
A reference to the array should appear to the left of the brackets. An arbitrary expression that has a non
negative integer value should be inside the brackets. Same syntax can be used for both read and write
the value of an element of an array. Thus, the following are all legal JavaScript statements:
let a = ["world"]; // Start with a one-element array
let value = a[0]; // Read element 0
a[1] = 3.14; // Write element 1
let i = 2;
a[i] = 3; // Write element 2
a[i + 1] = "hello"; // Write element 3
a[a[i]] = a[0]; // Read elements 0 and 2, write element 3
Example :-
var myArray = new Array(4);
myArray[0] = "A";
myArray[1] = "c";
myArray[2] = "s";
myArray[3] = "d";
var i = 3;
var theYear = myArray[i];
console.log("It is the year of the " + theYear + ".");
// output:
22
54
76
92
43
33
Using for…in
The for…in loop is an easier way to loop through arrays as it gives us the key which we can now use to
get the values from our array this way:
for (i in scores) {
console.log(scores[i]);
}
// output:
22
54
76
92
43
33
Array Destructing :-
Destructuring the array in JavaScript simply means extracting multiple values from data stored in objects
and arrays. The destructing assignment syntax is a JavaScript expression that makes it possible to unpack
values from arrays, or properties from objects, into distinct variables.
Example 1 :
// we have an array with the name and surname
let arr = ["John", "Smith"]
// destructuring assignment
let [firstName, surname] = arr;
console.log(firstName); // John
console.log(surname); // Smith
Example 2 :
let [firstName, surname] = "John Smith".split(' ');
console.log(firstName); // John
console.log(surname); // Smith
// output:
Person_1
Person_3
// output:
Monday
Wednesday
[‘Thrusday’, ‘Friday’, ‘Saturday’]
If the array is shorter than the list of variables at the left, there’ll be no errors. Absent values are
considered undefined:
Ex:
let [firstName, surname] = [];
console.log(firstName); // undefined
console.log(surname); // undefined
// output:
100
200
300
We used array destructuring to destructure the above array elements into specific elements x, y, and z in
a single line of code.
Multidimensional array
A multidimensional array is an array that has one or more nested arrays. This increases the number of
dimensions of the array.
a normal array is a 1-Dimensional array and can be accessed using a single index. But when there is one
nested array, it becomes a 2-Dimensional array. In this case, we can access the elements of the nested
array using two indices. Similarly, when there is an array that has an array inside it which have another
array inside that then it becomes a 3-Dimensional array. And so on.
JavaScript does not provide any built-in support for multidimensional arrays. There is no direct way to
create a multidimensional array in JavaScript. Instead, we can create a multidimensional array by using a
nested array
The simplest way to create a JavaScript multidimensional array is using array literals. For this, you can
manually create the array using square brackets and nest the other arrays inside the square brackets.
Example :-
var arr = [
[1, 2, 3],
[4, 5, 6]
];
The above code creates a multidimensional array with two nested arrays.
Accessing elements in JavaScript multidimensional array
A multidimensional array is accessed in the same fashion as a normal array. The only difference is that
we need to use two or more indices to access the elements of the nested array.
For example, to access the second element of the first nested array, we need to use arr[0][1].
For example :-
var arr = [
[1, 2, 3],
[4, 5, 6]
];
console.log(arr[1][1]); // output: 5
Adding elements in JavaScript multidimensional array
The Push or Splice method :-
The push method will add an element at the end of the array. You can push an entire array at the end of
the array or can add a new element to any internal array.
Example :-
var arr = [
['a', 'b', 'c'],
['d', 'e', 'f']
];
console.log(arr);
arr.push(['g', 'h', 'i']);
console.log(arr);
// output:
[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ] ]
[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], [ 'g', 'h', 'i' ] ]
Another method to add elements to the array is the splice method. It can add as well as remove
elements at any index of the array.
Example :-
var arr = [
['a', 'b', 'c'],
['d', 'e', 'f']
];
console.log(arr);
arr.splice(2, 0, ['g', 'h', 'i']);
console.log(arr);
arr.splice(1, 0, [1, 2]);
console.log(arr);
// output:
[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ] ]
[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], [ 'g', 'h', 'i' ] ]
[ [ 'a', 'b', 'c' ], [ 1, 2 ], [ 'd', 'e', 'f' ], [ 'g', 'h', 'i' ] ]
To remove elements from a multidimensional array you can use the pop or splice method.
The pop method will always remove the last element of the array and return it.
The splice method can remove any element from the array.
Example :-
var arr = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
];
console.log(arr);
arr.pop();
console.log(arr);
arr[0].splice(1, 1);
console.log(arr);
// output:
[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], [ 'g', 'h', 'i' ] ]
[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ] ]
[ [ 'a', 'c' ], [ 'd', 'e', 'f' ] ]
Shallow copy
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values
in the original object. If any of the fields of the object are references to other objects, just the reference
addresses are copied i.e., only the memory address is copied.
Example:-
constfirst_person = {
name: "Jack",
age: 24,
}
constsecond_person = first_person;
second_person.age = 25;
console.log(first_person.age); // output: 25
console.log(second_person.age); // output: 25
Deep copy
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the
fields. A deep copy occurs when an object is copied along with the objects to which it refers.
Example :-
constfirst_person = {
name: "Jack",
age: 24
};
let second_person = first_person;
second_person = {
name: "Jack",
age: 23
};
console.log(first_person.age); // Output: 24
console.log(second_person.age); // Output: 23
Note that JavaScript distinguishes between String objects and primitive string values. (The same is
true of Boolean and Numbers.)
String literals (denoted by double or single quotes) and strings returned from String calls in a non-
constructor context (that is, called without using the new keyword) are primitive strings. In contexts
where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will
automatically wrap the string primitive and call the method or perform the property lookup on the
wrapper object instead.
console.log(typeofstr); // "string"
console.log(typeofstr2); // "string"
console.log(typeofstr3); // "string"
console.log(typeofstrObj); // "object"
String primitives and String objects also give different results when using eval(). Primitives passed
to eval are treated as source code; String objects are treated as all other objects are, by returning
the object. For example:
For example, if you have a string assigned to a variable, you cannot modify it. Instead, you will create
a new string and assign the new string to the same variable like this:
This means that the original string "John Doe" still exists in memory, but the variable name now
refers to the new string "Jane".
Back-Tics Syntax
Template Literals use back-ticks (``) rather than the quotes ("") to define a string:
Example:
With template literals, you can use both single and double quotes inside a string:
Example
Multiline Strings
Example
let text=`The
quick
brown
fox
jumps
over
the lazy dog`;
Expression Substitution
Example
let price= 10;
let VAT= 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`; //Total: 12.50
String Length
Example
String slice()
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: start position, and end position (end not included).
Example
If you omit the second parameter, the method will slice out the rest of the string:
This example slices out a portion of a string from position -12 to position -6:
String substring()
The difference is that start and end values less than 0 are treated as 0 in substring().
Example:
let str= "Apple,Banana,Kiwi";
let part = str.substring(7, 13);
If you omit the second parameter, substring() will slice out the rest of the string.
Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "Google");
Note
The replace() method does not change the string it is called on.
The replace() method returns a new string.
The replace() method replaces only the first match
If you want to replace all matches, use a regular expression with the /g flag set. See examples below.
String ReplaceAll()
In 2021, JavaScript introduced the string method replaceAll():
Example
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
The replaceAll() method allows you to specify a regular expression instead of a string to be replaced.
If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is
thrown.
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");
String toUpperCase()
let text1 = "Hello World!";
let text2 = text1.toUpperCase(); // text2 is text1 converted to Upper
HELLO WORLD!
String toLowerCase()
let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1 converted to
lowerhello world!
String concat()
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2); // Hello World
The concat() method can be used instead of the plus operator. These two lines do the same:
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");// both will give same result Hello
World!
String split()
A string can be converted to an array with the split() method:
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters:
text.split("")
String charCodeAt()
The charCodeAt() method returns the unicode of the character at a specified index in a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:
Example
let text = "HELLO WORLD";
let char = text[0];
Note
Property access might be a little unpredictable:
It makes strings look like arrays (but they are not)
If no character is found, [ ] returns undefined, while charAt() returns an empty string.
It is read only. str[0] = "A" gives no error (but does not work!)
Example
let text = "HELLO WORLD";
text[0] = "A"; // Gives no error, but does not work
Search Methods
String indexOf()
String lastIndexOf()
String search()
String match()
String matchAll()
String includes()
String startsWith()
String endsWith()
String indexOf()
The indexOf() method returns the index (position) the first occurrence of a string in a string:
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
Note
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third, ..
String search()
The search() method searches a string for a string (or a regular expression) and returns the position
of the match:
let text = "Please locate where 'locate' occurs!";
text.search("locate");
let text = "Please locate where 'locate' occurs!";
text.search(/locate/);
Note: In Example1 , While we search kmit only its printing one time, actually we have two kmit in one
statement , to resolve such problems we are using Regular Expression Techniques.
Create a RegEx :
There are two ways you can create a regular expression in JavaScript.
1. Using a regular expression literal:
The regular expression consists of a pattern enclosed between slashes /.
For example: cost regularExp = /abc/;
Here, /abc/ is a regular expression.
2. Using the RegExp() constructor function:
You can also create a regular expression by calling the RegExp() constructor function. For
example: const reguarExp = new RegExp('abc');
Example-1:
Input:
const data1="Hi Welcome!!! to kmit. kmit locates in HYD"
const rex=/kmit/g
let result=data1.matchAll(rex)
console.log(Array.from(result));
Output:
0: ['kmit', index: 17, input: 'Hi Welcome!!! to kmit. kmit locates in
HYD']
1: ['kmit', index: 23, input: 'Hi Welcome!!! to kmit. kmit locates in HYD']
length: 2
Example-2:
Write a Regular Expression that displays all words which should contains second letter must be an
Vowel using function
function RegularExpression()
{
let data1="Hi Welcome!!! to kmit. kmit locates in HYD"
let regex = new RegExp(/.[a-e]\w/g);
let res=data1.matchAll(regex);
console.log(Array.from(res));
}
RegularExpression()
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this:
WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Symbols:
Expression Description
^ Start of string
$ End of string
. Any single character
+ One or more character
Expression Description
g g is used for global search which means the search will not return after the
first match.
i i is used for case-insensitive search meaning that a match can occur
regardless of the casing.
m m is used for multiline search.
u u is used for Unicode search
console.log(new RegExp('\\n',
'g').toString());
// Expected output: "/\n/g"
Sets
Set is a built-in data structure that allows you to store unique values of any type, whether they are
primitive values or object references.
Sets ensure that each value can only appear once in the collection.
Creating a Set:
Example:
const mySet = new Set();
const mySetFromArray = new Set([1, 2, 3, 2, 1]); // Duplicates are
automatically removed
console.log(mySetFromArray)
1. add(value): Adds a new element with the given value to the Set.
const mySet = new Set();
mySet.add(42);
mySet.add('hello');
console.log(mySet)
2. delete(value): Removes the element with the specified value from the Set.
const mySet = new Set([1, 2, 3]);
mySet.delete(2);
3. has(value): Checks if the Set contains an element with the specified value. Returns true if
found, otherwise false.
const mySet = newSet(['apple','banana','cherry']);
console.log(mySet.has('banana')); // true
console.log(mySet.has('grape')); // false
5. forEach(callbackFn, thisArg): Executes the given callback function for each element in the
Set.
const mySet = new Set([10, 20, 30]);
mySet.forEach((value) => { console.log(value); });
6. keys(): Returns an iterator of all the keys in the Set. (This is the same as the values, as Sets
only store unique values).
const mySet = new Set([1, 2, 3]);
const keyIterator = mySet.keys();
for (const key of keyIterator) { console.log(key); }
8. entries(): Returns an iterator of all entries (key-value pairs) in the Set, where the key is the
same as the value.
const mySet = new Set(['x', 'y', 'z']);
const entryIterator = mySet.entries();
for (const [key, value] of entryIterator) { console.log(key, value); }
Properties:
Remember that Sets are iterable, so you can use the for...of loop to iterate through their values,
keys, or entries.
Also, note that Sets only store unique values, so duplicate values are automatically eliminated when
adding elements.
Maps
Map is a built-in data structure that allows you to store key-value pairs. Unlike Sets, which store only
values,
Maps can use any data type as keys and values, including objects and functions.
Creating a Map:
Example:
const myMap = new Map();
const myMapWithInitialData = new Map([ ['key1', 'value1'], ['key2',
'value2'] ]); //Map(2) { 'key1' => 'value1', 'key2' => 'value2' }
Map methods and properties:
1. set(key, value): Adds a new key-value pair to the Map.
const myMap = new Map();
myMap.set('name', 'Alice');
myMap.set('age', 30);
3. has(key): Checks if the Map contains a key. Returns true if found, otherwise false.
console.log(myMap.has('age')); // true
console.log(myMap.has('gender'));// false
4. delete(key): Removes the key-value pair with the specified key from the Map.
myMap.delete('age');
6. forEach(callbackFn, thisArg): Executes the given callback function for each key-value pair in
the Map.
myMap.forEach((value, key) => { console.log(`${key}: ${value}`); });
They maintain the insertion order, making them useful for cases where order matters.
Keep in mind that the keys in a Map can be any data type, unlike objects where keys are always
converted to strings.
Objects in JavaScript
In JavaScript, an object is a fundamental data structure that allows you to store and organize data in
a key-value pair format.
Objects are a powerful way to organize and manipulate data in your code, and they are extensively
used in JavaScript programming for various purposes, including creating classes, managing data
structures, and representing real-world entities.
In JavaScript, most things are objects, from core JavaScript features like arrays to the browser APIs
built on top of JavaScript. You can even create your own objects to encapsulate related functions and
variables into efficient packages and act as handy data containers.
//input:
let data="Hi Welcome!!! to kmit. kmit locates in HYD"
console.log(data.search("kmit"))
//output: 17
The simplest way to create an object is by using object literals. An object literal is a comma-separated
list of key-value pairs enclosed in curly braces `{}`.
const person = {
name: "John Doe",
age: 30,
profession: "Software Developer"
};
You can create multiple objects with similar structures using constructor functions or ES6 classes.
function Person(name, age) {
this.name = name;
this.age = age;
}
ES6 introduced class syntax, which provides a more structured way to define and create objects.
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
const person = new Person("John", "Doe", 30);
You can add or modify properties of an object even after it's created.
person.location = "New York";
person.age = 31;
Object Iteration:
There isn't any method in an Object itself to delete its own properties.
The delete operator removes a property from an object. If the property's value is an object and there
are no more references to the object, the object held by that property is eventually released
automatically.
Syntax:
delete object.property
OR
delete object[property]
Example.
const Employee = {
firstname: 'John',
lastname: 'Doe',
};
console.log(Employee.firstname);
// Expected output: "John"
delete Employee.firstname;
console.log(Employee.firstname);
// Expected output: undefined
Nested Objects:
Methods in Objects:
Objects can also have methods, which are functions defined as properties.
const calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
Objects come with built-in methods to manipulate and work with them.
console.log(Object.keys(object1));
// Expected output: Array ["a", "b", "c"]
// Expected output:
// "a: somestring"
// "b: 42"
Object.assign(target, source): Copies properties from one or more source objects to a target object.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
console.log(target);
// Expected output: Object { a: 1, b: 4, c: 5 }
Object.defineProperties()
The Object.defineProperties() static method defines new or modifies existing properties directly on
an object, returning the object.
const object1 = {};
Object.defineProperties(object1, {
property1: {
value: 42,
writable: true,
},
property2: {},
});
console.log(object1.property1);
// Expected output: 42
Object.defineProperty()
The Object.defineProperty() static method defines a new property directly on an object, or modifies
an existing property on an object, and returns the object.
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false,
});
object1.property1 = 77;
// Throws an error in strict mode
console.log(object1.property1);
// Expected output: 42
Object.freeze()
Freezes an object. Other code cannot delete or change its properties. A frozen object can no longer
be changed: new properties cannot be added, existing properties cannot be removed
constobj = {
prop: 42,
};
Object.freeze(obj);
obj.prop = 33;
// Throws an error in strict mode
console.log(obj.prop);
// Expected output: 42
JavaScript uses prototypal inheritance. Objects can inherit properties and methods from other
objects.
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound.`);
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy makes a sound.
What is JSON?
JSON is a text-based data format following JavaScript object syntax, which was popularized by
Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used
independently from JavaScript, and many programming environments feature the ability to read
(parse) and generate JSON.
JSON exists as a string — useful when you want to transmit data across a network. It needs to be
converted to a native JavaScript object when you want to access the data. This is not a big issue —
JavaScript provides a global JSON object that has methods available for converting between the two.
A JSON string can be stored in its own file, which is basically just a text file with an extension of .json
JSON is purely a string with a specified data format — it contains only properties, no methods.
JSON requires double quotes to be used around strings and property names. Single quotes are not
valid other than surrounding the entire JSON string.
Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should
be careful to validate any data you are attempting to use (although computer-generated JSON is less
likely to include errors, as long as the generator program is working correctly). You can validate JSON
using an application like JSONLint.
JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays
or objects. So for example, a single string or number would be valid JSON.
Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings
may be used as properties.
JSON structure
As described above, JSON is a string whose format very much resembles JavaScript object literal
format. You can include the same basic data types inside JSON as you can in a standard JavaScript
object — strings, numbers, arrays, booleans, and other object literals.
For example:
{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": ["Radiation resistance", "Turning tiny", "Radiation
blast"]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}
We could then access the data inside it using the same dot/bracket notation we looked at in the
JavaScript object basics article.
For example:
superHeroes.homeTown;
superHeroes["active"];
To access data further down the hierarchy, you have to chain the required property names and array
indexes together. For example, to access the third superpower of the second hero listed in the
members list, you'd do this:
For example:
superHeroes["members"][1]["powers"][2];
First, we have the variable name — superHeroes.
Inside that, we want to access the members property, so we use ["members"].
members contains an array populated by objects. We want to access the second object
inside the array, so we use [1].
Inside this object, we want to access the powers property, so we use ["powers"].
Inside the powers property is an array containing the selected hero's superpowers. We want
the third one, so we use [2].
Arrays as JSON
Above we mentioned that JSON text basically looks like a JavaScript object inside a string. We can
also convert arrays to/from JSON. Below is also valid JSON,
for example:
[
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
}
]
The above is perfectly valid JSON. You'd just have to access array items (in its parsed version) by
starting with an array index, for example [0]["powers"][0].
To be able to display this data in our HTML file, we first need to fetch the data with JavaScript.
We will fetch this data by using the fetch API. We use the fetch API in the following way:
fetch(url)
.then(function (response) {
// The JSON data will arrive here
})
.catch(function (err) {
// If an error occured, you will catch it here
});
The url parameter used in the fetch function is where we get the JSON data. This is often an http
address. In our case it is just the filename people.json. We don’t have to drill down to any directory
since the json file is in the same directory as our index.html.
The fetch function will return a promise. When the JSON data is fetched from the file, the then
function will run with the JSON data in the response.
If anything goes wrong (like the JSON file cannot be found), the catch function will run.
JSON Stringify
The JSON.stringify() method converts a JSON- to a string.
Syntax
JSON.stringify( value [, replacer [, space]])
JSON.stringify ( value )
Parameters
value : The JavaScript value to be ‘stringified’.
replacer : (Optional) A function or an array which serves as a filter for properties of the value object
to be included in the JSON string.
space : (Optional) A numeric or string value to provide indentation to the JSON string. If a numeric
value is provided, that many spaces (upto 10) act as indentaion at each level. If a string value is
provided, that string (upto first 10 chracters) acts as indentation at each level.
Return type
The return type of the method is: string.
const newJoke = {
categories: ['dev'],
value: "Chuck Norris's keyboard is made up entirely of Cmd keys because
Chuck Norris is always in command."
};
console.log(JSON.stringify(newJoke));
// {"categories":["dev"],"value":"Chuck Norris's keyboard is made up
entirely of Cmd keys because Chuck Norris is always in command."}
console.log(JSON.stringify(user));
// result: {"id":101010,"name":"Derek","email":"derek@awesome.com"}
console.log(JSON.stringify(user, replacer));
// {"name":"Derek","email":"Removed for privacy"}
JSON.parse
JSON is used to exchange data from a web server. Data is always received in a string form from
a web server.
JSON.parse(), method helps to convert string data form into a JavaScript object.
var myObj = '{ "name": "Black Widow", "age": 32, "city": "New York" }';
var result = JSON.parse(myObj);
// Output: { name: "Black Widow", age: 32, city: "New York"}
Asynchronous Operations
Asynchronous operations provide a response after being processed using Web APIs. The purpose of
writing an asynchronous function is to utilize the function's output for subsequent operations.
JavaScript is single-threaded. This means that it carries out asynchronous operations via the callback
queue and event loop.
In synchronous JavaScript, each function is performed in turn, waiting for the previous one to
complete before executing the subsequent one. Synchronous code is written from top to bottom.
//Output
synchronous.
synchronous javascript!
Be good do good
Synchronous JavaScript runs from top to bottom, as we can observe the console running the function
linearly from top to bottom.
Async programming is vital because it allows multiple processes to run concurrently without
interfering with the main thread.
This is significant because the main thread is in charge of managing the call stack, which is a data
structure that holds the current sequence of function calls.
Blockage of the main thread leads to decreased performance because async programming permits
the main thread to stay unblocked, and additional tasks can be completed while the asynchronous
task is ongoing.
A JavaScript function call called the setTimeout() function, which allows us to run javascript code
after a certain amount of time.
After the specified time, the setTimeout() method executes a block of code. The method only runs
the code once.
Example:
console.log("asynchronous.");
setTimeout(() => console.log("asynchronous javascript!"), 3000));
console.log("asynchronous again!");
//Output
asynchronous.
asynchronous again!
asynchronous javascript!
Step 1: The first line of code will be executed, logging the string asynchronous to the console.
Step 2: The setTimeout method is invoked, which will execute the anonymous function after 3
seconds (3,000 milliseconds). The anonymous function will log asynchronous javascript! to the
console.
Step 3: The third line of code will be executed, logging the string asynchronous again! to the console.
Step 4: After 3 seconds, the anonymous function from the setTimeout method will be executed,
logging asynchronous javascript! to the console.
The setTimeout() method is being used in this code to postpone the execution of a function. It will
log the string output is begun after 5 seconds to the console using the function, which in this case is
an arrow function. The provided delay is 5,000 milliseconds (or 5 seconds).
Example for callback hell:
function incrementDigits(num, callback) {
setTimeout(function() {
num++;
console.log(num);
if (num< 10) {
incrementDigits(num, callback);
} else {
callback();
}
}, 1000);
}
incrementDigits(0, function() {
console.log('done!');
});
The setTimeout() function is used to delay the execution of the code in order to simulate a longer
process. The function will print out each number, starting at 0, until it reaches 10, and then the done!
message will be printed out.
As a result, the code can run asynchronously, which means that the functions can run concurrently
rather than waiting for one another to complete.
Handling callback hell
The way to create a callback function is to pass it as a parameter to another function and then call it
back after the task is completed.
There are ways to handle callbacks.
1. Use of promise: a promise can be generated for each callback. When the callback is successful, the
promise is resolved, and if the callback fails, the promise is rejected.
2. Use of async-await: asynchronous functions are executed sequentially with the use of await;
execution stops until the promise is revolved and function execution is successful.
Synchronous callbacks
listing few of callback methods in java script they are:
array.map(callback),
array.forEach(callback),
array.find(callback),
array.filter(callback),
array.reduce(callback, init)
The asynchronous callback
The asynchronous callback is executed after the execution of the higher-order function.
Example1:
function a() { Output:
b(); Welcome to KMIT
}
function b() { After 5 secs
setTimeout(() => {
console.log("After 5 secs");
}, 5000);
}
function c() {
console.log("Welcome to KMIT");
}
a();
c();
Promise
An async promise operation’s eventual success or failure is represented as a JavaScript object. It
enables the creation of asynchronous code that works and appears synchronous. A promise, in our
context, is something that will take some time to do. A promise has three possible states: pending,
fulfilled, or rejected.
Pending: the promise has been created, and the asynchronous function it's associated with has not
succeeded or failed yet. This is the state your promise is in when it's returned from a call to fetch(),
and the request is still being made.
Fulfilled: the asynchronous function has succeeded. When a promise is fulfilled, its then() handler is
called.
Rejected: the asynchronous function has failed. When a promise is rejected, its catch() handler is
called.
The constructor function takes a function as an argument. This function is called the executor
function.
// Promise constructor as an argument
function(resolve, reject){
// doSomethingHere
}
The executor function takes two arguments, resolve and reject.
which runs automatically when a new promise is created and processes the code as follows:
Step 1: A new promise is created using the promise constructor and two arguments, resolve and
reject.
Step 2: The `.then()“ method is called on the promise, which takes two callback functions, one for if
the promise is resolved and one for if the promise is rejected.
Step 3: The first callback function will be executed if the promise is successfully resolved, while the
second callback function will be executed if the promise is rejected.
function myDisplayer(some) {
console.log(some);
}
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Async/await
The use of await, which halts execution until the promise is fulfilled, allows us to write asynchronous
functions as though they were synchronous (executed sequentially). Async/await is a technique for
building asynchronous code that looks and behaves like synchronous code. It enables you to
construct code that appears to run in sequence but operates asynchronously.
Example:
//async/await
(async()=>{
const res =await incrementDigits(0);
console.log(res);
})();
The async/await syntax is used in this code fragment to increment a number until it reaches 10. The
async keyword, which comes before the declaration of the incrementDigits() function, denotes that a
promise will be returned by the function.
Error handling in asynchronous JavaScript
Error handling in asynchronous JavaScript involves try/catch blocks, which are used in JavaScript to
catch any mistakes that might happen throughout the asynchronous process.
try{
alert("This is an error function!")
}catch(e){
alert(e)
}
A catch block can have parameters that will give you error information. Generally, the catch block is
used to log an error or display specific messages to the user. Now that the “incrementDigits()“
asynchronous function has an error handler function
Example
const incrementDigits = async num=>{
try{
num++;
console.log(num);
if(num<10){
await incrementDigits(num);
}else{
return'done!';
}
}catch(err){
console.log(err);
}
};
(async()=>{
const res =await incrementDigits(0);
console.log(res);
})();
DOM Manipulations
DOM and its importance:
The Document Object Model (DOM) is a programming interface for web documents. It represents the
structure of a web page and allows you to interact with and manipulate its elements using JavaScript.
DOM manipulation is crucial for creating dynamic web applications. It allows to update the content,
structure, and style of a web page in response to user actions, making your website interactive and
responsive.
DOM Tree Structure:
The DOM is structured as a tree, with the Document Object at the top. Each HTML element becomes
a node in this tree, and you can traverse, access, and modify these nodes.
Accessing Elements:
Selecting Elements by ID:
You can select elements with a specific ID using document.getElementById().
Selecting Elements by Class:
To select elements by class name, use document.getElementsByClassName().
Selecting Elements by Tag Name:
To select elements by their HTML tag, use document.getElementsByTagName().
Selecting Elements by CSS Selectors:
Use document.querySelectorAll() to select elements using CSS selectors.
// Selecting an element by ID
const elementById = document.getElementById('myElementId');
Modifying Elements:
Changing HTML Content:
You can change the content of an element using the innerHTML property.
Changing Element Attributes:
Use the setAttribute() method to modify element attributes.
Modifying Element Styles:
Alter the styles of elements by accessing their style property.
// Removing an element
elementById.removeChild(newElement);
// Cloning an element
const cloneElement = elementById.cloneNode(true);
Event Handling:
Adding Event Listeners:
Attach event listeners to elements using addEventListener().
Event Object and Event Types:
Event listeners receive an event object with details about the event, including its type.
Event Bubbling and Event Delegation:
Understand how events propagate through the DOM and use event delegation for efficiency.
Do refer the table provided towards the end of the document for more such events available in
javascipt.
DOM Traversal:
Navigating the DOM Tree:
You can navigate up and down the DOM tree using properties like parentElement, childNodes, etc.
Parent, Child, and Sibling Elements:
Access parent, child, and sibling elements with parentNode, children, nextSibling, and previousSibling.
Finding Elements within a Parent:
Use querySelectorAll() on a parent element to find specific child elements.