0% found this document useful (0 votes)
30 views51 pages

Unit 2

JavaScript is a lightweight, interpreted programming language widely used for creating dynamic web applications and can be executed on both client and server sides. It offers advantages such as easy setup, browser support, and dynamic typing, but has limitations including security restrictions on file access and lack of multithreading. JavaScript can be embedded in HTML using <script> tags, and can be categorized into primitive and non-primitive data types, with variables declared using var, let, or const.
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)
30 views51 pages

Unit 2

JavaScript is a lightweight, interpreted programming language widely used for creating dynamic web applications and can be executed on both client and server sides. It offers advantages such as easy setup, browser support, and dynamic typing, but has limitations including security restrictions on file access and lack of multithreading. JavaScript can be embedded in HTML using <script> tags, and can be categorized into primitive and non-primitive data types, with variables declared using var, let, or const.
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
You are on page 1/ 51

What Is JavaScript?

JavaScript is a lightweight, interpreted programming language. It is commonly used to


create dynamic and interactive elements in web applications. JavaScript is very easy
to implement because it is integrated with HTML. It is open and cross-platform.

 JavaScript on the client side is directly executed in the user's browser. Almost all
browsers have JavaScript Interpreter and do not need to install any software.
There is also a browser console where you can test your JavaScript code.

 JavaScript is also used on the Server side (on Web Servers) to access databases,
file handling and security features to send responses, to browsers.

Advantages of JavaScript
The merits of using JavaScript are:
 Easy Setup: We don’t need a particular editor to start writing the JavaScript code.
Even anyone can write JavaScript code in NotePad.
 Browser Support: All browsers support JavaScript, as all modern browser comes
with the built-in JavaScript execution environment.
 Event Handling: JavaScript allows you to handle the events used to interact with
the web page.
 Dynamic Typing: JavaScript decides the type of variables at runtime. So, we
don’t need to care about variable data type while writing the code, providing more
flexibility to write code.
 Cross-platform Support: Each operating system and browser support
JavaScript. So, it is widely used for developing websites, mobile applications,
games, desktop applications, etc.
 Object-oriented Programming: JavaScript contains the classes, and we can
implement all object-oriented programming concepts using its functionality.
It also supports inheritance, abstraction, polymorphism, encapsulation, etc,
concepts of Object-oriented programming.
 Less server interaction: You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your
server.
 Richer interfaces: You can use JavaScript to include such items as drag-and drop
components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:
 Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
 JavaScript cannot be used for networking applications because there is no such
support available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.
JAVASCRIPT – SYNTAX
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within you
web page, but it is normally recommended that you should keep it within the <head>
tags.
The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes:
 Language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
 Type: This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
So your JavaScript syntax will look as follows.
<script language="javascript" type="text/javascript">
JavaScript code
</script>
YourFirst JavaScriptCode
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
document.write('Hello World');
</script>
</body>
</html>

Comments in JavaScript
JavaScript comments can be used to explain JavaScript code, and to make it more
readable. Comments are used to add notes to your code without affecting its execution.
JavaScript comments can also be used to prevent execution, when testing alternative
code.

1. Single Line Comments:- Single line comments start with //.Any text between //
and the end of the line will be ignored by JavaScript (will not be executed).
2. Multi-line Comments:- Multi-line comments start with /* and end with */.Any text
between /* and */ will be ignored by JavaScript.
Note:-
 JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.
 The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
The following example shows how to use comments in JavaScript.

<script language="javascript" type="text/javascript">


<!--
// This is a comment. It is similar to comments in C++
/*
This is a multiline comment in JavaScript
It is very similar to comments in C Programming
*/
//-->
</script>
JavaScript Placement in HTML File
1. Internal JavaScript :-

Internal JavaScript refers to embedding JavaScript code directly within the HTML file
using <script> tag.
However the most preferred ways to include JavaScript in an HTML file are as follows:
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.

Syntax

<script>
// JavaScript code here
</script>
(a) JavaScript in <head>...</head> section:-

If you want to have a script run on some event, such as when a user clicks somewhere,
then you will place that script in the head as follows −

<html>
<head>
<script type = "text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>

<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
(b) JavaScript in <body>...</body> section:-

If you need a script to run as the page loads so that the script generates content in the
page, then the script goes in the <body> portion of the document. In this case, you
would not have any function defined using JavaScript. Take a look at the following code.

<html>
<head>
</head>
<body>
<script type = "text/javascript">
document.write("Hello World")
</script>
<p>This is web page body </p>
</body>
</html>
(c) JavaScript in <body> and <head> Sections:-

You can put your JavaScript code in <head> and <body> sections altogether as follows

<html>
<head>
<script type = "text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>

<body>
<script type = "text/javascript">
document.write("Hello World")
</script>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
Advantages:-
 No need for extra HTTP requests to load scripts.
 Easy to use for small code snippets specific to a single HTML file.
Disadvantages:-
 Makes the HTML file less readable by mixing code and content.
 Difficult to maintain when the script grows large.
 Does not allow for JavaScript code caching.
2. External JavaScript:-
External JavaScript is when the JavaScript code written in another file having an
extension .js is linked to the HMTL with the src attribute of script tag.
Syntax
<script src="url_of_js_file"> </script>
Multiple script files can also be added to one page using several <script> tags.
<script src="file1.js"> </script>
<script src="file2.js"> >/script>
The use of external JavaScript is more practical when the same code is to be used in
many different web pages. Using an external script is easy, just put the name of the
script file(our .js file) in the src (source) attribute of <script> tag. External JavaScript
file can not contain <script> tags.

For example, you can keep the following content in the filename.js file, and then you
can use the sayHello function in your HTML file after including the filename.js file.

filename.js

function sayHello() {
alert("Hello World")
}
Note:- External JavaScript file doesn’t contain the <script> tag.

Here is an example to show how you can include an external JavaScript file in your
HTML code using the script tag and its src attribute.
You may include the external script reference within the <head> or <body> tag.

<html>
<head>
<script type = "text/javascript" src = "filename.js" ></script>
</head>
<body>
...
</body>
</html>
External References:-

You can add an external JavaScript file in the HTML using the below 3 ways.

1. Using the full file path

When you need to add any hosted JavaScript file or a file that doesn’t exists in the same
project into the HTML, you should use the full file path.

For example,

<head>
<script src = "C://javascript/filename.js" ></script>
</head>
2. Using the relative file path

If you are working on the project and JavaScript and HTML both files are in different
folders, you can use the relative file path.

<head>
<script src = "javascript\filename.js" ></script>
</head>
3. Using the filename only
If HTML and JavaScript both files are in the same folder, you can use the file name.
<head>
<script src = "filename.js" ></script>
</head>

Advantages of External JavaScript

There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further
reduces the page loading time.
4. It enables both web designers and coders to work with html and js files parallelly
and separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the js
file.
Disadvantages of External JavaScript

There are the following disadvantages of external files:

1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect
the execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external
javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.
JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set
of data types it supports. These are the type of values that can be represented and
manipulated in a programming language.

1. Primitive Datatypes:- Primitive datatypes represent single values and are


immutable.

1. Number Represents numeric values let n = 42;


(integers and decimals). let pi = 3.14;
2. String Represents text enclosed in let s = "Hello, World!";
single or double quotes.
3. Boolean Represents a logical value (true let bool= true;
or false).
4. A variable that has been let notAssigned;
Undefined declared but not assigned a console.log(notAssigned);
value.
5. Null Represents an intentional let empty = null;
absence of any value.
6. Symbol Represents unique and let sym = Symbol('unique');
immutable values, often used as
object keys.
7. BigInt Represents integers larger than let bigNumber =
Number.MAX_SAFE_INTEGER. 123456789012345678901234567890n;

2. Non-Primitive Datatypes:- Non-primitive types are objects and can store


collections of data or more complex entities.

1. Object Represents key-value pairs. let obj = {


name: "Amit",
age: 25
};
2. Array Represents an ordered list of values. let a = ["red", "green", "blue"];

3. Function Represents reusable blocks of code. function fun() {

console.log("GeeksforGeeks");
}
JavaScriptVariables
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 The var keyword is used var n = 10; Output


Keyword to declare a variable. It var n = 12; // Re-declaration is allowed 12
has a function-scoped or console.log(n);
globally-scoped console.log(n);
behaviour.
2. let The let keyword is let n= 10; Output
n = 20; // Value can be updated 20
Keyword introduced in ES6, has block
scope and cannot be re- // let n = 15; //can not redeclare
declared in the same scope. console.log(n)
3. const The const keyword declares const n = 100; Output
// n = 200; This will throw an error 100
Keyword variables that cannot be
reassigned. It’s block-scoped console.log(n)
as well.

JavaScriptVariableScope
The scope of a variable is the region of your program in which it is defined. JavaScript
variables have only two scopes.
 Global Variables: A global variable has global scope which means it can be
defined anywhere in your JavaScript code.
 Local Variables: A local variable will be visible only within a function where it
is defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable
with the same name. If you declare a local variable or function parameter with the
same name as a global variable, you effectively hide the global variable.

Example: Below is an example of Local scope.

function foo() {
var x = '1';
console.log('inside function: ', x);
}

foo(); // Inside function: 1


console.log(x); // Error: x is not defined

Output (In Console):

inside function: 1
x is not defined

Example: Below is an example of Global scope.

// Global scope
var x = '1'
const y = '2'
let z = '3'

console.log(x); // 1
console.log(y); // 2
console.log(z); // 3

function getNo() {
console.log(x); // x is accessible here
console.log(y); // y is accessible here
console.log(z); // z is accessible here
}
getNo();
Output
1
2
3
1
2
3
JavaScript Output
JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id)


method.

The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Output:-
Example
<!DOCTYPE html> My First Web Page
<html>
<body> My First Paragraph.
<h1>My First Web Page</h1>
<p>My First Paragraph</p> 11
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

Using document.write()

For testing purposes, it is convenient to use document.write().Using document.write()


after an HTML document is loaded, will delete all existing HTML.

The document.write() method should only be used for testing.

Example
<!DOCTYPE html>
Output:-
<html>
<body>
My First Web Page
<h1>My First Web Page</h1>
My First Paragraph.
<p>My first paragraph.</p>
11
<script>
document.write(5 + 6);
</script>

</body>
</html>
Using window.alert()

You can use an alert box to display data. You can skip the window keyword.

In JavaScript, the window object is the global scope object. This means that variables,
properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional.

Example
<!DOCTYPE html>
<html> Output:-
<body>
My First Web Page
<h1>My First Web Page</h1>
<p>My first paragraph.</p> My First Paragraph.

<script> 11
window.alert(5 + 6); //or alert(5 + 6);
</script>

</body>
</html>
Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display
data.
Example
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>
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 following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Logical Operators
4. Assignment Operators
5. Ternary (Conditional) Operators
6. String Operators
7. Type Operators
8. Bitwise Operators
9. Special Operators

1. Arithmetic Operators:-

We use arithmetic operators to perform arithmetic calculations like addition,


subtraction, etc.

Operator Name Example


+ Addition 3 + 4 // 7
- Subtraction 5 - 3 // 2
* Multiplication 2 * 3 // 6
/ Division 4 / 2 // 2
% Remainder 5 % 2 // 1
++ Increment (increments by 1) ++5 or 5++ // 6
-- Decrement (decrements by 1) --4 or 4-- // 3
** Exponentiation (Power) 4 ** 2 // 16
Example 1: Arithmetic Operators in JavaScript

<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = "); Output
result = a - b; a + b = 43
document.write(result); a - b = 23
a / b = 3.3
document.write(linebreak); a % b = 3
document.write("a / b = "); a + b + c = 43Test
a++ = 33
result = a / b;
b-- = 10
document.write(result);
document.write(linebreak); Set the variables to different values and then try...
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and then try...</p>
</body>
</html>
2. JavaScript Comparison Operators :-
We use comparison operators to compare two values and return a boolean value (true
or false).
Operator Meaning Example

== Equal to 3 == 5 gives us false

!= Not equal to 3 != 4 gives us true

> Greater than 4 > 4 gives us false

< Less than 3 < 3 gives us false


>= Greater than or equal to 4 >= 4 gives us true

<= Less than or equal to 3 <= 3 gives us true

=== Strictly equal to 3 === "3" gives us false

!== Strictly not equal to 3 !== "3" gives us true

Example 2: Comparison Operators in JavaScript


<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => "); Output
result = (a < b); (a == b) => false
document.write(result); (a < b) => true
document.write(linebreak); (a > b) => false
document.write("(a > b) => "); (a != b) => true
result = (a > b); (a >= b) => false
document.write(result); (a <= b) => true
document.write(linebreak); Set the variables to different values and
35 different operators and then
document.write("(a != b) => "); try...
result = (a != b);
document.write(result);
document.write(linebreak);
document.write("(a >= b) => ");
result = (a >= b);
document.write(result);
document.write(linebreak);
document.write("(a <= b) => ");
result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
3. JavaScript Logical Operators
We use logical operators to perform logical operations on boolean expressions.
Operator Syntax Description

&& (Logical expression1 && true only if both expression1 and expression2
AND) expression2 are true

expression1 || true if either expression1 or expression2 is


|| (Logical OR)
expression2 true

! (Logical NOT) !expression false if expression is true and vice versa

Example 3: Logical Operators in JavaScript


<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => ");
result = (a && b);
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then
try...
4. JavaScript Assignment Operators :-

We use assignment operators to assign values to variables.

Operator Name Example


= Assignment Operator a = 7;
+= Addition Assignment a += 5; // a = a + 5
-= Subtraction Assignment a -= 2; // a = a - 2
*= Multiplication Assignment a *= 3; // a = a * 3
/= Division Assignment a /= 2; // a = a / 2
%= Remainder Assignment a %= 2; // a = a % 2
**= Exponentiation Assignment a **= 2; // a = a**2

Example 4: Assignment Operators in JavaScript


<html>
<body>
<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a += b) => ");
result = (a += b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a -= b) => ");
result = (a -= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a *= b) => ");
result = (a *= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a /= b) => ");
result = (a /= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a %= b) => ");
result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...

5. Conditional Operator (?:)


The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the
evaluation.

Operator Description
? : (Conditional )
(?:)
If Condition is true? Then value X : Otherwise value Y

Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200; Output
document.write(result); ((a > b) ? 100 : 200) => 200
document.write(linebreak); ((a < b) ? 100 : 200) => 100
document.write ("((a < b) ? 100 : 200) => "); Set the variables to different values
and different operators and then
result = (a < b) ? 100 : 200;
try...
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
6. JavaScript String Operators

Operator Description Example


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Operators</h1>
<script>
let text1 = "Hello";
All the comparison let text2 = "Hi";
String let result = text1 < text2;
operators can also be
Comparison document.write("Is A less than B? " + result);
used on strings
</script>
</body>
</html>
Output
JavaScript String Operators
Is A less than B? true
<!DOCTYPE html>
<html>
The + can also be used to <body>
add (concatenate) <script>
strings. let text1 = "What a very ";
String Addition text1 += "nice day";
Note:-The += assignment document.write(text1);
operator can also be used </script>
to add (concatenate) </body>
strings </html>
Output
What a very nice day
<!DOCTYPE html>
<html>
<body>
<p>Adding a number and a string, returns a
string.</p>
<script>
let x = 5 + 5;
Adding let y = "5" + 5;
Strings and adding a number and a let z = "Hello" + 5;
Numbers string will return a string document.write(x + "<br>" + y + "<br>" + z);
</script>
</body>
</html>
Output
Adding a number and a string, returns a string.
10
55
Hello5

1. JavaScript typeof Operator


The typeof operator is a unary operator that is placed before its single operand,
which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a
number, string, or boolean value and returns true or false based on the evaluation.

Syntax of typeof Operator


typeof operand
The possible types that are available in JavaScript that typeof operator returns are:

Types typeof Result


String "string"
Number "number"
BigInt "bigint"
Boolean "boolean"
Object "object"
Symbol "symbol"
undefined "undefined"
null "object"
function "function"

Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...
JavaScript Conditional statements (if, else, and else if)
1. JavaScript if-statement

It is a conditional statement used to decide whether a certain statement or block of


statements will be executed or not i.e. if a certain condition is true then a block of
statements is executed otherwise not.

Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Example :-

2. JavaScript if-else statement

JavaScript if-else statement executes a block of code based on a condition. If the


condition evaluates to true, the code inside the “if” block executes; otherwise, the code
inside the “else” block, if present, executes.

Such control statements are used to cause the flow of execution to advance and branch
based on changes to the state of a program.

Syntax:
if (condition) {
// block of code to be executed if the condition is true
}
else {
// block of code to be executed if the condition is false
}
Example:

3. JavaScript if-else-if ladder statement

Here, a user can decide among multiple options. The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.

Syntax:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Example:

4. JavaScript nested-if statement

JavaScript allows us to nest if statements within if statements. i.e, we can place an if


statement inside another if statement. A nested if is an if statement that is the target of
another if or else.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example:
// JavaScript program to illustrate nested-if statement
let i = 10;
if (i == 10) { // First if statement
if (i < 15) {
console.log("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
console.log("i is smaller than 12 too");
else
console.log("i is greater than 15");
}
}

JavaScript switch Statement

The JavaScript switch statement evaluates an expression and executes a block of


code based on matching cases. It provides an alternative to long if-else chains,
improving readability and maintainability, especially when handling multiple conditional
branches.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Example:

let grade = "C";

// using switch...case
switch (grade) {
// first condition
case "A":
console.log("Excellent!");
break;
// second condition
case "B":
console.log("Good!");
break;
// third condition
case "C":
console.log("Average");
break;
// fourth condition
case "D":
console.log("Bad");
break;
default:
console.log("Fail");
}

// Output: Average

How Switch Statement Works

 Evaluation: The expression inside the switch the statement is evaluated once.

 Comparison: The value of the expression is compared with each case label (using
strict equality ===).

 Execution: If a match is found, the corresponding code block following the


matching case the label is executed. If no match is found, the execution jumps to
the default case (if present) or continues with the next statement after the switch
block.

 Break Statement: After executing a code block, the break statement terminates
the switch statement, preventing execution from falling through to subsequent
cases. If break is omitted, execution will continue to the next case (known as “fall-
through”).

 Default Case: The default case is optional. If no match is found, the code block
under default is executed.

Why do we use the break statement in a switch block?

The break statement is used to terminate the switch block once a matching case is
executed. Without break, the code will continue executing the subsequent cases (known
as “fall-through”), even if they don’t match.

What happens if there is no matching case in a switch statement?

If no cases match, the default block (if provided) will be executed. If there’s no default
block, no code runs if there are no matches.

JavaScript Loops
Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block
of code as long as a specified condition is true. This makes code more concise and
efficient.
JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times


 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true

The for Loop

The JavaScript for loop iterates the elements for the fixed number of times. It should
be used if number of iteration is known. It executes a block of code until a specified
condition is true.

The for statement creates a loop with 3 optional expressions:

for (expression 1; expression 2; expression 3) {


// code block to be executed
}

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed.

Example :-
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>

Output:

1
2
3
4
5
JavaScript while loop

The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. In the while loop, the condition is
first checked and if it evaluates to TRUE, the statements inside the curly braces are
executed.

Syntax Output:
while (condition) { 11 // code block to be executed
} 12
Example: 13
<script> 14
var i=11; 15
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Do-While loop

A Do-While loop is another type of loop in JavaScript that is similar to the while loop,
but with one key difference: the do-while loop guarantees that the block of code inside
the loop will be executed at least once, regardless of whether the condition is initially
true or false .

Syntax

do {
// code block to be executed
} while (condition);
Example:
<script> Output:
var i=21; 21
do{ 22
document.write(i + "<br/>"); 23
i++; 24
}while (i<=25); 25
</script>

JavaScript break Statement


The break statement terminates the loop immediately when it's encountered.

Example
// infinite loop because condition is always true
while (true) {
// get number input from user
let num = Number(prompt("Enter a number: "));

// break condition
if (num == 0) {
break;
}

console.log(num);
}

// Output:
// Enter a number: 5
// 5
// Enter a number: 0

In this example, the break statement terminates the infinite loop when the user input
num is 0. If it isn't 0, the loop keeps taking input and printing it to the screen.

JavaScript continue Statement

The continue statement skips the current iteration of the loop and proceeds to the next
iteration.

Example
// display odd numbers

for (let i = 1; i <= 5; i++) {


// skip the iteration if i is even
if (i % 2 === 0) {
continue;
}
console.log(i);
}

// Output:
// 1
// 3
// 5

Here, continue skips the rest of the loop's body when i is even. Thus, only odd numbers
are printed.
JavaScript - Functions
A function in JavaScript is a group of reusable code that can be called anywhere in your program. It eliminates
the need of writing the same code again and again. It helps programmers in writing modular codes. Functions
allow a programmer to divide a big program into a number of small and manageable functions.

Function Syntax and Working


Function Definition:-

A function definition is sometimes also termed a function declaration or function statement. Below are the rules
for creating a function in JavaScript:

 Begin with the keyword function followed by,

 A user-defined function name


 A list of parameters enclosed within parentheses and separated by commas.

 A list of statements composing the body of the function enclosed within curly braces {}.

function functionName(parameters) {
// code to be executed
}
Function Calling:
Function Calling at a later point in the script, simply type the function’s name. By default, all JavaScript
functions can utilize argument objects. Each parameter’s value is stored in an argument object.
// Function calling
functionName ();

Why Functions?
 Functions can be used multiple times, reducing redundancy.
 Break down complex problems into manageable pieces.
 Manage complexity by hiding implementation details.
 Can call themselves to solve problems recursively.
Key Characteristics of Functions
 Parameters and Arguments: Functions can accept parameters (placeholders) and be called with
arguments (values).
 Return Values: Functions can return a value using the return keyword.
 Default Parameters: Default values can be assigned to function parameters.

Example

The below code shows the button in the output. When you click the button, it will execute the sayHello()
function. The sayHello() function prints the "Hello there!" message in the output.

Open Compiler
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p> Use different text in the write method and then try... </p>
</body>
</html>

JavaScript Function Arguments


A function can contain one or more arguments that are sent by the calling code and can be utilized within the
function. Because JavaScript is a dynamically typed programming language, a Function Arguments can have
any data type as a value. A function can take multiple parameters separated by comma.
Example

Try the following example. We have modified our sayHello function here. Now it takes two parameters.

Open Compiler
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
The return Statement

A JavaScript function can have an optional return statement. This is required if you want to return a value
from a function. This statement should be the last statement in a function.

For example, you can pass two numbers in a function, and then you can expect the function to return their
multiplication in your calling program.

Example

The code below defines a function that concatenates two parameters before returning the resultant in the calling
program. Also, you may take a look that how it returns the value using the return statement.

Open Compiler
<html>
<head>
<script type="text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara ', 'Ali');
alert(result);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Types of Functions in JavaScript
1. Named function:
A Named function is one that we write in code and then use whenever we need it by referencing its name and
providing it with some parameters. Named functions come in handy when we need to call a function several
times to give various values to it or run it multiple times.
function add(a, b) {
return a + b;
}
console.log(add(5, 4));

Output
9
2. Anonymous function:
We can define a function in JavaScript without giving it a name. This nameless function is referred to as
the Anonymous function. A variable must be assigned to an anonymous function.
let add = function (a, b) {
return a + b;
}
console.log(add(5, 4));

Output
9
3. Nested Functions:
A function in JavaScript can contain one or more inner functions. These Nested Functions fall within the
purview of the outer function. The inner function has access to the variables and arguments of the outer
function. However, variables declared within inner functions cannot be accessed by outer functions.
function msg(firstName) {
function hey() {
console.log("Hey " + firstName);
}
return hey();
}
msg("Ravi");

Output
Hey Ravi
4. Immediately invoked function expression:
The browser executes the invoked function expression as soon as it detects it. Immediately invoked function
expression has the advantage of running instantly where it is situated in the code and producing direct output.
That is, it is unaffected by code that occurs later in the script and can be beneficial.
let msg = (function() {
return "Welcome to GfG" ;
})();
console.log(msg);

Output
Welcome to GfG
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike,
chair, glass, keyboard, monitor etc.

The JavaScript object is a non-primitive data type that is used to store data as key-value pairs. The key-value
pairs are often referred as properties. A key in a key-value pair, also called a "property name", is a string and
value can be anything. If a property's value is a function, the property is known as a method.

Objects are created using curly braces and each property is separated by a comma. Each property is written as
property name followed by colon (:) followed by property value. The key: value pairs are not stored in the
specific order in the object. So an object is an unordered collection of properties written as key: value pairs.

Creating Objects in JavaScript


There are different ways to create an object in JavaScript.

 Using an Object Literal


 Using the new Keyword
 Using an Object Constructor

(1) The JavaScript Object Literal:-


In JavaScript, ‘{}’ is represented by the object literal. You can add pair of key-value pairs between curly braces
to define an object.
You can follow the syntax below to use the object literal to define objects.
let obj = {
key: val,
}
Example

In the example below, we have defined a wall object containing the 4 properties. Each property contains the
different values of different data types.

<html>
<body>
Output
<p id = "output"> </p>
Book name is : Perl
<script>
Book author is : Ajay
const myBook = {
Total pages : 355
title: "Perl",
author: "Ajay",
pages: 355,
}
document.getElementById("output").innerHTML =
"Book name is : " + myBook.title + "<br>"
+"Book author is : " + myBook.author + "<br>"
+"Total pages : " + myBook.pages;
</script>
</body>
</html>
(2) The JavaScript new keyword:-

The new keyword is used to create an instance of an object. To create an object, the new operator is followed by
the constructor method.

Syntax of creating object directly is given below:

var objectname=new Object();


Example
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
(3) The JavaScript Object() Constructor

A constructor is a function that creates and initializes an object. JavaScript provides a special constructor
function called Object() to build the object. The return value of the Object() constructor is assigned to a
variable.

The variable contains a reference to the new object. The properties assigned to the object are not variables and
are not defined with the var keyword.

Example

Try the following example; it demonstrates how to create an Object.

<html>
<body>
<p id = "output"> </p>
<script>
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Ajay";
document.getElementById("output").innerHTML =
"Book name is : " + book.subject + "<br>" +
"Book author is : " + book.author; Output
</script> Book name is : Perl
</body> Book author is : Ajay
</html>
Basic Operations on JavaScript Objects
1. Accessing Object Properties
You can access an object’s properties using either dot notation or bracket notation
let obj = { name: "Sourav", age: 23 };

// Using Dot Notation


console.log(obj.name);

// Using Bracket Notation


console.log(obj["age"]);
Output
Sourav
23
2. Modifying Object Properties
Properties in an object can be modified by reassigning their values.
let obj = { name: "Sourav", age: 22 };
console.log(obj);

obj.age = 23;
console.log(obj);
Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }
3. Adding Properties to an Object
You can dynamically add new properties to an object using dot or bracket notation.
let obj = { model: "Tesla" };
obj.color = "Red";
console.log(obj);
Output
{ model: 'Tesla', color: 'Red' }
4. Removing Properties from an Object
The delete operator removes properties from an object.
let obj = { model: "Tesla", color: "Red" };
delete obj.color;
console.log(obj);
Output
{ model: 'Tesla' }
5. Checking if a Property Exists
You can check if an object has a property using the in operator or hasOwnProperty() method.
let obj = { model: "Tesla" };
console.log("color" in obj);
console.log(obj.hasOwnProperty("model"));
Output
false
true
6. Iterating Through Object Properties
Use for…in loop to iterate through the properties of an object.
let obj = { name: "Sourav", age: 23 };
for (let key in obj) {
console.log(key + ": " + obj[key]);
}
Output
name: Sourav
age: 23
7. Merging Objects
Objects can be merged using Object.assign() or the spread syntax { …obj1, …obj2 }.
let obj1 = { name: "Sourav" };
let obj2 = { age: 23};
let obj3 = { ...obj1, ...obj2 };
console.log(obj3);
Output
{ name: 'Sourav', age: 23 }
8. Object Length
You can find the number of properties in an object using Object.keys().
let obj = { name: "Sourav", age: 23 };
console.log(Object.keys(obj).length);
Output
2
9. Recognizing a JavaScript Object
To check if a value is an object, use typeof and verify it’s not null.
let obj = { name: "Sourav" };
console.log(typeof obj === "object" && obj !== null);
Output
true
Key Differences Between {} and new Object()
Feature {} (Object Literal) new Object() (Object Constructor)
Ease of Use More concise and readable. Less commonly used.
Performance Faster and more efficient. Slightly slower due to the constructor call.
Prototypal
Directly inherits from Object.prototype. Same, but adds an extra layer of abstraction.
Inheritance
Customization Literal syntax is sufficient for most use cases. Useful only in rare scenarios.
JavaScript Arrays
In JavaScript, an array is an ordered list of values. Each value is called an element, and each
element has a numeric position in the array, known as its index. Arrays in JavaScript are zero-
indexed, meaning the first element is at index 0, the second at index 1, and so on.

Syntax

Use the following syntax to create an array object in JavaScript −

const array_name = [item1, item2, ...];


Creating an Array
There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1. Create Array using Literal

The syntax of creating array using array literal is given below:

var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

Example :-
<script>
Output
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++) Sonoo
{ Vimal
document.write(emp[i] + "<br/>"); Ratan
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script> Output
var i;
var emp = new Array(); Arun
emp[0] = "Arun"; Varun
emp[1] = "Varun"; John
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide
value explicitly.

The example of creating object by array constructor is given below.

<script> Output
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){ Jai
document.write(emp[i] + "<br>"); Vijay
} Smith
</script>
Basic Operations on JavaScript Arrays
1. Accessing Elements of an Array

Any element in the array can be accessed using the index number. The index in the arrays starts with 0.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Accessing Array Elements


console.log(a[0]);
console.log(a[1]);

Output
HTML
CSS
2. Accessing the First Element of an Array

The array indexing starts from 0, so we can access first element of array using the index number.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Accessing First Array Elements


let fst = a[0];

console.log("First Item: ", fst);

Output
First Item: HTML
3. Accessing the Last Element of an Array

We can access the last array element using [array.length – 1] index number.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Accessing Last Array Elements


let lst = a[a.length - 1];

console.log("First Item: ", lst);

Output
First Item: JS
4. Modifying the Array Elements

Elements in an array can be modified by assigning a new value to their corresponding index.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];
console.log(a);

a[1]= "Bootstrap";
console.log(a);

Output
[ 'HTML', 'CSS', 'JS' ]
[ 'HTML', 'Bootstrap', 'JS' ]
5. Adding Elements to the Array

Elements can be added to the array using methods like push() and unshift().

 The push() method add the element to the end of the array.

 The unshift() method add the element to the starting of the array.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Add Element to the end of Array


a.push("Node.js");

// Add Element to the beginning


a.unshift("Web Development");

console.log(a);

Output
[ 'Web Development', 'HTML', 'CSS', 'JS', 'Node.js' ]
6. Removing Elements from an Array

To remove the elements from an array we have different methods like pop(), shift(), or splice().

 The pop() method removes an element from the last index of the array.

 The shift() method removes the element from the first index of the array.

 The splice() method removes or replaces the element from the array.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];
console.log("Original Array: " + a);

// Removes and returns the last element


let lst = a.pop();
console.log("After Removing the last: " + a);

// Removes and returns the first element


let fst = a.shift();
console.log("After Removing the First: " + a);

// Removes 2 elements starting from index 1


a.splice(1, 2);
console.log("After Removing 2 elements starting from index 1: " + a);

Output
Original Array: HTML,CSS,JS
After Removing the last: HTML,CSS
After Removing the First: CSS
After Removing 2 elements starting from index 1: CSS
7. Array Length

We can get the length of the array using the array length property.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

let len = a.length;

console.log("Array Length: " + len);

Output
Array Length: 3
8. Increase and Decrease the Array Length

We can increase and decrease the array length using the JavaScript length property.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"]

// Increase the array length to 7


a.length = 7;

console.log("After Increasing Length: ", a);

// Decrease the array length to 2


a.length = 2;
console.log("After Decreasing Length: ", a)

Output
After Increasing Length: [ 'HTML', 'CSS', 'JS', <4 empty items> ]
After Decreasing Length: [ 'HTML', 'CSS' ]
9. Iterating Through Array Elements

We can iterate array and access array elements using for loop.

Example: It is an example of for loop.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Iterating through for loop


for (let i = 0; i < a.length; i++) {
console.log(a[i])
}

Output
HTML
CSS
JS
10. Array Concatenation

Combine two or more arrays using the concat() method. It returns new array containing joined arrays elements.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS", "React"];
let b = ["Node.js", "Expess.js"];

// Concatenate both arrays


let concateArray = a.concat(b);

console.log("Concatenated Array: ", concateArray);


Output
Concatenated Array: [ 'HTML', 'CSS', 'JS', 'React', 'Node.js', 'Expess.js' ]
11. Conversion of an Array to String

We have a builtin method toString() to converts an array to a string.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Convert array ot String


console.log(a.toString());

Output
HTML,CSS,JS
12. Check the Type of an Arrays

The JavaScript typeof operator is used ot check the type of an array. It returns “object” for arrays.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Check type of array


console.log(typeof a);

Output
Object

JavaScript Strings

‘A JavaScript String is a sequence of characters, typically used to represent text.

 In JavaScript there is no character type (Similar to Python and different from C, C++ and
Java), so a single character string is used when we need a character.

 Like Java and Python, strings in JavaScript are immutable.

Creating String
There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)

1) By string literal

We can either use a single quote or a double quote to create a string. The syntax of creating string using string
literal is given below:

var stringname="string value";

Let's see the simple example of creating string literal.

<script>
var str="This is string literal";
document.write(str);
</script>
Output:

This is string literal

2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Let's see the example of creating string in JavaScript by new keyword.

<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>

Output:

hello javascript string

Basic Operations on JavaScript Strings


1. Finding the length of a String

You can find the length of a string using the length property.

let s = 'JavaScript';

let len = s.length;

console.log("String Length: " + len);

Output
String Length: 10

2. String Concatenation

You can combine two or more strings using + Operator.

let s1 = 'Java';

let s2 = 'Script';

let res = s1 + s2;

console.log("Concatenated String: " + res);

Output
Concatenated String: JavaScript
3. Escape Characters

We can use escape characters in string to add single quotes, dual quotes, and backslash.

\' - Inserts a single quote


\" - Inserts a double quote
\\ - Inserts a backslash
const s1 = "\'GfG\' is a learning portal";
const s2 = "\"GfG\" is a learning portal";
const s3 = "\\GfG\\ is a learning portal";

console.log(s1);
console.log(s2);
console.log(s3);

Output
'GfG' is a learning portal
"GfG" is a learning portal
\GfG\ is a learning portal

4. Breaking Long Strings

We will use a backslash to break a long string in multiple lines of code.

const s = "'GeeksforGeeks' is \
a learning portal";

console.log(s);

Output
'GeeksforGeeks' is a learning portal

Note: This method might not be supported on all browsers. A better way to break a string is by
using the string addition.

const s = "'GeeksforGeeks' is a"


+ " learning portal";

console.log(s);

Output
'GeeksforGeeks' is a learning portal

5. Find Substring of a String

We can extract a portion of a string using the substring() method.

let s1 = 'JavaScript Tutorial';

let s2 = s1.substring(0, 10);


console.log(s2);

Output
JavaScript

6. Convert String to Uppercase and Lowercase

Convert a string to uppercase and lowercase using toUpperCase() and toLowerCase() methods.

let s = 'JavaScript';

let uCase = s.toUpperCase();

let lCase = s.toLowerCase();

console.log(uCase);
console.log(lCase);

Output
JAVASCRIPT
javascript

7. String Search in JavaScript

Find the first index of a substring within a string using indexOf() method.

let s1 = 'def abc abc';

let i = s1.indexOf('abc');

console.log(i);

Output
4

8. String Replace in JavaScript

Replace occurrences of a substring with another using replace() method.

let s1 = 'Learn HTML at GfG';

let s2 = s1.replace('HTML', 'JavaScript');

console.log(s2);

Output
Learn JavaScript at GfG

9. Trimming Whitespace from String

Remove leading and trailing whitespaces using trim() method.


let s1 = ' Learn JavaScript ';

let s2 = s1.trim();

console.log(s2);

Output
Learn JavaScript

10. Access Characters from String

Access individual characters in a string using bracket notation and charAt() method.

let s1 = 'Learn JavaScript';

let s2 = s1[6];

console.log(s2);

s2 = s1.charAt(6);

console.log(s2);

Output
J
J

11. String Comparison in JavaScript

There are some inbuilt methods that can be used to compare strings such as the equality
operator and another like localeCompare() method.

let str1 = "John";


let str2 = new String("John");

console.log(str1 == str2);
console.log(str1.localeCompare(str2));

Output
true
0

Note: The Equality operator returns true, whereas the localeCompare method returns the
difference of ASCII values.

12. Passing JavaScript String as Objects

We can create a JavaScript string using the new keyword.

const str = new String("GeeksforGeeks");


console.log(str);

Output
[String: 'GeeksforGeeks']
Qus:-Are the strings created by the new keyword is same as normal strings?

No, the string created by the new keyword is an object and is not the same as normal strings.

const str1 = new String("GeeksforGeeks");


const str2 = "GeeksforGeeks";

console.log(str1 == str2);
console.log(str1 === str2);

Output
true
false
JavaScript Date Object
The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by
the help of JavaScript date object.

You can use different Date constructors to create date object. It provides methods to get and set day, month,
year, hour, minute and seconds.

Creating Date Objects

Date objects are created with the new Date() constructor.

There are 9 ways to create a new date object:

1. new Date()
2. new Date(date string)
3. new Date(year,month)
4. new Date(year,month,day)
5. new Date(year,month,day,hours)
6. new Date(year,month,day,hours,minutes)
7. new Date(year,month,day,hours,minutes,seconds)
8. new Date(year,month,day,hours,minutes,seconds,ms)
9. new Date(milliseconds)
JavaScript Date Example
Let's see the simple example to print date object. It prints date and time both.

Current Date and Time: <span id="txt"></span>


<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>

Output:

Current Date and Time: Sat Mar 01 2025 22:30:07 GMT+0530 (India Standard Time)
Let's see another code to print date/month/year.
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>

Output:

Date is: 1/3/2025

JavaScript Current Time Example

Let's see the simple example to print current time of system.

Current Time: <span id="txt"></span>


<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>

Output:

Current Time: 22:30:7

JavaScript Math Object


JavaScript Math object is used to perform mathematical operations on numbers. All the properties of Math are
static and unlike other objects, it does not have a constructor.

We use Math only on Number data type and not on BigInt

Syntax

The syntax to call the properties and methods of Math are as follows −

var pi_val = Math.PI; // Property

var sine_val = Math.sin(30); // Method


JavaScript Math Properties

Following is the list of properties of Math class in JavaScript −

Sr.No. Name & Description Example


E console.log("Math.E: " + Math.E);

1
Euler's constant and the base of natural
logarithms, approximately 2.718.
LN2 console.log("Math.LN2: " + Math.LN2);
2
Natural logarithm of 2, approximately 0.693.
LN10 console.log("Math.LN10: " + Math.LN10);

3
Natural logarithm of 10, approximately
2.302.
LOG2E console.log("Math.LOG2E: " + Math.LOG2E);
4
Base 2 logarithm of E, approximately 1.442.
LOG10E console.log("Math.Log10E: " + Math.LOG10E);

5
Base 10 logarithm of E, approximately
0.434.
PI console.log("Math.PI: " + Math.PI);

6
The ratio of a circle's circumference to its
diameter is approximately 3.14159.
SQRT1_2 console.log("Math.SQRT1_2: " + Math.SQRT1_2);

7
The square root of 1/2, equivalently, 1 over
the square root of 2, is approximately 0.707.
console.log("Math.SQRT2: " + Math.SQRT2);
8 SQRT2
The square root of 2, approximately 1.414.

JavaScript Math Methods


Math.sqrt(n)

The JavaScript math.sqrt(n) method returns the square root of the given number.

Square Root of 17 is: <span id="p1"></span>


<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>

Output:

Square Root of 17 is: 4.123105625617661

Math.random()

The JavaScript math.random() method returns the random number between 0 to 1.

Random Number is: <span id="p2"></span>


<script>
document.getElementById('p2').innerHTML=Math.random();
</script>

Output:

Random Number is: 0.9501566215092502


Math.pow(m,n)

The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.

3 to the power of 4 is: <span id="p3"></span>


<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>

Output:

3 to the power of 4 is: 81


Math.floor(n)

The JavaScript math.floor(n) method returns the lowest integer for the given number. For example 3 for 3.7, 5
for 5.9 etc.

Floor of 4.6 is: <span id="p4"></span>


<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>

Output:

Floor of 4.6 is: 4


Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For example 4 for 3.7, 6
for 5.9 etc.

Ceil of 4.6 is: <span id="p5"></span>


<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script>

Output:

Ceil of 4.6 is: 5


Math.round(n)

The JavaScript math.round(n) method returns the rounded integer nearest for the given number. If fractional
part is equal or greater than 0.5, it goes to upper value 1 otherwise lower value 0. For example 4 for 3.7, 3 for
3.3, 6 for 5.9 etc.

Round of 4.3 is: <span id="p6"></span><br>


Round of 4.7 is: <span id="p7"></span>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>

Output:

Round of 4.3 is: 4


Round of 4.7 is: 5
Math.abs(n)

The JavaScript math.abs(n) method returns the absolute value for the given number. For example 4 for -4, 6.6
for -6.6 etc.

Absolute value of -4 is: <span id="p8"></span>


<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script>
Output:
Absolute value of -4 is: 4

JavaScript Numbers

JavaScript numbers are primitive data types and, unlike other programming languages, you
don’t need to declare different numeric types like int, float, etc. JavaScript number object
follows IEEE standard to represent the floating-point numbers.This format stores numbers in 64
bits:

 0-51 bits store the value (fraction)

 52-62 bits store the exponent

 63rd bit stores the sign

Syntax
The syntax for creating a number object is as follows −

const val = new Number(number);

In the place of number, if you provide any non-number argument, then the argument cannot be converted into a
number, it returns NaN (Not-a-Number).

We can also create the number primitives by assigning the numeric values to the variables −

var x=102;//integer value


var y=102.7;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object

The JavaScript automatically converts the number primitive to the Number objects.

Adding Numbers and Strings:

 JavaScript uses the `+` operator for both addition and concatenation.

 Numbers are added, when strings are concatenated.

Example:

// Adding two numbers


let x = 10;
let y = 15;
let z = x + y;
console.log(z);

// Concatenating two strings:

let a = "10";
let b = "30";
let c = a + b;
console.log(c);

Output
25
1030
Numeric Strings:

JavaScript automatically converts the numeric strings to numbers in most operations like.

Example:

let x = "100" / "10";


let y = "100" * "10";
let z = "100" - "10";
console.log(x);
console.log(y);
console.log(z);

Output
10
1000
90
Undefined to NaN:

When you perform an operation involving undefined, JavaScript returns NaN (Not-a-Number).

const result = undefined + 10;


console.log(result); // NaN

Output
NaN
Null to 0:

The value null is coerced to 0 when used in arithmetic operations.

const total = null + 5;


console.log(total); // 5

Output
5
Boolean to Number:

Boolean values (true and false) are converted to numbers: 1 for true and 0 for false.

const num1 = true + 10;


const num2 = false + 10;

console.log(num1);
console.log(num2);

Output
11
10
String to Number

When performing arithmetic operations, JavaScript converts strings to numbers. If the string cannot be parsed
as a valid number, it returns NaN.

const str1 = '42';


const str2 = 'hello';

const numFromString1 = Number(str1);


const numFromString2 = Number(str2);

console.log(numFromString1);
console.log(numFromString2);

Output
42
NaN

JavaScript Boolean
In JavaScript, a Boolean value can either be TRUE or FALSE. Booleans are often used in programming to
control the flow of logic such as conditional statements like if, else, while, etc., and in Boolean expressions that
evaluate to true or false.

JavaScript Boolean is an object that represents value in two states: true or false. You can create the JavaScript
Boolean() constructor as given below.

Syntax:

Boolean (variable/expression)

There are some key points about Boolean in JavaScript such as:
Values

Boolean has two possible values in JavaScript which are true and false. These values are case sensitive,
meaning True, TRUE, False, and FALSE are not valid Boolean values in JavaScript.

Usage

In JavaScript, Booleans are primarily used in conditional statements such as if statements to determine which
block of code should have been executed or whether the condition evaluates to true or false.

let isTrue = true;


let isFalse = false;

if (isTrue) {
console.log("This will be printed because isTrue is true.");
}
if (!isFalse) {
console.log("This will also be printed because isFalse is false.");
}
Boolean Operators

In JavaScript, we have several operators that return the Boolean values:

Comparison operator (==,!=, ===, !==, etc.) compares values and returns true or false.

Logical operators (&&, ||, !) combine or invert boolean values to form more complex conditions.

Implicit Conversion

Sometimes JavaScript also performs automatic type conversion, or coercion in certain situations. For example,
when using a non-boolean value in a conditional context JavaScript will convert it to a Boolean:

if ("hello") {
console.log("This will be printed because non-empty strings are truthy.");
}

if (0) {
console.log("This will NOT be printed because 0 is falsy.");
}

As you can see in the above example, "hello" evaluates to true because it's a non-empty string, while 0
evaluates to false.

The Boolean() Function

The Boolean() function is used to explicitly convert a value to its Boolean equivalent. Truthy values return true,
while falsy values return false.

console.log(Boolean("Hello"));
console.log(Boolean(0));

Output
true
false

 Non-empty strings like “Hello” are truthy.

 Zero is a falsy value.


Everything With a “Value” is True

In JavaScript, all objects, arrays, and non-empty strings are considered truthy values.

console.log(Boolean({}));
console.log(Boolean([]));
console.log(Boolean("Hi"));

Output
true
true
true

Objects and arrays always evaluate to true in Boolean contexts.

Everything Without a “Value” is False

Certain values, like 0, null, undefined, NaN, and empty strings, are falsy.

console.log(Boolean("") === false);


console.log(Boolean(undefined));

Output
true
false

You might also like