Nothing Special   »   [go: up one dir, main page]

Introduction To JavaScript

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 101

Introduction to JavaScript

JavaScript is a lightweight, cross-platform, and interpreted compiled


programming language
e which is also known as the scripting language for webpages. It is
well-known for the development of web pages, many non-browser
environments also use it.
 JavaScript can be used for Client-side developments as well
as Server-side developments.
 Javascript is both imperative and declarative type of language.
 JavaScript contains a standard library of objects,
like Array, Date, and Math, and a core set of language
elements like operators, control structures, and statements. 

 Client-side: It supplies objects to control a browser and


its Document Object Model (DOM). Like if client-side
extensions allow an application to place elements on an
HTML form and respond to user events such as mouse
clicks, form input, and page navigation. Useful libraries for
the client-side are AngularJS, ReactJS, VueJS and so many
others.
 Server-side: It supplies objects relevant to running
JavaScript on a server. Like if the server-side extensions
allow an application to communicate with a database, and
provide continuity of information from one invocation to
another of the application, or perform file manipulations on a
server. The useful framework which is the most famous these
days is node.js.
 Imperative language – In this type of language we are
mostly concern about how it is to be done . It simply control
the flow of computation . The procedural programming
approach , object, oriented approach comes under this like
async await
 Declarative programming – In this type of language we are
concern about how it is to be done , basically here logical
computation require . Here  main goal is to describe the
desired result without direct dictation on how to get it like
arrow function do .

JavaScript can be added to your HTML file in two ways:
 Internal JS: We can add JavaScript directly to our HTML
file by writing the code inside the <script> tag. The <script>
tag can either be placed inside the <head> or the <body> tag
according to the requirement.
 External JS: We can write JavaScript code in other file
having an extension.js and then link this file inside the
<head> tag of the HTML file in which we want to add this
code.
Syntax:
<script>
// JavaScript Code
</script>
Example:
 HTML

<!DOCTYPE html>
<html lang="en">
   
<head>
    <title>
        Basic Example to Describe JavaScript
    </title>
</head>
   
<body>
   
    <!-- JavaScript code can be embedded inside
        head section or body section -->
    <script>
        console.log("HELLO");
    </script>
</body>
   
</html>
Output: The output will display on the console.
HELLO

History of JavaScript: It was created in 1995 by Brendan Eich while


he was an engineer at Netscape. It was originally going to be named
LiveScript but was renamed. Unlike most programming languages,
the JavaScript language has no concept of input or output. It is
designed to run as a scripting language in a host environment, and it is
up to the host environment to provide mechanisms for communicating
with the outside world. The most common host environment is the
browser. 
a
Features of JavaScript: According to a recent survey conducted
by Stack Overflow, JavaScript is the most popular language on
earth. 
With advances in browser technology and JavaScript having moved
into the server with Node.js and other frameworks, JavaScript is
capable of so much more. Here are a few things that we can do with
JavaScript: 
 JavaScript was created in the first place for DOM
manipulation. Earlier websites were mostly static, after JS
was created dynamic Web sites were made.
 Functions in JS are objects. They may have properties and
methods just like another object. They can be passed as
arguments in other functions.
 Can handle date and time.
 Performs Form Validation although the forms are created
using HTML.
 No compiler is needed.

Applications of JavaScript: 
 Web Development: Adding interactivity and behavior to
static sites JavaScript was invented to do this in 1995. By
using AngularJS that can be achieved so easily.
 Web Applications: With technology, browsers have
improved to the extent that a language was required to create
robust web applications. When we explore a map in Google
Maps then we only need to click and drag the mouse. All
detailed view is just a click away, and this is possible only
because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code. The
Electron and React is helpful in this department.
 Server Applications: With the help of Node.js, JavaScript
made its way from client to server and node.js is the most
powerful on the server-side.
 Games: Not only in websites, but JavaScript also helps in
creating games for leisure. The combination of JavaScript
and HTML 5 makes JavaScript popular in game development
as well. It provides the EaseJS library which provides
solutions for working with rich graphics.
 Smartwatches: JavaScript is being used in all possible
devices and applications. It provides a library PebbleJS which
is used in smartwatch applications. This framework works for
applications that require the internet for its functioning.
 Art: Artists and designers can create whatever they want
using JavaScript to draw on HTML 5 canvas, and make the
sound more effective also can be used p5.js library.
 Machine Learning: This JavaScript ml5.js library can be
used in web development by using machine learning.
 Mobile Applications: JavaScript can also be used to build an
application for non-web contexts. The features and uses of
JavaScript make it a powerful tool for creating mobile
applications. This is a Framework for building web and
mobile apps using JavaScript. Using React Native, we can
build mobile applications for different operating systems.
Limitations of JavaScript: 
  Security risks: JavaScript can be used to fetch data using
AJAX or by manipulating tags that load data such as <img>,
<object>, <script>. These attacks are called cross site script
attacks. They inject JS that is not the part of the site into the
visitor’s browser thus fetching the details. 
 Performance: JavaScript does not provide the same level of
performance as offered by many traditional languages as a
complex program written in JavaScript would be
comparatively slow. But as JavaScript is used to perform
simple tasks in a browser, so performance is not considered a
big restriction in its use.
 Complexity: To master a scripting language, programmers
must have a thorough knowledge of all the programming
concepts, core language objects, client and server-side objects
otherwise it would be difficult for them to write advanced
scripts using JavaScript.
 Weak error handling and type checking facilities: It is
weakly typed language as there is no need to specify the data
type of the variable. So wrong type checking is not performed
by compile.

Why JavaScript is known as a lightweight programming


language?
JavaScript is considered as lightweight due to the fact that it has low
CPU usage, is easy to implement and has a minimalist syntax.
Minimalist syntax as in, it has no data types. Everything is treated
here as an object. It is very easy to learn because of its syntax similar
to C++ and Java.
A lightweight language does not consume much of your CPU’s
resources. It doesn’t put excess strain on your CPU or RAM.
JavaScript runs in the browser even though it has complex paradigms
and logic which means it uses fewer resources than other languages.
For example, NodeJs, a variation of JavaScript not only performs
faster computations but also uses less resources than its counterparts
such as Dart or Java.
Additionally, when compared with other programming languages, it
has less in-built libraries or frameworks, contributing as another
reason for it to be lightweight. However, this brings it a drawback that
we need to incorporate external libraries and frameworks. 
Is JavaScript compiled or interpreted or both?
JavaScript is both compiled and interpreted. In the earlier versions of
JavaScript, it used only the interpreter that executed code line by line
and shows the result immediately. But with time the performance
became an issue as interpretation is quite slow. Therefore, in the
newer versions of JS, probably after the V8, JIT compiler was also
incorporated to optimize the execution and display the result more
quickly. This JIT compiler generates a bytecode that is relatively
easier to code. This bytecode is a set of highly optimized instructions. 
The V8 engine initially uses an interpreter, to interpret the code. On
further executions, the V8 engine finds patterns such as frequently
executed functions, frequently used variables, and compiles them to
improve performance.
JavaScript is best known for web page development but it is also used
in a variety of non-browser environments. You can learn JavaScript
from the ground up by following this JavaScript
Tutorial and JavaScript Examples.

Characteristics of JS: 
 Platform independent: JavaScript runs on browsers
which is available on all kinds of machines and is
hence platform independent.
 Dynamically typed languages: This language can
receive different data types over time.
 Case-Sensitive Format: JavaScript is case-sensitive
so you have to be aware of that.
 Light Weight: It is so lightweight, and all browsers are
supported by JS.
 Handling: Handling events is the main feature of JS, it
can easily respond on the website when the user tries
to perform any operation.
 Interpreter-Centered: JavaScript is built with an
interpreter centered that allows the user to get the
output without the use of the compiler.

Advantages of JS: 
 JavaScript is executed on the user’s browsers not on
the webserver so it saves bandwidth and loads on the
webserver.
 The JavaScript language is easy to learn it offers
syntax that is close to the English language.
 In JavaScript, if you ever need any certain feature then
you can write it by yourself and use an add-on
like Greasemonkey to implement it on the web page.
 It does not require a compilation process so no
compiler is needed user’s browsers do the task.
 JavaScript is easy to debug, and there are lots of
frameworks available that you can use and become a
master of that.
 It is constantly being improved and newer features are
being introduced that significantly tamp down the lines
of code for web applications. For example, Arrow
Functions were introduced in the ES6 version which
provides a short syntax to write anonymous functions.

Disadvantages of JS: 
 JavaScript codes are visible to the user so the user
can place some code into the site that compromises
the security of data over the website. That will be a
security issue.
 All browsers interpret JavaScript which is correctly, but
they interpret it differently from each other.
 It only supports single inheritance, so in a few cases
may require the object-oriented language
characteristic.
 A single error in code can totally stop the website’s
code rendering on the website.
 JavaScript stores numbers as 64-bit floating-point
numbers but operators operate on 32-bit bitwise
operands. JavaScript first converts the number to 32-
bit, performs the operation, and converts it to 64-bit
again which reduces its speed.
 Lack of debugging facility compared to other
programming languages.

Where to put JavaScript in an HTML Document ?


Scripts can be placed inside the body or the head section of an
HTML page or inside both the head and body. We can also place
javascript outside the HTML file which can be linked by specifying
its source in the script tag.
JavaScript in head: A JavaScript function is placed inside the head
section of an HTML page and the function is invoked when a button
is clicked. 
Examples: 
 html

<html>
<head>
    <script>
        function gfg() {
            document.getElementById("demo").innerHTML =
"Geeks For Geeks";
        }
    </script>
</head>
 
<body>
    <h2>
        JavaScript in Head
    </h2>
    <p id="demo" style="color:green;">
        geeksforgeeks.
    </p>
    <button type="button" >         click it
    </button>
</body>
</html>
Output: 

JavaScript in body: A JavaScript function is placed inside the body


section of an HTML page and the function is invoked when a button
is clicked. Example: 
 html

<html>
<body>
    <h2>
        JavaScript in Body
    </h2>
    <p id="demo">
        geeksforgeeks.
    </p>
    <button type="button" >         Try it
    </button>
    <script>
        function gfg() {
            document.getElementById("demo").innerHTML =
"Geeks For Geeks";
        }
    </script>
</body>
</html>
Output: 

External JavaScript: JavaScript can also be used as external files.


JavaScript files have file extension .js . To use an external script put
the name of the script file in the src attribute of a script tag. External
scripts cannot contain script tags. 
Example:
 Script.js
 Javascript

function gfg () {
    document.getElementById('demo').innerHTML =
'Paragraph Changed'
}
Index.html
 html

<html>
 
<head>

</head>
 
<body>
    <h2>
        External JavaScript
    </h2>
    <p id="demo">
        Geeks For Geeks.
    </p>
    <button type="button" >         Try it
    </button>
    <script src="myScript.js"></script>
</body>
</html>
 Output:

Advantages of External JavaScript:


 Cached JavaScript files can speed up page loading
 It makes JavaScript and HTML easier to read and maintain
 It separates the HTML and JavaScript code
 It focuses on code reusability which is one JavaScript Code
that can run in various HTML files.

JavaScript Statements
The programming instructions written in a program in a programming
language are known as statements. The order of execution of
Statements is the same as they are written.
1. Semicolons:
 Semicolons separate JavaScript statements.
 A semicolon marks the end of a statement in javascript. 
Example: 
 html

<h2>Welcome</h2>
<p id="geek"></p>
<script>
    var a, b, c;
    a = 2;
    b = 3;
    c = a + b;
    document.getElementById("geek")
              .innerHTML =
              "The value of c is " + c + ".";
</script>
 Output:

 
Multiple statements on one line are allowed if they are

separated with a semicolon.
a=2;b=3;z=a+b;
2. Code Blocks: JavaScript statements can be grouped together inside
curly brackets. Such groups are known as code blocks. The purpose
of grouping is to define statements to be executed together. 
Example: JavaScript function 
 html

<p>Welcome</p>
<button type="button"
         >     Click Me!
</button>
<p id="geek1"></p>
<p id="geek2"></p>
<script>
    function myFunction() {
        document.getElementById("geek1")
                  .innerHTML = "Hello";
        document.getElementById("geek2")
                  .innerHTML ="How are you?";
    }
</script>
Output:

3. White Space:
 Javascript ignores multiple white spaces.
4. Line Length and Line Breaks: Javascript code preferred line
length by most programmers is up to 80 characters. The best place
to break a code line in Javascript, if it doesn’t fit, is after an
operator. 
Example:
document.getElementById("geek1").innerHTML =
"Hello Geek!";
5. Keywords: Keywords are reserved words and cannot be used as
variable name. A Javascript keyword tells about what kind of
operation it will perform. 
Some commonly used keywords are:
 break and continue: break keyword is used to terminate a
loop and continue is used to skip a particular iteration in a
loop and move to next iteration.
 do…. while: In this the statements written within do block
are executed till the condition in while is true.
 for: It helps in executing a block of statements till the
condition is true.
 function: This keyword is used to declare a function.
 return: This keyword is used to exit a function.
 switch: This helps in executing a block of codes depending
on different cases.
 var, let  and const : These keywords are used to declare a
variable in js. 

JavaScript Comment
1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments

The JavaScript comments are meaningful way to deliver message. It is used to add


information about the code, warnings or suggestions so that end user can easily
interpret the code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the
browser.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.


1. To make code easy to understand It can be used to elaborate the code so that end
user can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being
executed. Sometimes, we add the code to perform some action. But after sometime,
there may be need to disable the code. In such case, it is better to use comments.

Types of JavaScript Comments


There are two types of comments in JavaScript.

1. Single-line Comment
2. Multi-line Comment

JavaScript Single line Comment


It is represented by double forward slashes (//). It can be used before and after the
statement.

Let’s see the example of single-line comment i.e. added before the statement.

1. <script>  
2. // It is single line comment  
3. document.write("hello javascript");  
4. </script>  

Let’s see the example of single-line comment i.e. added after the statement.

1. <script>  
2. var a=10;  
3. var b=20;  
4. var c=a+b;//It adds values of a and b variable  
5. document.write(c);//prints sum of 10 and 20  
6. </script>  

JavaScript Multi line Comment


It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash. For
example:

1. /* your code here  */  

It can be used before, after and middle of the statement.

1. <script>  
2. /* It is multi line comment.  
3. It will not be displayed */  
4. document.write("example of javascript multiline comment");  
5. </script>  

JavaScript - Variables

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.
JavaScript allows you to work with three primitive data types −
 Numbers, eg. 123, 120.50 etc.
 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only
a single value. In addition to these primitive data types,
JavaScript supports a composite data type known as object. We will cover objects in detail in
a separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-point
values. All numbers in JavaScript are represented as floating-point values. JavaScript
represents numbers using the 64-bit floating-point format defined by the IEEE 7
54 standard.

Declare a Variable
In JavaScript, a variable can be declared
using var, let, const keywords.

 var keyword is used to declare variables since JavaScript was


created. It is confusing and error-prone when using variables
declared using var.
 let keyword removes the confusion and error of var. It is the
new and recommended way of declaring variables in
JavaScript.
 const keyword is used to declare a constant variable that
cannot be changed once assigned a value.

Here, we will use the let keyword to declare variables. To declare a


variable, write the keyword let followed by the name of the
variable you want to give, as shown below.

Example: Variable Declaration

let msg; // declaring a variable without assigning a


value

In the above example, var msg; is a variable declaration. It does not


have any value yet. The default value of variables that do not have
any value is undefined.

You can assign a value to a variable using the = operator when you


declare it or after the declaration and before accessing it.

Example: Variable Initialization

let msg;
msg = "Hello JavaScript!"; // assigning a string value

In the above example, the msg variable is declared first and then


assigned a string value in the next line. mming project ideas for your portfolio | Web
Development Project Ideas

You can declare a variable and assign a value to it in the same


line. Values can be of any datatype such
as string, numeric , boolean, etc.
Example: Variable Declaration and Initialization

let name = "Steve"; //assigned string value


let num = 100; //assigned numeric value
let isActive = true; //assigned boolean value

Multiple variables can be declared in a single line, as shown below.

Example: Multiple Variables

let name = "Steve", num = 100, isActive = true;

You can copy the value of one variable to another variable, as


shown below.

Example: Copy Variable

let num1 = 100;


let num2 = num1;

JavaScript allows multiple white spaces and line breaks when you
declare a variables.

Example: Whitespace and Line Breaks

let name = "Steve",


num = 100,
isActive = true;

Variable names are case-sensitive in JavaScript. You cannot


declare a duplicate variable using the let keyword with the same
name and case. JavaScript will throw a syntax error. Although,
variables can have the same name if declared with the var keyword
(this is why it is recommended to use let).

Example: Syntax Error

let num = 100;


let num = 200; //syntax error

var num = 100;


var num = 200; //Ok
JavaScript Variable Nameing Conventions
 Variable names are case-sensitive in JavaScript. So, the
variable names msg, MSG, Msg, mSg are considered separate
variables.
 Variable names can contain letters, digits, or the symbols $
and _.
 A variable name cannot start with a digit 0-9.
 A variable name cannot be a reserved keyword in JavaScript,
e.g. var, function, return cannot be variable names.

Dynamic Typing
JavaScript is a loosely typed language. It means that you don't
need to specify what data type a variable will contain. You can
update the value of any type after initialization. It is also called
dynamic typing.

Example: Loosely Typed Variable

let myvariable = 1; // numeric value

myvariable = 'one'; // string value

myvariable = 1.1; // decimal value

myvariable = true; // Boolean value

myvariable = null; // null value


Constant Variables in JavaScript
Use const keyword to declare a constant variable in JavaScript.

 Constant variables must be declared and initialized at the


same time.
 The value of the constant variables can't be changed after
initialized them.

Example: Constant Variables


const num = 100;
num = 200; //error

const name; //error


name = "Steve";

The value of a constant variable cannot be changed but the


content of the value can be changed. For example, if an object is
assigned to a const variable then the underlying value of an object
can be changed.

Example: Constant Variables

const person = { name: 'Steve'};


person.name = "Bill";
alert(person.name); //Bill

It is best practice to give constant variable names in capital letters


to separate them from other non-constant variables.

Variable Scope
In JavaScript, a variable can be declared either in the global scope
or the local scope.

Global Variables
Variables declared out of any function are called global variables.
They can be accessed anywhere in the JavaScript code, even
inside any function.

Local Variables
Variables declared inside the function are called local variables of
that function. They can only be accessed in the function where
they are declared but not outside.

The following example includes global and local variables.

Example: Global and Local Variable

let greet = "Hello " // global variable


function myfunction(){
let msg = "JavaScript!";
alert(greet + msg); //can access global and local
variable
}

myfunction();
alert(greet);//can access global variable
alert(msg); //error: can't access local variable

Declare Variables without var and let


Keywords
Variables can be declared and initialized without
the var or let keywords. However, a value must be assigned to a
variable declared without the var keyword.

The variables declared without the var keyword become global


variables, irrespective of where they are declared.

It is Recommended to declare variable using the let keyword.

Example: Variable Declaration Without var or let Keyword

function myfunction(){
msg = "Hello JavaScript!";
}

myfunction();
alert(msg); // msg becomes global variable so can be
accessed here
 Points to Remember

1. Variables can be defined using let keyword. Variables defined


without let or var keyword become global variables.
2. Variables should be initialized before accessing it. Unassigned
variable has value undefined.
3. JavaScript is a loosely-typed language, so a variable can store
any type value.
4. Variables can have local or global scope. Local variables
cannot be accessed out of the function where they are
declared,
5. whereas the global variables can be accessed from anywhere.

Scope in JavaScript
Scope in JavaScript defines accessibility of variables, objects and
functions.

There are two types of scope in JavaScript.

1. Global scope
2. Local scope

Global Scope
Variables declared outside of any function become global variables.
Global variables can be accessed and modified from any function.

Example: Global Variable


<script>

var userName = "Bill";

function modifyUserName() {
userName = "Steve";
};

function showUserName() {
alert(userName);
};

alert(userName); // display Bill

modifyUserName();
showUserName();// display Steve

</script>
In the above example, the variable userName becomes a global
variable because it is declared outside of any function. A
modifyUserName() function modifies userName as userName is a
global variable and can be accessed inside any function. The same
way, showUserName() function displays current value of userName
variable. Changing value of global variable in any function will
reflect throughout the program.

Please note that variables declared inside a function


without var keyword also become global variables.

Example: Global Variable


<script>

function createUserName() {
userName = "Bill";
}

function modifyUserName() {
if(userName)
userName = "Steve";
};

function showUserName() {
alert(userName);
}

createUserName();
showUserName(); // Bill

modifyUserName();
showUserName(); // Steve

</script>

In the above example, variable userName is declared


without var keyword inside createUserName(), so it becomes
global variable automatically after calling createUserName() for
the first time.

 Note:
A userName variable will become global variable only after
createUserName() is called at least once. Calling
showUserName() before createUserName() will throw an
exception "userName is not defined".

Local Scope
Variables declared inside any function with var keyword are called
local variables. Local variables cannot be accessed or modified
outside the function declaration.

Example: Local Scope


<script>

function createUserName() {
var userName = "Bill";
}

function showUserName() {
alert(userName);
}

createUserName();
showUserName(); // throws error: userName is not defined

</script>

Function parameters are considered as local variables.

In the above example, userName is local to createUserName()


function. It cannot be accessed in showUserName() function or
any other functions. It will throw an error if you try to access a
variable which is not in the local or global scope. Use try catch
block for exception handling.

Some tips..

If local variable and global variable have same name then


changing value of one variable does not affect on the value of
another variable.

Example: Scope
var userName = "Bill";

function ShowUserName()
{
var userName = "Steve";

alert(userName); // "Steve"
}

ShowUserName();

alert(userName); // Bill

JavaScript does not allow block level scope inside { }. For


example, variables defined in if block can be accessed outside if
block, inside a function.

Example: No Block Level Scope


Function NoBlockLevelScope(){

if (1 > 0)
{
var myVar = 22;

alert(myVar);
}

NoBlockLevelScope();
 Points to Remember :

1. JavaScript has global scope and local scope.


2. Variables declared and initialized outside any function become
global variables.
3. Variables declared and initialized inside function becomes
local variables to that function.
4. Variables declared without var keyword inside any function
becomes global variables automatically.
5. Global variables can be accessed and modified anywhere in
the program.
6. Local variables cannot be accessed outside the function
declaration.
7. Global variable and local variable can have same name
without affecting each other.
8. JavaScript does not allow block level scope inside { }
brackets.

JavaScript Reserved Words


A list of all the reserved words in JavaScript are given in the following table. They cannot be
used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract else instanceof switch

boolean enum int synchronized

break export interface this

byte extends long throw

case false native throws

catch final new transient

char finally null true

class float package try

const for private typeof

continue function protected var

debugger goto public void

default if return volatile

delete implements short while

do import static with


double in super

JavaScript Message Boxes: alert(),


confirm(), prompt()
JavaScript provides built-in global functions to display popup
message boxes for different purposes.

 alert(message): Display a popup box with the specified


message with the OK button.
 confirm(message): Display a popup box with the specified
message with OK and Cancel buttons.
 prompt(message, defaultValue): Display a popup box to take
the user's input with the OK and Cancel buttons.

 Note:
In JavaScript, global functions can be accessed using
the window object
like window.alert(), window.confirm(), window.prompt().
5.3M

59

2/4 Angular NgRx effects | Real life implementation and how to figure it out yourself

alert()
The alert() function displays a message to the user to display some
information to users. This alert box will have the OK button to
close the alert box.

Syntax:
window.alert([message]);

The alert() function takes a paramter of any type e.g., string,


number, boolean etc. So, no need to convert a non-string type to
a string type.
Example: alert()
alert("This is an alert message box."); // display string message

alert('This is a numer: ' + 100); // display result of a


concatenation

alert(100); // display number

alert(Date()); // display current date

confirm()
Use the confirm() function to take the user's confirmation before
starting some task. For example, you want to take the user's
confirmation before saving, updating or deleting data.

Syntax:
bool window.confirm([message]);

The confirm() function displays a popup message to the user with


two buttons, OK and Cancel. The confirm() function returns true if a
user has clicked on the OK button or returns false if clicked on
the Cancel button. You can use the return value to process further.

The following takes user's confirmation before saving data:

Example: confirm()
var userPreference;

if (confirm("Do you want to save changes?") == true) {


userPreference = "Data saved successfully!";
} else {
userPreference = "Save Cancelled!";
}

prompt()
Use the prompt() function to take the user's input to do further
actions. For example, use the prompt() function in the scenario
where you want to calculate EMI based on the user's preferred
loan tenure.

Syntax:
string prompt([message], [defaultValue]);
The prompt() function takes two parameters. The first parameter is
the message to be displayed, and the second parameter is the
default value in an input box.

Example: Take User's Input using prompt()


var name = prompt("Enter your name:", "John");

if (name == null || name == "") {


document.getElementById("msg").innerHTML = "You did not entert
anything. Please enter your name again";
}
else
{
document.getElementById("msg").innerHTML = "You enterted: " +
name;
}

Javascript Operators
JavaScript includes operators same as other languages. An
operator performs some operation on single or multiple operands
(data value) and produces a result. For example, in 1 + 2,
the + sign is an operator and 1 is left side operand and 2 is right
side operand. The + operator performs the addition of two numeric
values and returns a result.

JavaScript includes following categories of operators.

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Ternary Operator

Arithmetic Operators
Arithmetic operators are used to perform mathematical operations
between numeric operands.
Operator Description

+ Adds two numeric operands.

- Subtract right operand from left operand

* Multiply two numeric operands.

/ Divide left operand by right operand.

% Modulus operator. Returns remainder of two operands.

++ Increment operator. Increase operand value by one.

-- Decrement operator. Decrease value by one.

The following example demonstrates how arithmetic operators


perform different tasks on operands.

Example: Arithmetic Operation


let x = 5, y = 10;

let z = x + y; //performs addition and returns 15

z = y - x; //performs subtraction and returns 5

z = x * y; //performs multiplication and returns 50

z = y / x; //performs division and returns 2

z = x % 2; //returns division remainder 1

The ++ and -- operators are unary operators. It works with either


left or right operand only. When used with the left operand,
e.g., x++, it will increase the value of x when the program control
goes to the next statement. In the same way, when it is used with
the right operand, e.g., ++x, it will increase the value of x there
only. Therefore, x++ is called post-increment, and ++x is called pre-
increment.

Example: Post and Pre Increment/Decrement


let x = 5;

x++; //post-increment, x will be 5 here and 6 in the next line

++x; //pre-increment, x will be 7 here


x--; //post-decrement, x will be 7 here and 6 in the next line

--x; //pre-decrement, x will be 5 here

String Concatenation
The + operator performs concatenation operation when one of the
operands is of string type. The following example demonstrates
string concatenation even if one of the operands is a string.

Example: + Operator with String


let a = 5, b = "Hello ", c = "World!", d = 10;

a + b; //returns "5Hello "

b + c; //returns "Hello World!"

a + d; //returns 15

b + true; //returns "Hello true"

c - b; //returns NaN; - operator can only used with numbers

Comparison Operators
JavaScript provides comparison operators that compare two
operands and return a boolean value true or false.

Operators Description

== Compares the equality of two operands without considering type.

=== Compares equality of two operands with type.

!= Compares inequality of two operands.

> Returns a boolean value true if the left-side value is greater than the right-side value; otherwise, returns false.

< Returns a boolean value true if the left-side value is less than the right-side value; otherwise, returns false.

>= Returns a boolean value true if the left-side value is greater than or equal to the right-side value; otherwise, ret

<= Returns a boolean value true if the left-side value is less than or equal to the right-side value; otherwise, return

The following example demonstrates the comparison operators.

Example: JavaScript Comparison Operators


let a = 5, b = 10, c = "5";
let x = a;

a == c; // returns true

a === c; // returns false

a == x; // returns true

a != b; // returns true

a > b; // returns false

a < b; // returns true

a >= b; // returns false

a <= b; // returns true

Logical Operators
In JavaScript, the logical operators are used to combine two or
more conditions. JavaScript provides the following logical
operators.

Operator Description

&& && is known as AND operator. It checks whether two operands are non-zero or not (0, false, undefined, null or ""
zero). It returns 1 if they are non-zero; otherwise, returns 0.

|| || is known as OR operator. It checks whether any one of the two operands is non-zero or not (0, false, undefined
considered as zero). It returns 1 if any one of of them is non-zero; otherwise, returns 0.

! ! is known as NOT operator. It reverses the boolean result of the operand (or condition). !false returns true
true returns false.

Example: Logical Operators


let a = 5, b = 10;

(a != b) && (a < b); // returns true

(a > b) || (a == b); // returns false

(a < b) || (a == b); // returns true

!(a < b); // returns false

!(a > b); // returns true


Assignment Operators
JavaScript provides the assignment operators to assign values to
variables with less key strokes.

Assignment
operators Description

= Assigns right operand value to the left operand.

+= Sums up left and right operand values and assigns the result to the left opera

-= Subtract right operand value from the left operand value and assigns the
operand.

*= Multiply left and right operand values and assigns the result to the left opera

/= Divide left operand value by right operand value and assign the result to the

%= Get the modulus of left operand divide by right operand and assign resulte
left operand.

Example: Assignment operators


let x = 5, y = 10, z = 15;

x = y; //x would be 10

x += 1; //x would be 6

x -= 1; //x would be 4

x *= 5; //x would be 25

x /= 5; //x would be 1

x %= 2; //x would be 1

Ternary Operator
JavaScript provides a special operator called ternary
operator :? that assigns a value to a variable based on some
condition. This is the short form of the if else condition.

Syntax:
<condition> ? <value1> : <value2>;
The ternary operator starts with conditional expression followed by
the ? operator. The second part (after ? and before :) will be
executed if the condition turns out to be true. Suppose, the
condition returns false, then the third part (after :) will be
executed.

Example: Ternary operator


let a = 10, b = 5;

let c = a > b? a : b; // value of c would be 10


let d = a > b? b : a; // value of d would be 5

 Points to Remember:

1. JavaScript includes operators that perform some operation on


single or multiple operands (data value) and produce a result.
2. JavaScript includes various categories of operators:
Arithmetic operators, Comparison operators, Logical
operators, Assignment operators, Conditional operators.
3. Ternary operator ?: is a short form of if-else condition.

JavaScript Data Types


In JavaScript, you can assign different types of values (data) to a
variable e.g. string, number, boolean, etc.

Example: A Variable with Different Types of Data


let myvariable = 1; // numeric value

myvariable = 'one'; // string value

myvariable = true; // Boolean value

In the above example, different types of values are assigned to


the same variable to demonstrate the loosely typed characteristics
of JavaScript. Here, 1 is the number type, 'one' is the string type,
and true is the boolean type.

JavaScript includes primitive and non-primitive data types as per


the latest ECMAScript 5.1 specification .
Primitive Data Types
The primitive data types are the lowest level of the data value in
JavaScript. The followings are primitive data types in JavaScript:

Data Type Description

String String is a textual content wrapped inside ' ' or " " or ` ` (tick sign).

Example: 'Hello World!', "This is a string", etc.

Number Number is a numeric value.

Example: 100, 4521983, etc.

BigInt BigInt is a numeric value in the arbitrary precision format.

Example: 453889879865131n, 200n, etc.

Boolean Boolean is a logical data type that has only two values, true or false.

Null A null value denotes an absense of value.

Example: let str = null;

Undefined undefined is the default value of a variable that has not been assigned any value.

Example: In the variable declaration, var str;, there is no value assigned to str. So, the ty
check using typeof(str) which will return undefined.
Structural Data Types
The structural data types contain some kind of structure with
primitive data.

Data Type Description

Object An object holds multiple values in terms of properties and methods.

Example:

let person = {
firstName: "James",
lastName: "Bond",
age: 15
};

Date The Date object represents date & time including days, months, years, hours, minutes, s
Data Type Description

milliseconds.

Example: let today = new Date("25 July 2021");

Array An array stores multiple values using special syntax.

Example: let nums = [1, 2, 3, 4];

JavaScript Strings
In JavaScript, a string is a primitive data type that is used for
textual data. JavaScript string must be enclosed in single quotes,
double quotes, or backticks. The followings are string literals in
JavaScript.

Example: String literals

"Hello World"

'Hello World'

`Hello World`

The string literal can be assigned to a variable using the equal


to = operator.

Example: String Variables

let str1 = "This is a double quoted string.";

let str2 = 'This is a single quoted string.';

let str3 = `This is a template string.`;

The template string (using backticks) is used when you want to


include the value of a variable or expressions into a string. Use $
{variable or expression}  inside backticks as shown below.

Example: Template String

let amount = 1000, rate = 0.05, duration = 3;


let result = `Total Amount Payble: ${amount*(1 +
rate*duration)}`;

The template string can be spanned in multiple lines which is not


allowed with a single or double quoted string, as shown below.

Example: Template String

let str1 = `This


is
multi-line
string`;

/*let str2 = "This


will
give
error"; */

JavaScript string can be treated like a character array. You can


access a character in a string using square brackets [index] or using
the str.at(pos) method.

Example: String as array

let str = 'Hello World';

let ch1 = str[0] // H


let ch2 = str[1] // e
let ch3 = str.at(2) // l
let ch4 = str.at(3) // l

str[4] = "P"; //error

JavaScript strings can be accessed using a for loop, as shown


below.

Example: Use for Loops

let str = 'Hello World';

for(let i =0; i< str.length; i++)


console.log(str[i]);
for(let ch of str)
console.log(ch);
Quotes Inside String
You can include single quotes in double-quoted string or include
double quotes in a single quoted string. However, you cannot
include a single quotes in single quoted string and double quotes
in double-quoted string.

Example: Quotes in string

let str1 = "This is 'simple' string";

let str2 = 'This is "simple" string';

let str3 = `This is 'simple' and "easy" string`;

If you want to include the same quotes in a string value as


surrounding quotes then use a backward slash (\) before the
quotation mark inside the string value.

Example: Quotes in string

let str1 = "This is \"simple\" string";

let str2 = 'This is \'simple\' string';


String Concatenation
JavaScript string can be concatenated using the + operator
or string.concat() method.

Example: String concatenation

let str1 = 'Hello ';


let str2 = "World ";

let str3 = str1 + str2; //Hello World


let str4 = str1.concat(str2);//Hello World
String Objects
JavaScript allows you to create a string object using
the new keyword, as shown below.

Example: String object

let str1 = new String(); //create string object


str1 = 'Hello World'; //assign value

// or

let str2 = new String('Hello World'); //create and


assign value

String objects and string literals are different. The typeof() method


will return the type of a variable. The following distinguished string
and string objects.

Example: String object

let str1 = new String('Hello World');


let str2 = "Hello World";

typeof(str1); //"object"
typeof(str2); //"string"
Strings Comparison
Two strings can be compared using <, >, ==, === operator,
and string.localeCompare(string) method.

The mathematical operators < and > compare two strings and


return a boolean (true or false) based on the order of the
characters in the string.

The == operator compares the content of strings and === compares


the reference equality of strings. The localeCompare() method
compares two strings in the current locale. It returns 0 if strings
are equal, else returns 1.

Example: String Comparison


console.log("a" < "b"); //true
console.log("b" < "a"); //false
console.log("Apple" == "Apple"); //true
console.log("Apple" == "apple"); //false
console.log("Apple" === "Apple"); //true
console.log("Apple" === "apple"); //false
console.log("Apple".localeCompare("Apple")); //0
console.log("Apple".localeCompare("apple")); //1

Note that the === operator compares the reference of strings


objects and not the values.

Example: String Object Comparison

let str1 = "Hello";


let str2 = 'Hello';
let str3 = new String('Hello');

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


console.log(str1 === str2);//true
console.log(str1 == str3); //true
console.log(str1 === str3);//false
JavaScript String Methods & Properties
JavaScript string (primitive or String object) includes default
properties and methods which you can use for different purposes.

String Properties
Property Description

length Returns the length of the string.

String Methods
Method Description

charAt(position) Returns the character at the specified position (in Number).

charCodeAt(position) Returns a number indicating the Unicode value of the character at the given position (in

concat([string,,]) Joins specified string literal values (specify multiple strings separated by comma) and retu

indexOf(SearchString, Position) Returns the index of first occurrence of specified String starting from specified number in
Method Description

found.

lastIndexOf(SearchString, Returns the last occurrence index of specified SearchString, starting from specified positi
Position) found.

localeCompare(string,position) Compares two strings in the current locale.

match(RegExp) Search a string for a match using specified regular expression. Returns a matching array.

replace(searchValue, Search specified string value and replace with specified replace Value string and return n
replaceValue) expression can also be used as searchValue.

search(RegExp) Search for a match based on specified regular expression.

slice(startNumber, endNumber) Extracts a section of a string based on specified starting and ending index and returns a n

split(separatorString, Splits a String into an array of strings by separating the string into substrings based on sp
limitNumber) Regular expression can also be used as separator.

substr(start, length) Returns the characters in a string from specified starting position through the specified n
(length).

substring(start, end) Returns the characters in a string between start and end indexes.

toLocaleLowerCase() Converts a string to lower case according to current locale.

toLocaleUpperCase() Converts a sting to upper case according to current locale.

toLowerCase() Returns lower case string value.

toString() Returns the value of String object.

toUpperCase() Returns upper case string value.

valueOf() Returns the primitive value of the specified string object.

String Methods for Html


The following string methods convert the string as a HTML wrapper
element.

Method Description

anchor() Creates an HTML anchor <a>element around string value.

big() Wraps string in <big> element.

blink() Wraps a string in <blink> tag.

bold() Wraps string in <b> tag to make it bold in HTML.

fixed() Wraps a string in <tt> tag.


Method Description

fontcolor() Wraps a string in a <font color="color"> tag.

fontsize() Wraps a string in a <font size="size"> tag.

italics() Wraps a string in <i> tag.

link() Wraps a string in <a>tag where href attribute value is set to specified string.

small() Wraps a string in a <small>tag.

strike() Wraps a string in a <strike> tag.

sub() Wraps a string in a <sub>tag

sup() Wraps a string in a <sup>tag

JavaScript Numbers: Integer, Float,


Binary, Exponential, Hexadecimal, Octal
The Number is a primitive data type used for positive or negative
integer, float, binary, octal, hexadecimal, and exponential values in
JavaScript.

The Number type in JavaScript is double-precision 64 bit binary format


like double in C# and Java. It follows the international IEEE
754 standard.

The first character in a number type must be an integer value, and it


must not be enclosed in quotation marks. The following example shows
the variables having different types of numbers in JavaScript.

Example: Numbers in JavaScript


var num1 = 100; // integer
var num2 = -100; //negative integer

var num3 = 10.52; // float


var num4 = -10.52; //negative float

var num5 = 0xfff; // hexadecimal


var num6 = 256e-5; // exponential
var num7 = 030; // octal
var num8 = 0b0010001; // binary
Integers

Numbers can be positive or negative integers. However, integers are


floating-point values in JavaScript. Integers value will be accurate up to
15 digits in JavaScript. Integers with 16 digits onwards will be changed
and rounded up or down; therefore, use BigInt for integers larger than
15 digits.

Example: Integers in JavaScript


//16 digit integer
var int1 = 1234567890123456; //accurate

//17 digit integer


var int2 = 12345678901234569; //will be 12345678901234568

//16 digit integer


var int3 = 9999999999999998; //will be 9999999999999998

//16 digit integer, last digit 9


var int4 = 9999999999999999; //will be 10000000000000000
BigInt

The BigInt type is a numeric primitive type that can store integers with
arbitrary precision. Use the BigInt for the large integers having more
than 15 digits. Append n to the end of an integer to make it BigInt.

Example: Integers in JavaScript


//16 digit integer
var int1 = 1234567890123459n; //will be 1234567890123459

//17 digit integer


var int2 = 12345678901234569n; //will be 12345678901234569

//20 digit integer


var int3 = 9999999999999999999n; //will be 9999999999999999999

Floating-point Numbers

The floating-point numbers in JavaScript can only keep 17 decimal


places of precision; beyond that, the value will be changed.

Example: Floating-point Numbers in JavaScript


//17 decimal places
var f1 = 123456789012345.9; //accurate

//18 decimal places


var f2 = 1234567890123456.9; //will be 1234567890123457

//19 decimal places


var f3 = 1234567890123456.79; //will be 1234567890123456.8

Arithmetic operations on floating-point numbers in JavaScript are not


always accurate. For example:

Example: Arithmetic Operations on Floating-point Numbers


var f1 = 5.1 + 5.2; //will be 10.3

var f2 = 10.1 + 10.2; //will be 20.299999999999997

var f3 = (10.1*100 + 10.2*100)/100; //instead of 10.1 + 10.2

Arithmetic operation (except addition) of the numeric string will result in


a number, as shown below.

Example: Arithmetic Operation of Numeric Strings


var numStr1 = "5", numStr2 = "4";

var multiplication = numStr1 * numStr2; //returns20


var division = numStr1 / numStr2; //returns 1.25
var modulus = numStr1 % numStr2; //returns 1

Even if one of the values is a number, the result would be the same.

Example: Arithmetic Operation on Number and String


var num = 5, str = "4";

var multiplication = num * str; //returns 20


var division = num / str; //returns 1.25
var modulus = num % str; //returns 1

The + operator concatenates if any one value is a literal string.

Example: Arithmetic Operation on Number and String


var num = 5, str = "4";

var result = num + str; //returns "54"


Binary, Octal, Hexadecimal, Exponential

The binary numbers must start with 0b or 0B followed by 0 or 1.

The octal numbers must start with zero and the lower or upper letter
'O', 0o or 0O.

The Hexadecimal numbers must start with zero and the lower or upper
letter 'X', 0x or 0X.

The exponential numbers should follow the beN format where b is a base


integer or float number followed by e char, and N is an exponential
power number.

Example: Binary, Ocal, Hexadecimal, Exponential Numbers


var b = 0b100; // binary
var oct = 0o544; // octal
var hex = 0x123456789ABCDEF; // hexadecimal
var exp = 256e-5; // exponential

Number() Function in JavaScript

The Number() is a constructor function in JavaScript that converts values


of other types to numbers.

Example: Number() Function


var i = Number('100');
var f = Number('10.5');
var b = Number('0b100');
typeof(i); // returns number
typeof(f); // returns number
typeof(b); // returns number

By using the new operator  with the Number() function will return an


object which contains constants and methods for working with numbers.

Example: Number Object


var i = new Number('100');
var f = new Number('10.5');
var b = new Number('0b100');
typeof(i); // returns object
typeof(f); // returns object
typeof(b); // returns object
Compare Numbers

Be careful while comparing numbers using == or === operators.


The == operator compares object references and not the values whereas
the === operator compare values. The following example compares
numbers created by different ways.

Example: Numbers Comparison


var num1 = new Number(100);
var num2 = Number('100');
var num3 = 100;

num1 == num2; // true


num1 === num2; // false

num2 == num3;//true
num2 === num3; // true

num1 == num3;//true
num1 === num3;//false
Number Properties

The Number type includes some default properties. JavaScript treats


primitive values as objects, so all the properties and methods are
applicable to both literal numbers and number objects.

The following table lists all the properties of Number type.

Property Description

MAX_VALUE Returns the maximum number value supported in JavaScript

MIN_VALUE Returns the smallest number value supported in JavaScript

NEGATIVE_INFINITY Returns negative infinity (-Infinity)

NaN Represents a value that is not a number.

POSITIVE_INFINITY Represents positive infinity (Infinity).

Example: Number properties


Number.MAX_VALUE; //1.7976931348623157e+308
Number.MIN_VALUE; //5e-324
Number.NEGATIVE_INFINITY; //-Infinity
Number.POSITIVE_INFINITY; //Infinity
Number.NaN;//NaN
Number Methods
The following table lists all the methods of Number type

Method Description

toExponential(fractionDigits) Returns exponential value as a string.

Example:
var num = 100; num.toExponential(2); //
returns '1.00e+2'

toFixed(fractionDigits) Returns string of decimal value of a number based on specified fractionDigits.

Example:
var num = 100; num.toFixed(2); // returns '100.00'

toLocaleString() Returns a number as a string value according to a browser's locale settings.

Example:
var num = 100; num.toLocaleString(); // returns '100'

toPrecision(precisionNumber) Returns number as a string with specified total digits.

Example:
var num = 100; num.toPrecision(4); // returns '100.0'

toString() Returns the string representation of the number value.

Example:
var num = 100; num.toString(); // returns '100'

valueOf() Returns the value of Number object.

Example: var num = new Number(100); num.valueOf(); //

returns '100'

JavaScript Booleans
The boolean (not Boolean) is a primitive data type in JavaScript. It
can have only two values: true or false. It is useful in controlling
program flow using conditional statements like if
else, switch, while loop, etc.
The followings are boolean variables.

Example: boolean Variables


var YES = true;

var NO = false;

The following example demonstrates how a boolean value controls


the program flow using the if condition.

Example: Boolean
var YES = true;
var NO = false;

if(YES)
{
alert("This code block will be executed");
}

if(NO)
{
alert("This code block will not be executed");
}

The comparison expressions return boolean values to indicate


whether the comparison is true or false. For example, the following
expressions return boolean values.

Example: boolean Expressions


var a = 10, b = 20;

var result = 1 > 2; // false

result = a < b; // true

result = a > b; // false

result = a + 20 > b + 5; // true

Boolean Function
JavaScript provides the Boolean() function that converts other types
to a boolean type. The value specified as the first parameter will
be converted to a boolean value. The Boolean() will return true for
any non-empty, non-zero, object, or array.

Example: Boolean() Function


var a = 10, b = 20;

var b1 = Boolean('Hello'); // true

var b2 = Boolean('h'); // true

var b3 = Boolean(10); // true

var b4 = Boolean([]); // true

var b5 = Boolean(a + b); // true

If the first parameter is 0, -0, null, false, NaN, undefined, '' (empty
string), or no parameter passed then the Boolean() function
returns false.

Example: Boolean() Function


var b1 = Boolean(''); // false

var b2 = Boolean(0); // false

var b3 = Boolean(null); // false

var a;
var b4 = Boolean(a); // false

Using Boolean constructor:

The new operator  with the Boolean() function returns a Boolean object.

Example: Boolean Object


var bool = new Boolean(true);

alert(bool); // true

Any boolean object, when passed in a conditional statement, will


evaluate to true.

Example: Boolean Object in Condition


var bool = new Boolean(false);
if(bool){
alert('This will be executed.');
}

Boolean vs boolean
The new Boolean() will return a Boolean object, whereas it returns a
boolean without the new keyword. The boolean (lower case) is the
primitive type, whereas Boolean (upper case) is an object in
JavaScript. Use the typeof operator to check the types.

Example: Boolean vs boolean


var b1 = new Boolean(true);
var b2 = true;

typeof b1; // object


typeof b2; // boolean

Boolean Methods
Primitive or Boolean object includes following methods.

Method Description

toLocaleString( Returns string of boolean value in local browser environment.


)
Example: var result = (1 > 2); result.toLocaleString(); // returns "false"

toString() Returns a string of Boolean.

Example: var result = (1 > 2); result.toString(); // returns "false"

valueOf() Returns the value of the Boolean object.

Example: var result = (1 > 2); result.valueOf(); // returns false


JavaScript Objects: Create Objects,
Access Properties & Methods
Here you will learn objects, object literals, Object() constructor
function, and access object in JavaScript.

You learned about primitive and structured data types in


JavaScript. An object is a non-primitive, structured data type in
JavaScript. Objects are same as variables in JavaScript, the only
difference is that an object holds multiple values in terms of
properties and methods.

In JavaScript, an object can be created in two ways: 1) using


Object Literal/Initializer Syntax 2) using the Object() Constructor
function with the new keyword. Objects created using any of these
methods are the same.

The following example demonstrates creating objects using both


ways.

Example: JavaScript Objects


var p1 = { name:"Steve" }; // object literal syntax

var p2 = new Object(); // Object() constructor function


p2.name = "Steve"; // property

Above, p1 and p2 are the names of objects. Objects can be declared


same as variables using var or let keywords. The p1 object is
created using the object literal syntax (a short form of creating
objects) with a property named name. The p2 object is created by
calling the Object() constructor function with the new keyword.
The p2.name = "Steve"; attach a property name to p2 object with
a string value "Steve".

Create Object using Object Literal Syntax


The object literal is a short form of creating an object. Define an
object in the { } brackets with key:value pairs separated by a
comma. The key would be the name of the property and the value
will be a literal value or a function.
Syntax:
var <object-name> = { key1: value1, key2: value2,...};

The following example demonstrates objects created using object


literal syntax.

Example: Object Literal Syntax


var emptyObject = {}; // object with no properties or methods

var person = { firstName: "John" }; // object with single property

// object with single method


var message = {
showMessage: function (val) {
alert(val);
}
};

// object with properties & method


var person = {
firstName: "James",
lastName: "Bond",
age: 15,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};

Note that the whole key-value pair must be declared. Declaring


only a key without a value is invalid, as shown below.

Example: Wrong Syntax


var person = { firstName };

var person = { getFullName: };

Create Objects using Objects() Constructor


Another way of creating objects is using the Object() constructor
function using the new keyword. Properties and methods can be
declared using the dot notation .property-name or using the square
brackets ["property-name"], as shown below.

Example: Create Object using Object() Constructor


var person = new Object();

// Attach properties and methods to person object


person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};

An object can have variables as properties or can have computed


properties, as shown below.

Example: Variables as Object Properties


var firstName = "James";
var lastName = "Bond";

var person = { firstName, lastName }

Access JavaScript Object Properties &


Methods
An object's properties can be accessed using the dot
notation obj.property-name or the square brackets obj["property-name"].
However, method can be invoked only using the dot notation with
the parenthesis, obj.method-name(), as shown below.

Example: Access JS Object


var person = {
firstName: "James",
lastName: "Bond",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};

person.firstName; // returns James


person.lastName; // returns Bond

person["firstName"];// returns James


person["lastName"];// returns Bond

person.getFullName(); // calling getFullName function


In the above example, the person.firstName access
the firstName property of a person object. The person["firstName"] is
another way of accessing a property. An object's methods can be
called using () operator e.g. person.getFullName(). JavaScript engine
will return the function definition if accessed method without the
parenthesis.

Accessing undeclared properties of an object will return undefined .


If you are not sure whether an object has a particular property or
not, then use the hasOwnProperty() method before accessing them, as
shown below.

Example: hasOwnProperty()
var person = new Object();

person.firstName; // returns undefined

if(person.hasOwnProperty("firstName")){
person.firstName;
}

The properties and methods will be available only to an object


where they are declared.

Example: Object Constructor


var p1 = new Object();
p1.firstName = "James";
p1.lastName = "Bond";

var p2 = new Object();


p2.firstName; // undefined
p2.lastName; // undefined

p3 = p1; // assigns object


p3.firstName; // James
p3.lastName; // Bond
p3.firstName = "Sachin"; // assigns new value
p3.lastName = "Tendulkar"; // assigns new value

Enumerate Object's Properties


Use the for in loop to enumerate an object, as shown below.

Example: Access Object Keys


var person = new Object();
person.firstName = "James";
person.lastName = "Bond";

for(var prop in person){


alert(prop); // access property name
alert(person[prop]); // access property value
};

Pass by Reference
Object in JavaScript passes by reference from one function to
another.

Example: JS Object Passes by Reference


function changeFirstName(per)
{
per.firstName = "Steve";
}

var person = { firstName : "Bill" };

changeFirstName(person)

person.firstName; // returns Steve

Nested Objects
An object can be a property of another object. It is called a nested
object.

Example: Nested JS Objects


var person = {
firstName: "James",
lastName: "Bond",
age: 25,
address: {
id: 1,
country:"UK"
}
};

person.address.country; // returns "UK"


 Points to Remember :
1. JavaScript object is a standalone entity that holds multiple
values in terms of properties and methods.
2. Object property stores a literal value and method represents
function.
3. An object can be created using object literal or object
constructor syntax.
4. Object literal:
5. var person = {
6. firstName: "James",
7. lastName: "Bond",
8. age: 25,
9. getFullName: function () {
10. return this.firstName + ' ' + this.lastName
11. }
12. };

13. Object constructor:


14. var person = new Object();
15.
16. person.firstName = "James";
17. person["lastName"] = "Bond";
18. person.age = 25;
19. person.getFullName = function () {
20. return this.firstName + ' ' + this.lastName;
21. };

22. Object properties and methods can be accessed using


dot notation or [ ] bracket.
23. An object is passed by reference from one function to
another.
24. An object can include another object as a property.

JavaScript Date: Create, Convert,


Compare Dates in JavaScript
JavaScript provides Date object to work with date & time,
including days, months, years, hours, minutes, seconds, and
milliseconds.

Use the Date() function to get the string representation of the


current date and time in JavaScript. Use the new keyword in
JavaScript to get the Date object.

Example: Date In JavaScript

Date(); //Returns current date and time string

//or

var currentDate = new Date(); //returns date object of current date


and time
Try it

Create a date object by specifying different parameters in


the Date() constructor function.

Date() Syntax
new Date()
new Date(value)
new Date(dateString)
new Date(year, monthIndex)
new Date(year, monthIndex, day)
new Date(year, monthIndex, day, hours)
new Date(year, monthIndex, day, hours, minutes)
new Date(year, monthIndex, day, hours, minutes, seconds)
new Date(year, monthIndex, day, hours, minutes, seconds,
milliseconds)
Parameters:
 No Parameters: A date object will be set to the current date &
time if no parameter is specified in the constructor.
 value: An integer value representing the number of
milliseconds since January 1, 1970, 00:00:00 UTC.
 dateString: A string value that will be parsed
using Date.parse() method.
 year: An integer value to represent a year of a date. Numbers
from 0 to 99 map to the years 1900 to 1999. All others are
actual years.
 monthIndex: An integer value to represent a month of a date.
It starts with 0 for January till 11 for December
 day: An integer value to represent day of the month.
 hours: An integer value to represent the hour of a day between
0 to 23.
 minutes: An integer value to represent the minute of a time
segment.
 seconds: An integer value to represent the second of a time
segment.
 milliseconds: An integer value to represent the millisecond of a
time segment. Specify numeric milliseconds in the constructor
to get the date and time elapsed from 1/1/1970.

In the following example, a date object is created by passing


milliseconds in the Date() constructor function. So date will be
calculated based on milliseconds elapsed from 1/1/1970.

Example: Create Date by Specifying Milliseconds


var date1 = new Date(0); // Thu Jan 01 1970 05:30:00

var date2 = new Date(1000); // Thu Jan 01 1970 05:30:01

var date3 = new Date(5000); // Thu Jan 01 1970 05:30:05


Try it

The following example shows various formats of a date string that


can be specified in a Date() constructor.

Example: Create Date by Specifying Date String


var date1 = new Date("3 march 2015");

var date2 = new Date("3 February, 2015");

var date3 = new Date("3rd February, 2015"); // invalid date

var date4 = new Date("2015 3 February");

var date5 = new Date("3 2015 February ");

var date6 = new Date("February 3 2015");

var date7 = new Date("February 2015 3");

var date8 = new Date("2 3 2015");


var date9 = new Date("3 march 2015 20:21:44");
Try it

You can use any valid separator in the date string to differentiate
date segments.

Example: Create Date using Different Date Separator


var date1 = new Date("February 2015-3");

var date2 = new Date("February-2015-3");

var date3 = new Date("February-2015-3");

var date4 = new Date("February,2015-3");

var date5 = new Date("February,2015,3");

var date6 = new Date("February*2015,3");

var date7 = new Date("February$2015$3");

var date8 = new Date("3-2-2015"); // MM-dd-YYYY

var date9 = new Date("3/2/2015"); // MM-dd-YYYY


Try it

Specify seven numeric values to create a date object with the


specified year, month and optionally date, hours, minutes, seconds
and milliseconds.

Example: Date
var date1 = new Date(2021, 2, 3); // Mon Feb 03 2021
var date2 = new Date(2021, 2, 3, 10); // Mon Feb 03 2021 10:00
var date3 = new Date(2021, 2, 3, 10, 30); // Mon Feb 03 2021 10:30
var date4 = new Date(2021, 2, 3, 10, 30, 50); // Mon Feb 03 2021
10:30:50
var date5 = new Date(2021, 2, 3, 10, 30, 50, 800); // Mon Feb 03
2021 10:30:50
Try it

Date Formats
JavaScript supports ISO 8601 date format by default - YYYY-MM-
DDTHH:mm:ss.sssZ
Example: ISO Date Format
var dt = new Date('2015-02-10T10:12:50.5000z');

Convert Date Formats


Use different Date methods to convert a date from one format to
another format, e.g., to Universal Time, GMT, or local time format.

The following example


demonstrates ToUTCString(), ToGMTString(), ToLocalDateString(),
and ToTimeString() methods to convert date into respective formats.

Example: Date Conversion in Different Formats


var date = new Date('2015-02-10T10:12:50.5000z');

date; 'Default format:'

date.toDateString();'Tue Feb 10 2015'

date.toLocaleDateString();'2/10/2015'

date.toGMTString(); 'GMT format'

date.toISOString(); '2015-02-10T10:12:50.500Z'

date.toLocaleString();'Local date Format '

date.toLocaleTimeString(); 'Locale time format '

date.toString('YYYY-MM-dd'); 'Tue Feb 10 2015 15:42:50'

date.toTimeString(); '15:42:50'

date.toUTCString(); 'UTC format '


Try it

To get date string in formats other than the ones listed above, you
need to manually form the date string using different date object
methods. The following example converts a date string to DD-MM-
YYYY format.

Example: Get Date Segments


var date = new Date('4-1-2015'); // M-D-YYYY
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();

var dateString = (d <= 9 ? '0' + d : d) + '-' + (m <= 9 ? '0' + m :


m) + '-' + y;
Try it
 
 Note:
Use third party JavaScript Date library
like datejs.com or momentjs.com to work with Dates
extensively in JavaScript.

Compare Dates in JavaScript


Use comparison operators to compare two date objects.

Example: Date Comparison


var date1 = new Date('4-1-2015');
var date2 = new Date('4-2-2015');

if (date1 > date2)


alert(date1 + ' is greater than ' + date2);
else (date1 < date2 )
alert(date1 + ' is less than ' + date2);

Date Methods Reference


The following table lists all the get methods of Date object.

Method Description
getDate() Returns numeric day (1 - 31) of the specified date.
getDay() Returns the day of the week (0 - 6) for the specified date.
getFullYear() Returns four digit year of the specified date.
getHours() Returns the hour (0 - 23) in the specified date.
getMilliseconds() Returns the milliseconds (0 - 999) in the specified date.
getMinutes() Returns the minutes (0 - 59) in the specified date.
getMonth() Returns the month (0 - 11) in the specified date.
getSeconds() Returns the seconds (0 - 59) in the specified date.
getTime() Returns the milliseconds as number since January 1, 1970, 00:00:00 UTC.
getTimezoneOffset() Returns the time zone offset in minutes for the current locale.
Method Description
getUTCDate() Returns the day (1 - 31) of the month of the specified date as per UTC time
getUTCDay() Returns the day (0 - 6) of the week of the specified date as per UTC timezo
getUTCFullYear() Returns the four digits year of the specified date as per UTC time zone.
getUTCHours() Returns the hours (0 - 23) of the specified date as per UTC time zone.
getUTCMilliseconds() Returns the milliseconds (0 - 999) of the specified date as per UTC time zon
getUTCMinutes() Returns the minutes (0 - 59) of the specified date as per UTC time zone.
getUTCMonth() Returns the month (0 - 11) of the specified date as per UTC time zone.
getUTCSeconds() Returns the seconds (0 - 59) of the specified date as per UTC time zone.
getYear() Returns the no of years of the specified date since 1990. This method is De

The following table lists all the set methods of Date object.

Method Description
setDate() Sets the day as number in the date object.
setFullYear() Sets the four digit full year as number in the date object. Optionally set month and date.
setHours() Sets the hours as number in the date object. Optionally set minutes, seconds and milliseconds.
setMilliseconds() Sets the milliseconds as number in the date object.
setMinutes() Sets the minutes as number in the date object. Optionally set seconds & milliseconds.
setMonth() Sets the month as number in the date object. Optionally set date.
setSeconds() Sets the seconds as number in the date object. Optionally set milliseconds.
setTime() Sets the time as number in the Date object since January 1, 1970, 00:00:00 UTC.
setUTCDate() Sets the day in the date object as per UTC time zone.
setUTCFullYear() Sets the full year in the date object as per UTC time zone
setUTCHours() Sets the hour in the date object as per UTC time zone
setUTCMilliseconds() Sets the milliseconds in the date object as per UTC time zone
setUTCMinutes() Sets the minutes in the date object as per UTC time zone
setUTCMonth() Sets the month in the date object as per UTC time zone
setUTCSeconds() Sets the seconds in the date object as per UTC time zone
setYear() Sets the year in the date object. This method is Deprecated
toDateString() Returns the date segment from the specified date, excludes time.
toGMTString() Returns a date string in GMT time zone.
toLocaleDateString() Returns the date segment of the specified date using the current locale.
toLocaleFormat() Returns a date string in default format.
toLocaleString() Returns a date string using a current locale format.
toLocaleTimeString() Returns the time segment of the specified Date as a string.
toString() Returns a string for the specified Date object.
toTimeString() Returns the time segment as a string from the specified date object.
toUTCString() Returns a string as per UTC time zone.
valueOf() Returns the primitive value of a Date object.

JavaScript Arrays: Create, Access, Add &


Remove Elements
We have learned that a variable can hold only one value. We
cannot assign multiple values to a single variable. JavaScript array
is a special type of variable, which can store multiple values using
a special syntax.

The following declares an array with five numeric values.

let numArr = [10, 20, 30, 40, 50];

In the above array, numArr is the name of an array variable. Multiple


values are assigned to it by separating them using a comma inside
square brackets as [10, 20, 30, 40, 50] . Thus, the numArr variable
stores five numeric values. The numArr array is created using the
literal syntax and it is the preferred way of creating arrays.

Another way of creating arrays is using the Array() constructor, as


shown below.

let numArr = new Array(10, 20, 30, 40, 50);

Every value is associated with a numeric index starting with 0. The


following figure illustrates how an array stores values.

JavaSc
ript Array Representation

The following are some more examples of arrays that store


different types of data.

Example: Array Literal Syntax

let stringArray = ["one", "two", "three"];

let numericArray = [1, 2, 3, 4];


let decimalArray = [1.1, 1.2, 1.3];

let booleanArray = [true, false, false, true];


Try it

It is not required to store the same type of values in an array. It


can store values of different types as well.

let data = [1, "Steve", "DC", true, 255000, 5.5];


Get Size of an Array
Use the length property to get the total number of elements in an
array. It changes as and when you add or remove elements from
the array.

Example: Get Array Size

let cities = ["Mumbai", "New York", "Paris",


"Sydney"];
console.log(cities.length); //4

cities[4] = "Delhi";
console.log(cities.length); //5
Try it

Accessing Array Elements


Array elements (values) can be accessed using an index. Specify
an index in square brackets with the array name to access the
element at a particular index like arrayName[index]. Note that the
index of an array starts from zero.

Example: Accessing Array Elements

let numArr = [10, 20, 30, 40, 50];


console.log(numArr[0]); // 10
console.log(numArr[1]); // 20
console.log(numArr[2]); // 30
console.log(numArr[3]); // 40
console.log(numArr[4]); // 50
let cities = ["Mumbai", "New York", "Paris",
"Sydney"];

console.log(cities[0]); // "Mumbai"
console.log(cities[1]); // "New York"
console.log(cities[2]); // "Paris"
console.log(cities[3]); // "Sydney"

//accessing element from nonexistance index


console.log(cities[4]); // undefined
Try it

For the new browsers, you can use the arr.at(pos) method to get


the element from the specified index. This is the same
as arr[index] except that the at() returns an element from the last
element if the specified index is negative.

Example: Accessing Array using at()

let numArr = [10, 20, 30, 40, 50];


console.log(numArr.at(0)); // 10
console.log(numArr.at(1)); // 20
console.log(numArr.at(2)); // 30
console.log(numArr.at(3)); // 40
console.log(numArr.at(4)); // 50
console.log(numArr.at(5)); // undefined

//passing negative index


console.log(numArr.at(-1)); // 50
console.log(numArr.at(-2)); // 40
console.log(numArr.at(-3)); // 30
console.log(numArr.at(-4)); // 20
console.log(numArr.at(-5)); // 10
console.log(numArr.at(-6)); // undefined
Try it

You can iterate an array using Array.forEach(), for, for-of, and for-in


loop, as shown below.

Example: Accessing Array Elements


let numArr = [10, 20, 30, 40, 50];

numArr.forEach(i => console.log(i)); //prints all


elements

for(let i=0; i<numArr.length; i++)


console.log(numArr[i]);

for(let i of numArr)
console.log(i);

for(let i in numArr)
console.log(numArr[i]);
Try it

Update Array Elements


You can update the elements of an array at a particular index
using arrayName[index] = new_value  syntax.

Example: Update Array Elements

let cities = ["Mumbai", "New York", "Paris",


"Sydney"];

cities[0] = "Delhi";
cities[1] = "Los angeles";

console.log(cities); //["Delhi", "Los angeles",


"Paris", "Sydney"]
Try it

Adding New Elements


You can add new elements using arrayName[index] = new_value  syntax.
Just make sure that the index is greater than the last index. If you
specify an existing index then it will update the value.

Example: Add Array Elements


let cities = ["Mumbai", "New York", "Paris",
"Sydney"];

cities[4] = "Delhi"; //add new element at last


console.log(cities); //["Mumbai", "New York", "Paris",
"Sydney", "Delhi"]

cities[cities.length] = "London";//use length property


to specify last index
console.log(cities); //["Mumbai", "New York", "Paris",
"Sydney", "Delhi", "London"]

cities[9] = "Pune";
console.log(cities); //["Mumbai", "New York", "Paris",
"Sydney", "Delhi", "Londen", undefined, undefined,
undefined, "Pune"]
Try it

In the above example, cities[9] = "Pune" adds "Pune" at 9th index and


all other non-declared indexes as undefined.

The recommended way of adding elements at the end is using


the push() method. It adds an element at the end of an array.

Example: Add Element At Last using push()

let cities = ["Mumbai", "New York", "Paris",


"Sydney"];

cities.push("Delhi"); //add new element at last


console.log(cities); //["Mumbai", "New York", "Paris",
"Sydney", "Delhi"]
Try it

Use the unshift() method to add an element to the beginning of an


array.

Example: Add Element using unshift()

let cities = ["Mumbai", "New York", "Paris",


"Sydney"];
cities.unshift("Delhi"); //adds new element at the
beginning
console.log(cities); //["Delhi", "Mumbai", "New York",
"Paris", "Sydney"]

cities.unshift("London", "Pune"); //adds new element


at the beginning
console.log(cities); //["London", "Pune", "Delhi",
"Mumbai", "New York", "Paris", "Sydney"]
Try it

Remove Array Elements


The pop() method returns the last element and removes it from the
array.

Example: Remove Last Element

let cities = ["Mumbai", "New York", "Paris",


"Sydney"];

let removedCity = cities.pop(); //returns and removes


the last element
console.log(cities); //["Mumbai", "New York", "Paris"]
Try it

The shift() method returns the first element and removes it from


the array.

Example: Remove First Element

let cities = ["Mumbai", "New York", "Paris",


"Sydney"];

let removedCity = cities.shift(); //returns first


element and removes it from array
console.log(cities); //["New York", "Paris", "Sydney"]
Try it
You cannot remove middle elements from an array. You will have
to create a new array from an existing array without the element
you do not want, as shown below.

Example: Remove Middle Elements

let cities = ["Mumbai", "New York", "Paris",


"Sydney"];
let cityToBeRemoved = "Paris";

let mycities = cities.filter(function(item) {


return item !== cityToBeRemoved
})

console.log(mycities); //["Mumbai", "New York",


"Sydney"]
console.log(cities); //["Mumbai", "New York", "Paris",
"Sydney"]

Array Methods Reference


The following table lists all the Array methods.

Method Description
concat() Returns new array by combining values of an array that is specified as parameter with existing array values.
every() Returns true or false if every element in the specified array satisfies a condition specified in the callback functi
if single element does not satisfy the condition.
filter() Returns a new array with all the elements that satisfy a condition specified in the callback function.
forEach() Executes a callback function for each elements of an array.
indexOf() Returns the index of the first occurrence of the specified element in the array, or -1 if it is not found.
join() Returns string of all the elements separated by the specified separator
lastIndexOf() Returns the index of the last occurrence of the specified element in the array, or -1 if it is not found.
map() Creates a new array with the results of calling a provided function on every element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements at the end of an array and returns the new length of the array.
reduce() Pass two elements simultaneously in the callback function (till it reaches the last element) and returns a single
reduceRight( Pass two elements simultaneously in the callback function from right-to-left (till it reaches the last element) an
) value.
reverse() Reverses the elements of an array. Element at last index will be first and element at 0 index will be last.
shift() Removes the first element from an array and returns that element.
slice() Returns a new array with specified start to end elements.
some() Returns true if at least one element in this array satisfies the condition in the callback function.
Method Description
sort() Sorts the elements of an array.
splice() Adds and/or removes elements from an array.
toString() Returns a string representing the array and its elements.
unshift() Adds one or more elements to the front of an array and returns the new length of the array.

Difference between null and undefined


in JavaScript
Here you will learn what is null and undefined in JavaScript and
what is the difference between them.

What is a null?
A null means the absence of a value. You assign a null to a
variable with the intention that currently this variable does not
have any value but it will have later on. It is like a placeholder for
a value. The type of null is the object.

Example: null

let num = null;

console.log(num); // null
console.log(typeof num); // "object"

Sometimes, null variables are the result of erroneous code. For


example, if you try to find an HTML element
using document.getElelementByID()  with the wrong id, then it will
return null. So it is recommended to check for null before doing
something with that element.

Example: null

var saveButton = document.getElementById("save");

if (saveButton !== null)


saveButton.submit();
What is undefined?
A variable is undefined when you haven't assigned any value yet,
not even a null.

Example: undefined Variable

let num;
console.log(num);//"undefined"

Generally, variables are undefined when you forgot to assign


values or change existing code. For example, consider the
following Greet() function that returns a string.

function Greet(){
return "Hi";
}

let str = Greet();//"Hi"

Now, suppose somebody changes the function as below. So


now, str will be undefined.

function Greet(){
alert("Hi");
}
let str = Greet();//undefined

Thus, undefined variables are the result of some code problems.

Difference between null and undefined


You must explicitly assign a null to a variable. A variable has
undefined when no value assigned to it.

Example: null and undefined Variables

let num1 = null;


let num2;

console.log(num1);//null
console.log(num2); //undefined
The '' is not the same as null or undefined.

let str = '';

console.log(typeof str);//string
console.log(str === null); //false
console.log(str === undefined); //false

The type of null variable is object whereas the type of undefined


variable is "undefined".

Example: Types

let num1 = null;


let num2;

console.log(typeof num1);//"object"
console.log(typeof num2); //"undefined"

Use the === operator to check whether a variable is null or


undefined. The == operator gives the wrong result.

Example: Comparison using === and ==

let num1 = null;


let num2;

console.log(num1 == null); //true


console.log(num2 == undefined);//true

console.log(num1 == undefined);//true (incorrect)


console.log(num2 == null);//true (incorrect)

console.log(num1 === null); //true


console.log(num2 === undefined);//true

console.log(num1 === undefined);//false


console.log(num2 === null);//false

console.log(num1 == num2);//true (incorrect)


console.log(num1 === num2);//false
The null and undefined variables are falsy to if-statements and
ternary operators.

Example: Null and undefined with if-statements

let num1 = null;


let num2;

if(num1)
{
console.log(num1);
}
else
{
console.log("num1 is null");
}

if(num2)
{
console.log(num2);
}
else
{
console.log("num2 is undefined");
}

A null variable treated as 0 in an numeric expression whereas


undefined variable will be NaN.

Example: With Numeric Expresion

let num1 = null;


let num2;

console.log(num1 + 10);//10
console.log(num2 + 10); //NaN

It will give wrong result when concatenated with string.

Example: With String Values

let num1 = null;


let num2;

console.log(num1 + " Hello");//"null Hello"


console.log(num2 + " Hello"); //"undefined Hello"

Note: The null and undefined variables are one of the main
reasons for runtime errors in JavaScript. The best practice is to
check variables for null or undefined before using them.

Functions in JavaScript
Functions are the basic building block of JavaScript. Functions
allow us to encapsulate a block of code and reuse it multiple times.

Functions make JavaScript code more readable, organized,


reusable, and maintainable.

Syntax:
function <function-name>(arg1, arg2, arg3,...)
{
//write function code here
};

In JavaScript, a function can be defined using the function keyword,


followed by the name of a function and parentheses. Optionally, a
list of input parameters can be included within the parentheses.
The code block that needs to be executed when the function is
called is written within curly braces.

Defining a Function in JavaScript


The following defines a function named greet that will display an
alert box.

Example: Define a Function

function greet() {
alert("Hello World!");
}

The above greet() function does not include any input parameters.


It contains a single statement that displays an alert message.
Now, you can call or invoke the greet function by using the function
name followed by the () operator, as shown below. When you call
a function, JavaScript will execute the codes written inside the
calling function.

Example: Calling a Function

greet();
Try it

Function Parameters
You can pass values to a function using parameters. A function can
have one or more parameters, and the values will be passed by
the calling code.

Example: Function Parameters

function greet(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}

greet("Steve", "Jobs");
Try it

JavaScript is a dynamic type scripting language, so a function


parameter can have a value of any data type.

Example: Function Parameters

function greet(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}

greet("Bill", "Gates");
greet(100, 200);
Try it

You can pass fewer or more arguments while calling a function. If


you pass fewer arguments then the rest of the parameters will
become undefined . If you pass more arguments then additional
arguments will be ignored.
Example: Function Parameters

function greet(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}

greet("Steve", "Jobs", "Mr."); // display Hello Steve


Jobs
greet("Bill"); // display Hello Bill undefined
greet(); // display Hello undefined undefined
Try it

You can also use the built-in arguments object to access


parameters inside a function.

Return a Value From a Function


A function can return a value to the calling code using
the return keyword followed by a variable or a value.

The following returns a number 10.

Example: Return a value of a Function

function getNumber() {
return 10;
};

let result = getNumber();


console.log(result); //output: 10
Try it

Typically, a function returns some calculated value using


paramters or an expression from a function. For example, the
following sum function adds two parameters values using
the + operator and returns the result of an expression.

Example: Return value from a Function

function Sum(num1, num2) {


return num1 + num2;
};
var result = Sum(10,20); // returns 30
Try it

A function can return another function in JavaScript.

Example: Function Returning a Function

function multiple(x) {

function fn(y)
{
return x * y;
}
return fn;
}

var triple = multiple(3);


triple(2); // returns 6
triple(3); // returns 9
Try it

Function Expression
A function expression in JavaScript is a function that is stored as a
value, and can be assigned to a variable or passed as an argument
to another function.

Example: Function Expression

var add = function (num1, num2) {


return num1 + num2;
};

var result = add(10, 20);//returns 30


Try it
Anonymous Function
In JavaScript, you can also create anonymous functions, which are
functions without a name. Anonymous functions are often used as
arguments to other functions, and are

Anonymous functions are typically used in functional programming


e.g. callback function, creating closure or immediately invoked
function expression .

Example: Anonymous Function

let numbers = [10, 20, 30, 40, 50];

let squareNumbers = numbers.map(function(number) {


return number * number;
});
Try it

Arrow Functions
Arrow functions are a shorthand syntax for defining anonymous
functions in JavaScript. They have compact syntax compared to
anonymous functions. However, they do not have their
own this value.

Example: Arrow Function

let square = num => num * num;

let result = square(5);


console.log(result); //25
Try it

Nested Functions
In JavaScript, a function can have one or more inner functions.
These nested functions are in the scope of outer function. Inner
function can access variables and parameters of outer function.
However, outer function cannot access variables defined inside
inner functions.
Example: Nested Functions

function greet(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}

return SayHello();
}

greet("Steve");

JavaScript if...else Statements


JavaScript includes if/else conditional statements to control the
program flow, similar to other programming languages.

JavaScript includes following forms of if-else statements:

1. if Statement
2. if else Statement
3. else if Statement

if Statement
Use if conditional statement if you want to execute something
based on some condition.

Syntax:
if(boolean expression)
{
// code to be executed if condition is true
}
Example: if condition
if( 1 > 0)
{
alert("1 is greater than 0");
}

if( 1 < 0)
{
alert("1 is less than 0");
}
Try it

In the above example, the first if statement contains 1 > 0 as


conditional expression. The conditional expression 1 > 0 will be
evaluated to true, so an alert message "1 is greater than 0" will be
displayed, whereas conditional expression in second if statement
will be evaluated to false, so "1 is less than 0" alert message will
not be displayed.

In the same way, you can use variables in a conditional


expression.

Example: if condition
var mySal = 1000;
var yourSal = 500;

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}
Try it
 
 Note:
curly braces { } is not required when if block contains only
a single line to execute.

Use comparison operators carefully when writing conditional


expression. For example, == and === is different.

Example: if condition
if(1=="1")
{
alert("== operator does not consider types of operands");
}

if(1==="1")
{
alert("=== operator considers types of operands");
}
Try it

else condition
Use else statement when you want to execute the code every time
when if condition evaluates to false.

The else statement must follow if or else if statement. Multiple


else block is NOT allowed.

Syntax:
if(condition expression)
{
//Execute this code..
}
else{
//Execute this code..
}
Example: else condition
var mySal = 500;
var yourSal = 1000;

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}
else
{
alert("My Salary is less than or equal to your salary");
}
Try it

else if condition
Use "else if" condition when you want to apply second level
condition after if statement.

Syntax:
if(condition expression)
{
//Execute this code block
}
else if(condition expression){
//Execute this code block
}
Example: else if condition
var mySal = 500;
var yourSal = 1000;

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}
else if(mySal < yourSal)
{
alert("My Salary is less than your salary");
}
Try it

JavaScript allows multiple else if statements also.

Example: Multiple if else conditions


var mySal = 500;
var yourSal = 1000;

if( mySal > yourSal)


{
alert("My Salary is greater than your salary");
}
else if(mySal < yourSal)
{
alert("My Salary is less than your salary");
}
else if(mySal == yourSal)
{
alert("My Salary is equal to your salary");
}
Try it

We will learn about switch case in the next section.

 Points to Remember :

1. Use if-else conditional statements to control the program


flow.
2. JavaScript includes three forms of if condition: if condition, if
else condition and else if condition.
3. The if condition must have conditional expression in brackets
() followed by single statement or code block wrapped with
{ }.
4. 'else if' statement must be placed after if condition. It can be
used multiple times.
5. 'else' condition must be placed only once at the end. It must
come after if or else if statement.

JavaScript switch
The switch is a conditional statement like if statement. Switch is
useful when you want to execute one of the multiple code blocks
based on the return value of a specified expression.

Syntax:
switch(expression or literal value){
case 1:
//code to be executed
break;
case 2:
//code to be executed
break;
case n:
//code to be executed
break;
default:
//default code to be executed
//if none of the above case executed
}

Use break keyword to stop the execution and exit from the switch. Also, you
can write multiple statements in a case without using curly braces { }.

As per the above syntax, switch statement contains an expression


or literal value. An expression will return a value when evaluated.
The switch can includes multiple cases where each case represents
a particular value. Code under particular case will be executed
when case value is equal to the return value of switch expression.
If none of the cases match with switch expression value then the
default case will be executed.

Example: switch Statement


var a = 3;

switch (a) {
case 1:
alert('case 1 executed');
break;
case 2:
alert("case 2 executed");
break;
case 3:
alert("case 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}
Try it

In the above example, switch statement contains a literal value as


expression. So, the case that matches a literal value will be
executed, case 3 in the above example.

The switch statement can also include an expression. A case that


matches the result of an expression will be executed.

Example: switch Statement


var a = 3;

switch (a/3) {
case 1:
alert("case 1 executed");
break;
case 2:
alert("case 2 executed");
break;
case 3:
alert("case 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}
Try it

In the above example, switch statement includes an expression


a/3, which will return 1 (because a = 3). So, case 1 will be
executed in the above example.

The switch can also contain string type expression.

Example: switch with String Type Case


var str = "bill";

switch (str)
{
case "steve":
alert("This is Steve");
case "bill":
alert("This is Bill");
break;
case "john":
alert("This is John");
break;
default:
alert("Unknown Person");
break;
}
Try it

Multiple cases can be combined in a switch statement.

Example: Combined switch Cases


var a = 2;

switch (a) {
case 1:
case 2:
case 3:
alert("case 1, 2, 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}
Try it

 Points to Remember :

1. The switch is a conditional statement like if statement.


2. A switch statement includes literal value or is expression
based
3. A switch statement includes multiple cases that include code
blocks to execute.
4. A break keyword is used to stop the execution of case block.
5. A switch case can be combined to execute same code block
for multiple cases.

JavaScript for Loop


JavaScript includes for loop like Java or C#. Use for loop to
execute code repeatedly.

Syntax:
for(initializer; condition; iteration)
{
// Code to be executed
}

The for loop requires following three parts.

 Initializer: Initialize a counter variable to start with


 Condition: specify a condition that must evaluate to true for
next iteration
 Iteration: increase or decrease counter

Example: for loop


for (var i = 0; i < 5; i++)
{
console.log(i);
}
Try it
Output:
0 1 2 3 4

In the above example, var i = 0 is an initializer statement where


we declare a variable i with value 0. The second part, i < 5 is a
condition where it checks whether i is less than 5 or not. The third
part, i++ is iteration statement where we use ++ operator to
increase the value of i to 1. All these three parts are separated by
semicolon ;.

The for loop can also be used to get the values for an array.

Example: for loop


var arr = [10, 11, 12, 13, 14];

for (var i = 0; i < 5; i++)


{
console.log(arr[i]);
}
Try it
Output:
10 11 12 13 14

Please note that it is not mandatory to specify an initializer,


condition and increment expression into bracket. You can specify
initializer before starting for loop. The condition and increment
statements can be included inside the block.

Example: for loop


var arr = [10, 11, 12, 13, 14];
var i = 0;

for (; ;) {

if (i >= 5)
break;

console.log(arr[i]);

i++;
}
Try it
Output:
10 11 12 13 14

Learn about while loop in the next section.

 Points to Remember :

1. JavaScript for loop is used to execute code repeatedly.


2. for loop includes three parts: initialization, condition and
iteration. e.g.for(initializer; condition; iteration){ ... }
3. The code block can be wrapped with { } brackets.
4. An initializer can be specified before starting for loop. The
condition and increment statements can be included inside
the block.

JavaScript - While Loop


JavaScript includes while loop to execute code repeatedly till it
satisfies a specified condition. Unlike for loop, while loop only
requires condition expression.

Syntax:
while(condition expression)
{
/* code to be executed
till the specified condition is true */
}
Example: while loop
var i =0;

while(i < 5)
{
console.log(i);
i++;
}
Try it
Output:
0 1 2 3 4
Make sure condition expression is appropriate and include increment or
decrement counter variables inside the while block to avoid infinite loop.

As you can see in the above example, while loop will execute the
code block till i < 5 condition turns out to be false. Initialization
statement for a counter variable must be specified before starting
while loop and increment of counter must be inside while block.

do while
JavaScript includes another flavour of while loop, that is do-while
loop. The do-while loop is similar to while loop the only difference
is it evaluates condition expression after the execution of code
block. So do-while loop will execute the code block at least once.

Syntax:
do{

//code to be executed

}while(condition expression)
Example: do-while loop
var i = 0;

do{

alert(i);
i++;

} while(i < 5)

Try it
Output:

0 1 2 3 4

The following example shows that do-while loop will execute a


code block even if the condition turns out to be false in the first
iteration.

Example: do-while loop


var i =0;

do{

alert(i);
i++;

} while(i > 1)

Output:

0
 Points to Remember :

1. JavaScript while loop & do-while loop execute the code block
repeatedly till conditional expression returns true.
2. do-while loop executes the code at least once even if
condition returns false.

JavaScript eval
eval() is a global function in JavaScript that evaluates a specified
string as JavaScript code and executes it.

Example: eval
eval("alert('this is executed by eval()')");
Try it

The eval() function can also call the function and get the result as
shown below.

Example: eval
var result;

function Sum(val1, val2)


{
return val1 + val2;
}

eval("result = Sum(5, 5);");

alert(result);
Try it

eval can convert string to JSON object.

Example: eval with JSON Object


var str = '({"firstName":"Bill","lastName":"Gates"})';

var obj = eval(str);

obj.firstName; // Bill

Recommendation
It is not recommended to use eval() because it is slow, not secure,
and makes code unreadable and maintainable.

Error handling in JavaScript


JavaScript is a loosely-typed language. It does not give compile-time errors. So
some times you will get a runtime error for accessing an undefined variable or
calling undefined function etc.

try catch block does not handle syntax errors.

JavaScript provides error-handling mechanism to catch runtime errors using try-


catch-finally block, similar to other languages like Java or C#.

Syntax:
try
{
// code that may throw an error
}
catch(ex)
{
// code to be executed if an error occurs
}
finally{
// code to be executed regardless of an error occurs or not
}

 try: wrap suspicious code that may throw an error in try block.


 catch: write code to do something in catch block when an error occurs. The
catch block can have parameters that will give you error information.
Generally catch block is used to log an error or display specific messages to
the user.
 finally: code in the finally block will always be executed regardless of the
occurrence of an error. The finally block can be used to complete the
remaining task or reset variables that might have changed before error
occurred in try block.

Let's look at simple error handling examples.

Example: Error Handling in JS


try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}

In the above example, we are calling function Sum, which is not defined yet. So, try
block will throw an error which will be handled by catch block. Ex includes error
message that can be displayed.

The finally block executes regardless of whatever happens.

Example: finally Block


try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
finally{
document.getElementById("message").innerHTML = "finally block
executed";
}
Try it

throw
Use throw keyword to raise a custom error.

Example: throw Error


try
{
throw "Error occurred";
}
catch(ex)
{
alert(ex);
}

You can use JavaScript object for more information about an error.

Example: throw error with error info


try
{
throw {
number: 101,
message: "Error occurred"
};
}
catch (ex) {
alert(ex.number + "- " + ex.message);
}
JavaScript Regular Expressions
A regular expression is a sequence of characters that forms a search
pattern.

The search pattern can be used for text search and text replace
operations.

What Is a Regular Expression?


A regular expression is a sequence of characters that forms a search
pattern.

When you search for data in a text, you can use this search pattern to
describe what you are searching for.

A regular expression can be a single character, or a more complicated


pattern.

Regular expressions can be used to perform all types of text


search and text replace operations.

Syntax
/pattern/modifiers;

Example
/w3schools/i;

Example explained:

/w3schools/i  is a regular expression.

w3schools  is a pattern (to be used in a search).

i  is a modifier (modifies the search to be case-insensitive).

Using String Methods


In JavaScript, regular expressions are often used with the two string
methods: search() and replace().
The search() method uses an expression to search for a match, and returns
the position of the match.

The replace() method returns a modified string where the pattern is


replaced.

Using String search() With a String


The search() method searches a string for a specified value and returns the
position of the match:

Example
Use a string to do a search for "W3schools" in a string:

let text = "Visit W3Schools!";


let n = text.search("W3Schools");

The result in n will be:

Using String search() With a Regular


Expression
Example
Use a regular expression to do a case-insensitive search for "w3schools" in a
string:

let text = "Visit W3Schools";


let n = text.search(/w3schools/i);

The result in n will be:


Using String replace() With a String
The replace() method replaces a specified value with another value in a
string:

let text = "Visit Microsoft!";


let result = text.replace("Microsoft", "W3Schools");

Use String replace() With a Regular


Expression
Example
Use a case insensitive regular expression to replace Microsoft with
W3Schools in a string:

let text = "Visit Microsoft!";


let result = text.replace(/microsoft/i, "W3Schools");

The result in res will be:

Visit W3Schools!

Did You Notice?


Regular expression arguments (instead of string arguments) can be used in
the methods above.
Regular expressions can make your search much more powerful (case
insensitive for example).

Regular Expression Modifiers


Modifiers can be used to perform case-insensitive more global searches:

Modifier Description
i Perform case-insensitive matching

g Perform a global match (find all matches rather than stopping

after the first match)

m Perform multiline matching

Regular Expression Patterns


Brackets are used to find a range of characters:

Expression Description

[abc] Find any of the characters between the brackets

[0-9] Find any of the digits between the brackets

(x|y) Find any of the alternatives separated with |

Metacharacters are characters with a special meaning:

Metacharacter Description

\d Find a digit
\s Find a whitespace character

\b Find a match at the beginning of a word like this: \bWORD, o


WORD\b

\uxxxx Find the Unicode character specified by the hexadecimal num

Quantifiers define quantities:

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or

more occurrences of n

n? Matches any string that contains zero or

one occurrences of n

Using the RegExp Object


In JavaScript, the RegExp object is a regular expression object with
predefined properties and methods.
Using test()
The test() method is a RegExp expression method.

It searches a string for a pattern, and returns true or false, depending on the
result.

The following example searches a string for the character "e":

Example
const pattern = /e/;
pattern.test("The best things in life are free!");

Since there is an "e" in the string, the output of the code above will be:

true

Try it Yourself »

You don't have to put the regular expression in a variable first. The two lines
above can be shortened to one:

/e/.test("The best things in life are free!");

Using exec()
The exec() method is a RegExp expression method.

It searches a string for a specified pattern, and returns the found text as an
object.

If no match is found, it returns an empty (null) object.

The following example searches a string for the character "e":

Example
/e/.exec("The best things in life are free!");

Try it Yourself »
Complete RegExp Reference
For a complete reference, go to our Complete JavaScript RegExp Reference.

The reference contains descriptions and examples of all RegExp properties


and methods.

You might also like