Introduction of Java Script, control Statement
& Looping:
JavaScript is a cross-platform, object-oriented scripting language used to make webpages
interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). There
are also more advanced server-side versions of JavaScript such as [Link], which allow you
to add more functionality to a website than downloading files (such as real time
collaboration between multiple computers). Inside a host environment (for example, a web
browser), JavaScript can be connected to the objects of its environment to provide
programmatic control over them.
JavaScript contains a standard library of objects, such as Array, Map, and Math, and a core set
of language elements such as operators, control structures, and statements. Core JavaScript
can be extended for a variety of purposes by supplementing it with additional objects; for
example:
• Client-side JavaScript extends the core language by supplying objects to control a
browser and its Document Object Model (DOM). For example, client-side extensions
allow an application to place elements on an HTML form and respond to user events
such as mouse clicks, form input, and page navigation.
• Server-side JavaScript extends the core language by supplying objects relevant to
running JavaScript on a server. For example, server-side extensions allow an
application to communicate with a database, provide continuity of information from
one invocation to another of the application, or perform file manipulations on a
server.
This means that in the browser, JavaScript can change the way the webpage (DOM) looks.
And, likewise, [Link] JavaScript on the server can respond to custom requests sent by code
executed in the browser.
Creating Variable in JavaScript:
In JavaScript, variables are created using the keywords let, const, and var. They act as
containers for storing data values.
Variable Declaration Keywords
The modern and recommended keywords are let and const. var is the older method and
generally avoided in modern JavaScript due to its confusing scoping behavior.
Keyword Reassignable? Requires Initial Value? Scope
let Yes No (defaults to undefined) Block-scoped
const No Yes Block-scoped
var Yes No (defaults to undefined) Function/Global scoped
How to Create and Initialize Variables
The basic syntax involves the keyword, a name, and an optional assignment operator (=)
followed by a value.
• Using let (for variables that can change):
let score = 5;
score = 10; // Value can be updated later
You can declare it without assigning a value initially, in which case it holds
undefined. let userName;
userName = "John";
• Using const (for values that should not change):
const pi = 3.14159;
// pi = 3.14; // This would cause an error (TypeError)
const variables must be assigned a value when they are declared.
• Using var (legacy method):
var age = 25;
Variable Naming Rules
When naming variables, you must follow a few rules:
• Names must start with a letter, an underscore (_), or a dollar sign ($). •
Names cannot start with a digit (0-9).
• Names can contain letters, digits, underscores, and dollar signs.
• Names are case-sensitive (age and Age are different variables).
• Reserved JavaScript keywords (e.g., let, class, return) cannot be used as variable names.
It is recommended to use descriptive names written in camelCase format (e.g.,
numberOfSeasons, annualSalary) for better code readability.
Comments:
JavaScript supports two types of comments that are ignored by the interpreter and used to
add notes, explanations, or temporarily disable code.
Types of Comments
• Single-line comments (//)
o Any text following // on the same line is treated as a comment.
o They are ideal for short notes or commenting on a single line of code.
// This is a single-line comment
let age = 30; // Inline comment to explain the variable's purpose
• Multi-line comments (/* ... */)
o Text placed between /* and */ can span multiple lines and is ignored by the
JavaScript engine.
o They are useful for longer explanations, documenting functions or commenting
out large blocks of code.
/*
This is a multi-line comment.
It is used to explain complex logic
or disable a block of code during testing.*/ let width = 5; let height = 10;
Datatypes in JavaScript
In JavaScript, non-primitive data types, also known as reference types or objects, are
used to store collections of data and more complex entities.
Example:
// Number
let length = 16;
let weight = 7.5;
// BigInt
let x = 1234567890123456789012345n;
let y = BigInt(1234567890123456789012345)
// Strings
let color = "Yellow";
let lastName = "Johnson";
// Boolean
let x = true;
let y = false;
// Undefined
let x; let y;
// Null
let x = null;
let y = null;
// Symbol
const x = Symbol();
const y = Symbol();
// Object
const person = {firstName:"John", lastName:"Doe"};
// Array Object
const cars = ["Saab", "Volvo", "BMW"];
// Date Object
const date = new Date("2022-03-25");
And etc.
We Will Discuss Various Object Datatypes in later Tutorials
Note: To Check Data Type of a Variable: use typeof operator
Operators in JavaScript:
In JavaScript, an operator is a symbol that performs an action on one or more values
(operands) and returns a result. Operators are a fundamental part of the language, used for
tasks like mathematical calculations, comparing values, and managing logic.
Common types of operators in JavaScript include:
• Arithmetic Operators: Perform mathematical calculations.
o + (Addition)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o % (Remainder/Modulus)
o ** (Exponentiation)
o ++ (Increment)
o -- (Decrement)
• Assignment Operators: Assign values to variables. The basic assignment operator is =,
but shorthand compound operators exist, such as += (add and assign) or *= (multiply
and assign).
• Comparison Operators: Compare two values and return a boolean (true or false).
o == (Equal to, checks value only, allows type coercion)
o === (Strict equal to, checks both value and type)
o != (Not equal to)
o !== (Strict not equal to)
o > (Greater than), < (Less than), >= (Greater than or equal to), <= (Less than or
equal to)
• Logical Operators: Combine multiple conditions.
o && (Logical AND)
o || (Logical OR)
o ! (Logical NOT)
• Miscellaneous/Unary Operators:
o ? : (Conditional or Ternary operator, a shorthand for if...else statements)
let a=20;
let b=15;
let x=(a>b)?true:false;
[Link](x);
o typeof (Returns the data type of an operand)
o in (Checks if a property exists in an object)
const car = {
make: "Honda",
model: "Accord",
year: 1998,
};
[Link]("make" in car); // Expected output: true
[Link]("color" in car); // Expected output: false
[Link]("toString" in car); // Expected output: true
(inherited property)
o delete (Removes a property from an object)
const person = {
name: 'John',
age: 30
};
[Link]([Link]+"<br>"); // 30
delete [Link];
[Link]([Link]+"<br>"); // undefined, the property is gone
Control Statements and Looping in JavaScript
Control statements in JavaScript are used to control the flow of execution of a program.
They help in decision-making and repeating tasks. Control structures are mainly divided into
Conditional Statements and Looping Statements.
Conditional Control Statements
if Statement
Executes a block of code if the condition is true.
let age = 18;
if (age >= 18) {
[Link]("Eligible to vote");
}
if...else Statement
Provides an alternative block if the condition is false.
let marks = 40;
if (marks >= 35) {
[Link]("Pass");
} else {
[Link]("Fail");
}
if...else if...else Statement
Used to test multiple conditions.
let grade = 85;
if (grade >= 90) {
[Link]("A Grade");
} else if (grade >= 75) {
[Link]("B Grade");
} else {
[Link]("C Grade");
}
switch Statement
Used when multiple values are checked against a single
expression. let day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
}
Looping Statements
Looping statements are used to execute a block of code repeatedly until a condition
becomes false.
for Loop
Used when the number of iterations is known.
for (let i = 1; i <= 5; i++) {
[Link](i);
}
while Loop
Executes as long as the condition is true.
let i = 1;
while (i <= 5) {
[Link](i);
i++;
}
do...while Loop
Executes the loop at least once, even if the condition is false.
let i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
for...in Loop
Used to iterate over object properties.
let student = { name: "Tushar", age: 25 };
for (let key in student) {
[Link](key + " : " + student[key]+"<br>");
}
for...of Loop
Used to iterate over iterable objects like arrays and strings.
let colors = ["Red", "Green", "Blue"];
for (let data of colors) {
[Link](data+" ");
forEach() method
The forEach() method is a clean and readable way to loop through arrays without the need
for manual index management (initialization, condition, increment).
Syntax:
[Link]((currentValue, index, array) => {
// code to be executed for each element
});
The callback function accepts up to three arguments:
• currentValue (required): The value of the current element being processed. •
index (optional): The index of the current element.
• array (optional): The original array that forEach was called upon.
Example
const fruits = ["apple", "banana", "cherry"];
[Link]((fruit, index) => {
[Link]("Fruit at index "+index+" : "+fruit+"<br>");
});
Loop Control Statements
break
Terminates the loop immediately.
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
[Link](i); }
continue
Skips the current iteration and continues with the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
[Link](i);
}