Introduction To JavaScript
Introduction To JavaScript
Introduction To JavaScript
<!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
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.
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.
<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" onclick="gfg()">
click it
</button>
</body>
</html>
Output:
<html>
<body>
<h2>
JavaScript in Body
</h2>
<p id="demo">
geeksforgeeks.
</p>
<button type="button" onclick="gfg()">
Try it
</button>
<script>
function gfg() {
document.getElementById("demo").innerHTML =
"Geeks For Geeks";
}
</script>
</body>
</html>
Output:
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" onclick="myFunction()">
Try it
</button>
<script src="myScript.js"></script>
</body>
</html>
Output:
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"
onclick="myFunction()">
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 comment is ignored by the JavaScript engine i.e. embedded in the
browser.
1. Single-line Comment
2. Multi-line Comment
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>
1. /* your code here */
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.
let msg;
msg = "Hello JavaScript!"; // assigning a string value
JavaScript allows multiple white spaces and line breaks when you
declare a variables.
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.
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.
myfunction();
alert(greet);//can access global variable
alert(msg); //error: can't access local variable
function myfunction(){
msg = "Hello JavaScript!";
}
myfunction();
alert(msg); // msg becomes global variable so can be
accessed here
Points to Remember
Scope in JavaScript
Scope in JavaScript defines accessibility of variables, objects and
functions.
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.
function modifyUserName() {
userName = "Steve";
};
function showUserName() {
alert(userName);
};
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.
function createUserName() {
userName = "Bill";
}
function modifyUserName() {
if(userName)
userName = "Steve";
};
function showUserName() {
alert(userName);
}
createUserName();
showUserName(); // Bill
modifyUserName();
showUserName(); // Steve
</script>
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.
function createUserName() {
var userName = "Bill";
}
function showUserName() {
alert(userName);
}
createUserName();
showUserName(); // throws error: userName is not defined
</script>
Some tips..
Example: Scope
var userName = "Bill";
function ShowUserName()
{
var userName = "Steve";
alert(userName); // "Steve"
}
ShowUserName();
alert(userName); // Bill
if (1 > 0)
{
var myVar = 22;
alert(myVar);
}
NoBlockLevelScope();
Points to Remember :
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]);
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]);
Example: confirm()
var userPreference;
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.
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.
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
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.
a + d; //returns 15
Comparison Operators
JavaScript provides comparison operators that compare two
operands and return a boolean value true or false.
Operators Description
> 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
a == c; // returns true
a == x; // returns true
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.
Assignment
operators Description
+= 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.
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.
Points to Remember:
String String is a textual content wrapped inside ' ' or " " or ` ` (tick sign).
Boolean Boolean is a logical data type that has only two values, true or false.
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.
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.
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.
"Hello World"
'Hello World'
`Hello World`
// or
typeof(str1); //"object"
typeof(str2); //"string"
Strings Comparison
Two strings can be compared using <, >, ==, === operator,
and string.localeCompare(string) method.
String Properties
Property Description
String Methods
Method Description
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.
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.
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.
Method Description
link() Wraps a string in <a>tag where href attribute value is set to specified string.
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.
Floating-point Numbers
Even if one of the values is a number, the result would be the same.
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.
num2 == num3;//true
num2 === num3; // true
num1 == num3;//true
num1 === num3;//false
Number Properties
Property Description
Method Description
Example:
var num = 100; num.toExponential(2); //
returns '1.00e+2'
Example:
var num = 100; num.toFixed(2); // returns '100.00'
Example:
var num = 100; num.toLocaleString(); // returns '100'
Example:
var num = 100; num.toPrecision(4); // returns '100.0'
Example:
var num = 100; num.toString(); // returns '100'
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.
var NO = false;
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");
}
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.
If the first parameter is 0, -0, null, false, NaN, undefined, '' (empty
string), or no parameter passed then the Boolean() function
returns false.
var a;
var b4 = Boolean(a); // false
alert(bool); // true
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.
Boolean Methods
Primitive or Boolean object includes following methods.
Method Description
Example: hasOwnProperty()
var person = new Object();
if(person.hasOwnProperty("firstName")){
person.firstName;
}
Pass by Reference
Object in JavaScript passes by reference from one function to
another.
changeFirstName(person)
Nested Objects
An object can be a property of another object. It is called a nested
object.
//or
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.
You can use any valid separator in the date string to differentiate
date segments.
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');
date.toLocaleDateString();'2/10/2015'
date.toISOString(); '2015-02-10T10:12:50.500Z'
date.toTimeString(); '15:42:50'
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.
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.
JavaSc
ript Array Representation
cities[4] = "Delhi";
console.log(cities.length); //5
Try it
console.log(cities[0]); // "Mumbai"
console.log(cities[1]); // "New York"
console.log(cities[2]); // "Paris"
console.log(cities[3]); // "Sydney"
for(let i of numArr)
console.log(i);
for(let i in numArr)
console.log(numArr[i]);
Try it
cities[0] = "Delhi";
cities[1] = "Los angeles";
cities[9] = "Pune";
console.log(cities); //["Mumbai", "New York", "Paris",
"Sydney", "Delhi", "Londen", undefined, undefined,
undefined, "Pune"]
Try it
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.
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
console.log(num); // null
console.log(typeof num); // "object"
Example: null
let num;
console.log(num);//"undefined"
function Greet(){
return "Hi";
}
function Greet(){
alert("Hi");
}
let str = Greet();//undefined
console.log(num1);//null
console.log(num2); //undefined
The '' is not the same as null or undefined.
console.log(typeof str);//string
console.log(str === null); //false
console.log(str === undefined); //false
Example: Types
console.log(typeof num1);//"object"
console.log(typeof num2); //"undefined"
if(num1)
{
console.log(num1);
}
else
{
console.log("num1 is null");
}
if(num2)
{
console.log(num2);
}
else
{
console.log("num2 is undefined");
}
console.log(num1 + 10);//10
console.log(num2 + 10); //NaN
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.
Syntax:
function <function-name>(arg1, arg2, arg3,...)
{
//write function code here
};
function greet() {
alert("Hello World!");
}
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.
greet("Steve", "Jobs");
Try it
greet("Bill", "Gates");
greet(100, 200);
Try it
function getNumber() {
return 10;
};
function multiple(x) {
function fn(y)
{
return x * y;
}
return fn;
}
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.
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.
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");
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
Example: if condition
var mySal = 1000;
var yourSal = 500;
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.
Syntax:
if(condition expression)
{
//Execute this code..
}
else{
//Execute this code..
}
Example: else condition
var mySal = 500;
var yourSal = 1000;
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;
Points to Remember :
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 { }.
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
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
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
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 :
Syntax:
for(initializer; condition; iteration)
{
// Code to be executed
}
The for loop can also be used to get the values for an array.
for (; ;) {
if (i >= 5)
break;
console.log(arr[i]);
i++;
}
Try it
Output:
10 11 12 13 14
Points to Remember :
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
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;
alert(result);
Try it
obj.firstName; // Bill
Recommendation
It is not recommended to use eval() because it is slow, not secure,
and makes code unreadable and maintainable.
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
}
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.
throw
Use throw keyword to raise a custom error.
You can use JavaScript object for more information about an error.
The search pattern can be used for text search and text replace
operations.
When you search for data in a text, you can use this search pattern to
describe what you are searching for.
Syntax
/pattern/modifiers;
Example
/w3schools/i;
Example explained:
Example
Use a string to do a search for "W3schools" in a string:
Visit W3Schools!
Modifier Description
i Perform case-insensitive matching
Expression Description
Metacharacter Description
\d Find a digit
\s Find a whitespace character
Quantifiers define quantities:
Quantifier Description
It searches a string for a pattern, and returns true or false, depending on the
result.
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:
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.
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.