0% found this document useful (0 votes)
15 views24 pages

Introduction to Scripting Languages

Uploaded by

632.hurabbs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views24 pages

Introduction to Scripting Languages

Uploaded by

632.hurabbs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to scripting languages

A scripting language is a programming language designed to automate


the execution of tasks that would otherwise be executed one by one by
a human operator. These languages are typically interpreted, meaning
that they are executed line by line by an interpreter rather than being
compiled into machine code beforehand.
Here are the some key features of scripting languages:
 Interpreted Execution: Scripting languages are typically interpreted
rather than compiled.
 Ease of Use: Scripting languages have simpler syntax, making them
easier to learn, especially for beginners.
 Dynamic Typing: Variables are typed at runtime, allowing more
flexibility during execution.
 Integration: Scripting languages are used to automate tasks by
connecting and controlling different programs or system components.
 High-Level Abstractions: They offer high-level features that simplify
interaction with systems and applications.
Popular Scripting Languages
Several scripting languages are widely used in different domains of
software development, automation, and web development. Some of the
most popular scripting languages include:
 Python: Python is one of the most popular and versatile scripting
languages. Known for its simple syntax and readability, Python is used
for web development, data analysis, machine learning, automation, and
more.
 JavaScript: JavaScript is the most widely used scripting language for
web development. It is primarily used for client-side scripting to create
interactive web pages but can also be used on the server-side
with [Link].
 Bash: Bash is a command-line shell and scripting language commonly
used in UNIX-like operating systems such as Linux and macOS for
system administration tasks.
 PHP: PHP is a server-side scripting language widely used for web
development. It powers popular content management systems
like WordPress and is embedded within HTML for dynamic content
generation.
 Ruby: Ruby is a dynamic, object-oriented scripting language known for
its elegant syntax and developer-friendly environment. It is commonly
used with the Ruby on Rails framework for web development.
 Perl: Perl is an interpreted scripting language known for its text-
processing capabilities. It is often used in system administration,
network programming, and web development.
 PowerShell: PowerShell is a task automation and configuration
management framework from Microsoft, which is used for system
administration tasks, particularly on Windows systems.
Advantages of scripting languages
Here are the some advantages of scripting languages:
 Easy learning: The user can learn to code in scripting languages
quickly, not much knowledge of web technology is required.
 Fast editing: It is highly efficient with the limited number of data
structures and variables to use.
 Interactivity: It helps in adding visualization interfaces and
combinations in web pages. Modern web pages demand the use of
scripting languages. To create enhanced web pages, fascinated visual
description which includes background and foreground colors and so
on.
 Functionality: There are different libraries which are part of different
scripting languages. They help in creating new applications in web
browsers and are different from normal programming languages.
Application of Scripting Languages
Scripting languages are used in many areas:
 Web Development: Scripting languages like JavaScript, PHP, and
Python are used for both client-side and server-side development,
enabling dynamic content and interactivity.
 Automation: Scripting languages automate repetitive tasks like file
management, system administration, and batch processing, saving
time and reducing human error.
 System Administration: Bash and PowerShell are commonly used for
managing servers, handling tasks like user management and system
monitoring.
 Data Processing: Scripting languages like Python and Perl are used
to manipulate, clean, and process data for tasks like ETL (Extract,
Transform, Load).
 Testing: Scripting languages are often used for writing automated
tests to ensure software functionality and efficiency.
Difference Between Scripting Languages vs
Programming Languages
Below are the difference between scripting languages and programming
languages:
Scripting Languages Programming Languages

Interpreted (line-by-line execution) Compiled (transformed to machine code)


Scripting Languages Programming Languages

Easier syntax, simpler tasks More complex and powerful syntax

Automation, web scripting, task


Full-fledged application development
automation

Slower execution due to


Faster execution due to compilation
interpretation

Highly flexible for rapid Can be more rigid but optimized for
development larger systems

Limitations of Scripting Languages


While scripting languages are incredibly useful in many contexts, they
also have some limitations:
 Performance: Scripting languages tend to be slower than compiled
languages because they are interpreted line by line.
 Limited Complexity: While they are great for smaller tasks and
scripting, scripting languages may not be suitable for large-scale,
performance-intensive applications.
 Dependency on Interpreters: Scripting languages rely on interpreters
to run the code, meaning that users must have the necessary
interpreter installed to run the script.

JavaScript overview
JavaScript is a versatile, dynamically typed programming language that
brings life to web pages by making them interactive. It is used for building
interactive web applications, supports both client-side and server-side
development, and integrates seamlessly with HTML, CSS, and a rich
standard library.
 JavaScript is a single-threaded language that executes one task at a
time.
 It is an interpreted language which means it executes the code line by
line.
 The data type of the variable is decided at run-time in JavaScript,
which is why it is called dynamically typed.
"Hello World" Program in Server Console
We can also print the "Hello World" program directly into the console
terminal without embedded it into HTML. Create an [Link] file and add
the code to it.
// This is a comment
[Link]("Hello, World!");
Run it in your terminal with:
node [Link]
Output:
Hello, World!
Comments in JavaScript
Comments are notes in your code that the JavaScript interpreter ignores.
They’re great for explaining what your code does or for testing purposes.
 Single-line comment: Starts with //
// This is a single-line comment
 Multi-line comment: Enclosed in /* */
/* This is a multi-line comment
spanning multiple lines */
Key Features of JavaScript
Here are some key features of JavaScript that make it a powerful
language for web development:
 Client-Side Scripting:JavaScript runs on the user's browser, so has a
faster response time without needing to communicate with the server.
 Versatile: JavaScript can be used for a wide range of tasks, from
simple calculations to complex server-side applications.
 Event-Driven: JavaScript can respond to user actions (clicks,
keystrokes) in real-time.
 Asynchronous: JavaScript can handle tasks like fetching data
from servers without freezing the user interface.
 Rich Ecosystem: There are numerous libraries and frameworks built
on JavaScript, such as React, Angular, and [Link], which make
development faster and more efficient.
Client Side and Server Side nature of JavaScript

JavaScript's flexibility extends to both the client-side and server-side,


allowing developers to create complete web applications. Here’s how it
functions in each environment:
Client-Side:
 Involves controlling the browser and its DOM (Document Object
Model).
 Handles user events like clicks and form inputs.
 Common libraries include AngularJS, ReactJS, and VueJS.
Server-Side:
 Involves interacting with databases, manipulating files, and generating
responses.
 [Link] and frameworks like [Link] are widely used for server-side
JavaScript, enabling full-stack development.
Programming Paradigms in JavaScript
JavaScript supports both imperative and declarative programming styles:
 Imperative Programming: Focuses on how to perform tasks by
controlling the flow of computation. This includes approaches like
procedural and object-oriented programming, often using constructs
like async/await to handle asynchronous actions.
 Declarative Programming: Focuses on what should be done rather
than how it’s done. It emphasizes describing the desired result, such
as with arrow functions, without detailing the steps to achieve it.

Limitations of JavaScript
Despite its power, JavaScript has some limitations to consider:
 Security Risks : JavaScript can be used for attacks like Cross-Site
Scripting (XSS), where malicious scripts are injected into a website to
steal data by exploiting elements like <img>, <object>, or <script> tags.
 Performance : JavaScript is slower than traditional languages for
complex tasks, but for simple tasks in a browser, performance is
usually not a major issue.
 Complexity : To write advanced JavaScript, programmers need to
understand core programming concepts, objects, and both client- and
server-side scripting, which can be challenging.
 Weak Error Handling and Type Checking : JavaScript is weakly
typed, meaning variables don’t require explicit types. This can lead to
issues as type checking is not strictly enforced.
JavaScript Versions
Let’s take a look at the different versions of ECMAScript, their release
years, and the key features they introduced
Version Year Key Features

ES5 2009 strict mode, JSON, getters/setters

ES6 2015 let/const, classes, arrow functions

ES7-ES13 2016-2022 async/await, BigInt, optional chaining

ES14 2023 toSorted, findLast, static blocks

Note: Older versions of browsers do not support ES6.

Primitive data types and objects


Variables hold values, and every value has a specific data type that
defines the kind of information it holds. These data types are broadly
categorized into two groups: Primitive Data Types and Non-Primitive
Data Types. Let us discuss it one by one.
1. Primitive Data Types
Primitive data types are the built-in data types provided by JavaScript.
They represent single values and are not mutable. JavaScript supports
the following primitive data types:
1.1 Number:
Number data type in JavaScript can be used to hold decimal values as
well as values without decimals.
Example: Below is an example.
let x = 250;
let y = 40.5;
[Link]("Value of x=" + x);
[Link]("Value of y=" + y);

Output
Value of x=250
Value of y=40.5

1.2 String:
The string data type in JavaScript represents a sequence of characters
that are surrounded by single or double quotes.
Example: Below is an example.
let str = 'Hello All';
let str1 = "Welcome to my new house";
[Link]("Value of str=" + str);
[Link]("Value of str1=" + str1);

Output
Value of str=Hello All
Value of str1=Welcome to my new house

1.3 Undefined:
This means that a variable has been declared but has not been assigned
a value, or it has been explicitly set to the value `undefined`.
Example: Below is an example.
let x;
[Link](x); // Outputs: undefined
Output:
1.4 Boolean:
The boolean data type can accept only two values i.e. true and false.
Example: Below is an example.
let x;
[Link](x); // Outputs: undefined
Output:

1.5 Null:
This data type can hold only one possible value that is null.
Example: Below is an example.
let x = null;
[Link]("Value of x=" + x);

Output
Value of x=null

1.6 BigInt:
BigInt data type can represent numbers greater than 253-1 which helps to
perform operations on large numbers. The number is specified by writing
'n' at the end of the value
Example: Below is an example.
let bigNum = 123422222222222222222222222222222222222n
[Link](bigNum)

Output

123422222222222222222222222222222222222n

1.7 Symbol:
Symbol data type is used to create objects which will always be unique.
these objects can be created using Symbol constructor.
Example: Below is an example.
let sym = Symbol("Hello")
[Link](typeof(sym));
[Link](sym);
Output
symbol
Symbol(Hello)

2. Non-primitive Data Types


Non-primitive data types, also known as reference types, are objects and
derived data types. They can store collections of values or more complex
entities. The two key non-primitive data types in JavaScript are:
Below is a list of Non-primitive data types.
2.1 Object:
An object in Javascript is an entity having properties and methods.
Everything is an object in javascript.
How to create an object in javascript:
 Using Constructor Function to define an object:
// Create an empty generic object
let obj = new Object();

// Create a user defined object


let mycar = new Car();
 Using Literal notations to define an object:
// An empty object
let square = {};

// Here a and b are keys and


// 20 and 30 are values
let circle = {a: 20, b: 30};
Example: Below is an example.
// Creating object with the name person
let person = {
firstName: "Luiza",
lastName: "Shaikh",
};

// Print the value of object on console


[Link]([Link]
+ " " + [Link]);

Output
Luiza Shaikh

2.2 Array:
With the help of an array, we can store more than one element under a
single name.
Ways to declare a single-dimensional array:
// Call it with no arguments
let a = new Array();

// Call it with single numeric argument


let b = new Array(10);

// Explicitly specify two or


// more array elements
let d = new Array(1, 2, 3, "Hello");
Example: Below is an example.
let a = new Array();
let b = new Array(10);
let d = new Array(1, 2, 3, "Hello");
[Link]("value of a=" + a);
[Link]("value of b" + b);
[Link]("value of d=" + d);

Output
value of a=
value of b,,,,,,,,,
value of d=1,2,3,Hello
Note: JavaScript does not support two-dimensional arrays. but we can do
this by creating an array of an array.
Difference Between Primitive vs Non-Primitive
Primitive Non-Primitive

Non-Primitive data types are created


Primitive Data types are predefined.
by the programmer

Primitive Data types will have certain Non-Primitive data types can be
values. NULL.

Size depends on the type of data


Size is not fixed
structure.

Examples are numbers and strings. Examples are Array and Linked List.
Primitive Non-Primitive

It can start with a lowercase. It can start with uppercase.

Variables
A variable is like a container that holds data that can be reused or
updated later in the program. In JavaScript, variables are declared using
the keywords var, let, or const.
1. var Keyword
The var keyword is used to declare a variable. It has a function-scoped or
globally-scoped behaviour.
var n = 5;
[Link](n);

var n = 20; // reassigning is allowed


[Link](n);

Output
5
20

2. let Keyword
The let keyword is introduced in ES6, has block scope and cannot be re-
declared in the same scope.
let n= 10;
n = 20; // Value can be updated
// let n = 15; //can not redeclare
[Link](n)

Output
20

3. const Keyword
The const keyword declares variables that cannot be reassigned. It's
block-scoped as well.
const n = 100;
// n = 200; This will throw an error
[Link](n)

Output
100
Exploring JavaScript Datatypes and Variables:
Understanding Common Expressions
[Link](null === undefined)
 Expression: null === undefined
 Result: false
In JavaScript, both null and undefined represent "empty" values but are
distinct types. null is a special object representing the intentional
absence of a value, while undefined signifies that a variable has been
declared but not assigned a value. Despite their similar purpose, they are
not strictly equal (===) to each other.
[Link](5 > 3 > 2)
 Expression: 5 > 3 > 2
 Result: false
At first glance, this expression may appear to be checking if 5 is greater
than 3 and 3 is greater than 2, but JavaScript evaluates it left-to-right due
to its operator precedence.
 First, 5 > 3 evaluates to true.
 Then, true > 2 is evaluated, which in JavaScript results in 1 > 2,
which evaluates to false.
So, 5 > 3 > 2 evaluates to false.
[Link]([] === [])
 Expression: [] === []
 Result: false
In JavaScript, arrays are objects. Even if two arrays have the same
content, they are still different objects in memory.
 When you compare two arrays with ===, you are comparing their
references, not their contents.
 Since [] and [] are different instances in memory, the result is false.
[Link]("10" < "9")
 Expression: "10" < "9"
 Result: true
When JavaScript compares strings, it compares their Unicode values
lexicographically (character by character).
 "10" is compared to "9". Since "1" has a lower Unicode value
than "9", JavaScript determines that "10" is less than "9" it's due to
JavaScript's string comparison mechanism. [Link](NaN === NaN)
 Expression: NaN === NaN
 Result: false
In JavaScript, NaN (Not-a-Number) is a special value that represents an
invalid number or the result of an operation that cannot produce a valid
number.
 One of the most unusual aspects of NaN is that it is not equal to itself.
This behavior exists due to the design of the IEEE 754 standard, which
JavaScript follows for floating-point arithmetic.
 As a result, NaN === NaN returns false.
To check if a value is NaN, use [Link]().
[Link](true == 1)
 Expression: true == 1
 Result: true
JavaScript uses type coercion with the loose equality operator (==). When
comparing true and 1, JavaScript converts true to 1 and then compares
the values.
 Since 1 == 1 is true, the overall expression evaluates to true.
This behavior might lead to unexpected results in some cases, so it’s
often recommended to use the strict equality operator (===) to avoid
implicit type coercion.
[Link](undefined > 0)
 Expression: undefined > 0
 Result: false
When JavaScript attempts to compare undefined with 0, it
converts undefined to NaN (Not-a-Number). Any comparison
involving NaN returns false.
 undefined > 0 becomes NaN > 0, which evaluates to false.
[Link]("5" === 5)
 Expression: "5" === 5
 Result: false
The strict equality operator (===) checks both value and type. Since "5" is
a string and 5 is a number, the types are different, and the comparison
returns false.
 If you used the loose equality operator ( ==), JavaScript would perform
type coercion, converting the string "5" to the number 5, and the
comparison would return true.
 [Link]([1, 2] == [1, 2])
 Expression: [1, 2] == [1, 2]
 Result: false
Even though both arrays contain the same elements, JavaScript
compares arrays by reference, not by value.
 Since each array is a separate object in memory, their references are
different, and thus the comparison returns false.
To check if two arrays are equal, you must compare their contents
element by element.
[Link](Infinity > 1000)
 Expression: Infinity > 1000
 Result: true
In JavaScript, Infinity represents an unbounded, positive number. It's
greater than any finite number, including 1000.
 Therefore, Infinity > 1000 evaluates to true.

COERCION in java script


Coercion in JavaScript refers to the process of converting a value from one
data type to another. This conversion can occur in two primary ways:
 Implicit Coercion (Automatic Type Conversion):
This happens automatically by the JavaScript engine when an operation,
comparison, or assignment involves values of different data types. JavaScript
attempts to make sense of the operation by converting one or both values to a
compatible type.
 Example: Adding a number and a string (e.g., 5 + "10") results in the number
being converted to a string, leading to string concatenation ( "510").
 Example: Using the loose equality operator ( ==) between a number and a string
(e.g., 1 == "1") results in the string being converted to a number for comparison,
leading to true.
 Explicit Coercion (Manual Type Conversion):
This involves intentionally converting a value to a different type using built-in
JavaScript functions or constructors. This provides more control and clarity over
the conversion process.
 Example: Converting a string to a number
using Number() (e.g., Number("123") results in 123).
 Example: Converting a value to a string using String() (e.g., String(123) results
in "123").
 Example: Converting a value to a boolean
using Boolean() (e.g., Boolean(0) results in false, while Boolean("hello") results
in true).

EXPRESSION in java script


In both Java and JavaScript, an expression is a combination of literals,
variables, operators, and method/function calls that evaluates to a single
value. This value can be a number, a string, a boolean, an object, or any
other data type supported by the language.

Key characteristics of expressions:


 Evaluation to a single value:
This is the defining characteristic. Whether it's a simple arithmetic calculation or a
complex function call, an expression always resolves to one specific value.
 Can be used as part of a larger statement:
Expressions often form components of statements, such as assignment
statements, conditional statements, or loop statements.
 May have side effects (optional):
While many expressions simply compute a value, some, like assignment
expressions (x = 5) or function calls that modify external state, can also produce
side effects.
Examples of expressions in Java and JavaScript:
Arithmetic expressions.
Java
int sum = 5 + 3;

JavaScript
let sum = 5 + 3;

String expressions.
Java
String greeting = "Hello" + " World";

JavaScript
let greeting = "Hello" + " World";

Boolean expressions.
Java
boolean isGreater = (x > 10);

JavaScript
let isGreater = (x > 10);

Function/method call expressions.


Java
int result = [Link](10, 20);

JavaScript
let result = [Link](10, 20);

Function expressions (JavaScript specific).


JavaScript
let sayHi = function() { [Link]("Hi!"); };

Comments in javascript
Comments help explain code (they are not executed and hence do not
have any logic implementation). We can also use them to temporarily
disable parts of your code.
1. Single Line Comments
A single-line comment in JavaScript is denoted by two forward slashes
(//),
// A single line comment
[Link]("Hello");
Output
Hello

2. Multi-line Comments
A multiline comment begins with /* and ends with */
/* It is multi line comment.
It will not be displayed upon
execution of this code */

[Link]("Multiline comment in javascript");

Output
Multiline comment in javascript

Uses of Comments:
 Code Explanation:
To clarify the purpose or logic of specific code sections, variables, or functions.
 Debugging:
To temporarily disable lines or blocks of code without deleting them.
 Documentation:
To provide information for other developers (or your future self) about the code's
design, assumptions, or usage.

JavaScript operators
JavaScript operators are symbols or keywords used to perform operations
on values and variables. They are the building blocks of JavaScript
expressions and can manipulate data in various ways.
There are various operators supported by JavaScript:

1. JavaScript Arithmetic Operators


Arithmetic Operators perform mathematical calculations like addition,
subtraction, multiplication, etc.
const sum = 5 + 3; // Addition
const diff = 10 - 2; // Subtraction
const p = 4 * 2; // Multiplication
const q = 8 / 2; // Division
[Link](sum, diff, p, q);

Output
8 8 8 4
 + adds two numbers.
 - subtracts the second number from the first.
 * multiplies two numbers.
 / divides the first number by the second.
2. JavaScript Assignment Operators
Assignment operators are used to assign values to variables. They can
also perform operations like addition or multiplication while assigning the
value.
let n = 10;
n += 5;
n *= 2;
[Link](n);

Output
30
 = assigns a value to a variable.
 += adds and assigns the result to the variable.
 *= multiplies and assigns the result to the variable.
3. JavaScript Comparison Operators
Comparison operators compare two values and return a boolean (true or
false). They are useful for making decisions in conditional statements.
[Link](10 > 5);
[Link](10 === "10");

Output
true
false
 > checks if the left value is greater than the right.
 === checks for strict equality (both type and value).
 Other operators include <, <=, >=, and !==.
4. JavaScript Logical Operators
Logical operators are mainly used to perform the logical operations that
determine the equality or difference between the values.
const a = true, b = false;
[Link](a && b); // Logical AND
[Link](a || b); // Logical OR

Output
false
true
 && returns true if both operands are true.
 || returns true if at least one operand is true.
 ! negates the boolean value.
5. JavaScript Bitwise Operators
Bitwise operators perform operations on binary representations of
numbers.
const res = 5 & 1; // Bitwise AND
[Link](res);

Output
1
 & performs a bitwise AND.
 | performs a bitwise OR.
 ^ performs a bitwise XOR.
 ~ performs a bitwise NOT.
6. JavaScript Ternary Operator
The ternary operator is a shorthand for conditional statements. It takes
three operands.
const age = 18;
const status = age >= 18 ? "Adult" : "Minor";
[Link](status);

Output
Adult
condition ? expression1 : expression2 evaluates expression1 if the
condition is true, otherwise evaluates expression2.
7. JavaScript Comma Operator
Comma Operator (,) mainly evaluates its operands from left to right
sequentially and returns the value of the rightmost operand.
let n1, n2
const res = (n1 = 1, n2 = 2, n1 + n2);
[Link](res);

Output
3
 Each expression is evaluated from left to right.
 The final result of the expression is the rightmost value.
8. JavaScript Unary Operators
Unary operators operate on a single operand (e.g., increment,
decrement).
let x = 5;
[Link](++x); // Pre-increment
[Link](x--); // Post-decrement (Output: 6, then x becomes 5)

Output
6
6
 ++ increments the value by 1.
 -- decrements the value by 1.
 typeof returns the type of a variable.
9. JavaScript Relational Operators
JavaScript Relational operators are used to compare its operands and
determine the relationship between them. They return a Boolean value
(true or false) based on the comparison result.
const obj = { length: 10 };
[Link]("length" in obj);
[Link]([] instanceof Array);

Output
true
true
 in checks if a property exists in an object.
 instanceof checks if an object is an instance of a constructor.
10. JavaScript BigInt Operators
BigInt operators allow calculations with numbers beyond the safe integer
range.
const big1 = 123456789012345678901234567890n;
const big2 = 987654321098765432109876543210n;
[Link](big1 + big2);
Output
1111111110111111111011111111100n
 Operations like addition, subtraction, and multiplication work with
BigInt.
 Use n suffix to denote BigInt literals.
11. JavaScript String Operators
JavaScript String Operators include concatenation (+) and concatenation
assignment (+=), used to join strings or combine strings with other data
types.
const s = "Hello" + " " + "World";
[Link](s);

Output
Hello World
 + concatenates strings.
 += appends to an existing string.
12. JavaScript Chaining Operator (?.)
The optional chaining operator allows safe access to deeply nested
properties without throwing errors if the property doesn’t exist.
const obj = { name: "Aman", address: { city: "Delhi" } };
[Link]([Link]?.city);
[Link]([Link]?.phone);

Output
Delhi
undefined
 ?. safely accesses a property or method.
 Returns undefined if the property doesn’t exist.

Conditional statements in javascrpit


JavaScript conditional statements allow you to execute specific blocks
of code based on conditions. If the condition is met, a particular block of
code will run; otherwise, another block of code will execute based on
the condition.
Types of Conditional Statements
 if statement
 if...else statement
 if...else if...else statement
 switch statement
 ternary (conditional) operator
1. if Statement
The if statement evaluates a condition inside parentheses. If the condition
is true, the block of code inside the curly braces {} runs. If it’s false, it
skips that block.
Syntax
if (condition) {
// code runs if condition is true
}
let x = 20;

if (x % 2 === 0) {
[Link]("Even");
}

if (x % 2 !== 0) {
[Link]("Odd");
};

Output
Even

2. if-else Statement
The if-else statement will perform some action for a specific condition.
Here we are using the else statement in which the else statement is
written after the if statement and it has no condition in their code block.
let age = 25;

if (age >= 18) {


[Link]("Adult")
} else {
[Link]("Not an Adult")
};

Output
Adult

3. else if Statement
The else if statement in JavaScript allows handling multiple possible
conditions and outputs, evaluating more than two options based on
whether the conditions are true or false.
const x = 0;
if (x > 0) {
[Link]("Positive.");
} else if (x < 0) {
[Link]("Negative.");
} else {
[Link]("Zero.");
};

Output
Zero.

4. Using Switch Statement (JavaScript Switch Case)


The switch statement is a control structure in JavaScript that allows you to
execute different blocks of code based on the value of a single
expression. It’s a cleaner, more readable alternative to multiple if...else if
statements when you need to compare one variable against many
possible values.
const marks = 85;

let Branch;

switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
case marks >= 80:
Branch = "Mechanical engineering";
break;
case marks >= 70:
Branch = "Chemical engineering";
break;
case marks >= 60:
Branch = "Electronics and communication";
break;
case marks >= 50:
Branch = "Civil engineering";
break;
default:
Branch = "Bio technology";
break;
}

[Link](`Student Branch name is : ${Branch}`);

Output
Student Branch name is : Mechanical engineering
5. Using Ternary Operator ( ?: )
The ternary operator is a compact shorthand for an if...else statement. It is
called “ternary” because it takes three operands:
 A condition to test.
 An expression to evaluate if the condition is true.
 An expression to evaluate if the condition is false.
Syntax
condition ? expressionIfTrue : expressionIfFalse
let age = 21;

const result =
(age >= 18) ? "You are eligible to vote."
: "You are not eligible to vote.";

[Link](result);

Output
You are eligible to vote.

6. Nested if...else
A nested if...else statement is an if...else structure placed inside another if
or else block. This allows you to check multiple conditions in a hierarchical
or layered way, making complex decision trees possible.
let weather = "sunny";
let temp = 25;

if (weather === "sunny") {


if (temp > 30) {
[Link]("It's a hot day!");
} else if (temp > 20) {
[Link]("It's a warm day.");
} else {
[Link]("It's a bit cool today.");
}
} else if (weather === "rainy") {
[Link]("Don't forget your umbrella!");
} else {
[Link]("Check the weather forecast!");
};

Output
It's a warm day.

Summary
Conditional
Statement Description

if statement Executes a block of code if a specified condition is true.

Executes a block of code if the same condition of the


else statement
preceding if statement is false.

Adds more conditions to the if statement, allowing for


else if statement
multiple alternative conditions to be tested.

Evaluates an expression, then executes the case


switch statement
statement that matches the expression's value.

Provides a concise way to write if-else statements in a


ternary operator
single line.

Nested if else Allows for multiple conditions to be checked in a


statement hierarchical manner.

Why Use Conditional Statements?


Here are the some reasons for using conditional statements:
 Control Program Flow: Decide which code to execute based on
different situations.
 Make Decisions: React differently to user input, data values, or
system states.
 Enhance Interactivity: Enable dynamic behavior in apps and
websites.
 Handle Multiple Scenarios: Manage different outcomes or error
handling paths.
 Improve Code Flexibility: Write adaptable, reusable code that can
respond to change.
Best Practices
 Keep Conditions Simple and Clear: Write straightforward
expressions to improve readability and reduce errors.
 Use Strict Equality (===) Over Loose Equality (==): Prevent
unexpected type coercion bugs.
 Always Use Curly Braces {}: Even for single-line blocks, to avoid
mistakes and improve maintainability.
 Prefer else if or switch for Multiple Conditions: Organize your code
better and enhance readability.
 Avoid Deep Nesting: Use logical operators (&&, ||) or early returns to
flatten your code structure.
 Include Default Cases: Use else or default to handle unexpected
conditions.
 Comment Complex Conditions: Explain the logic for future reference
and easier maintenance.
 Test All Possible Paths: Make sure every branch of your condition
executes as expected during testing.

You might also like