Unit 2
Unit 2
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.
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.
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>
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.
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.
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.
function foo() {
var x = '1';
console.log('inside function: ', x);
}
inside function: 1
x is not defined
// 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:
Using innerHTML
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()
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.
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:-
<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
&& (Logical expression1 && true only if both expression1 and expression2
AND) expression2 are true
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 :-
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...
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
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
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Example :-
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:
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:
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");
}
}
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example:
// 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
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 ===).
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.
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.
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:
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.
Expression 1 is executed (one time) before the execution of 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>
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.
The continue statement skips the current iteration of the loop and proceeds to the next
iteration.
Example
// display odd numbers
// 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.
A function definition is sometimes also termed a function declaration or function statement. Below are the rules
for creating a function in JavaScript:
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>
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.
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.
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
<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 };
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
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
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.
<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.
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.
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.
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.
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.
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.
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.
Output
Array Length: 3
8. Increase and Decrease the Array Length
We can increase and decrease the array length using the JavaScript length property.
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.
Output
HTML
CSS
JS
10. Array Concatenation
Combine two or more arrays using the concat() method. It returns new array containing joined arrays elements.
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.
Output
Object
JavaScript Strings
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.
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:
<script>
var str="This is string literal";
document.write(str);
</script>
Output:
The syntax of creating string object using new keyword is given below:
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Output:
You can find the length of a string using the length property.
let s = 'JavaScript';
Output
String Length: 10
2. String Concatenation
let s1 = 'Java';
let s2 = 'Script';
Output
Concatenated String: JavaScript
3. Escape Characters
We can use escape characters in string to add single quotes, dual quotes, and backslash.
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
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.
console.log(s);
Output
'GeeksforGeeks' is a learning portal
Output
JavaScript
Convert a string to uppercase and lowercase using toUpperCase() and toLowerCase() methods.
let s = 'JavaScript';
console.log(uCase);
console.log(lCase);
Output
JAVASCRIPT
javascript
Find the first index of a substring within a string using indexOf() method.
let i = s1.indexOf('abc');
console.log(i);
Output
4
console.log(s2);
Output
Learn JavaScript at GfG
let s2 = s1.trim();
console.log(s2);
Output
Learn JavaScript
Access individual characters in a string using bracket notation and charAt() method.
let s2 = s1[6];
console.log(s2);
s2 = s1.charAt(6);
console.log(s2);
Output
J
J
There are some inbuilt methods that can be used to compare strings such as the equality
operator and another like localeCompare() method.
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.
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.
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.
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.
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:
Output:
Syntax
The syntax to call the properties and methods of Math are as follows −
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.
The JavaScript math.sqrt(n) method returns the square root of the given number.
Output:
Math.random()
Output:
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
Output:
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.
Output:
Output:
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.
Output:
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.
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:
Syntax
The syntax for creating a number object is as follows −
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 −
The JavaScript automatically converts the number primitive to the Number objects.
JavaScript uses the `+` operator for both addition and concatenation.
Example:
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:
Output
10
1000
90
Undefined to NaN:
When you perform an operation involving undefined, JavaScript returns NaN (Not-a-Number).
Output
NaN
Null to 0:
Output
5
Boolean to Number:
Boolean values (true and false) are converted to numbers: 1 for true and 0 for false.
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.
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.
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
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 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
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
Certain values, like 0, null, undefined, NaN, and empty strings, are falsy.
Output
true
false