Introduction to Scripting Languages
Introduction to Scripting Languages
Highly flexible for rapid Can be more rigid but optimized for
development larger systems
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
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
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)
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();
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
Primitive Data types will have certain Non-Primitive data types can be
values. NULL.
Examples are numbers and strings. Examples are Array and Linked List.
Primitive Non-Primitive
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);
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.
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);
JavaScript
let result = [Link](10, 20);
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 */
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:
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.
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;
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.
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;
}
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;
Output
It's a warm day.
Summary
Conditional
Statement Description