0% found this document useful (0 votes)
15 views

Javascript

Uploaded by

bharathikrishna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Javascript

Uploaded by

bharathikrishna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible


within the function or block only. For example:

1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>

Or,

1. <script>
2. If(10<13){
3. var y=20;//JavaScript local variable
4. }
5. </script>

JavaScript global variable

A JavaScript global variable is accessible from any function. A variable i.e.


declared outside the function or declared with window object is known as global
variable. For example:

1. <script>
2. var data=200;//gloabal variable
3. function a(){
4. document.writeln(data);
5. }
6. function b(){
7. document.writeln(data);
8. }
9. a();//calling JavaScript function
10.b();
11.</script>
JavaScript If-else

The JavaScript if-else statement is used to execute the code whether condition is
true or false. There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript if


statement is given below.

1. if(expression){
2. //content to be evaluated

3. }
Flowchart of JavaScript If statement

Let’s see the simple example of if statement in javascript.

1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>
Test it Now

Output of the above example


value of a is greater than 10

JavaScript If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript
if-else statement is given below.

1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
Flowchart of JavaScript If...else statement
Let’s see the example of if-else statement in JavaScript to find out the even or odd
number.

1. <script>
2. var a=20;
3. if(a%2==0){
4. document.write("a is even number");
5. }
6. else{
7. document.write("a is odd number");
8. }
9. </script>
Test it Now

Output of the above example


a is even number

JavaScript If...else if statement

It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.

1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10.else{
11.//content to be evaluated if no expression is true
12.}

Let’s see the simple example of if else if statement in javascript


1. <script>
2. var a=20;
3. if(a==10){
4. document.write("a is equal to 10");
5. }
6. else if(a==15){
7. document.write("a is equal to 15");
8. }
9. else if(a==20){
10.document.write("a is equal to 20");
11.}
12.else{
13.document.write("a is not equal to 10, 15 or 20");
14.}
15.</script>
Test it Now

Output of the above example


a is equal to 20

JavaScript Functions

JavaScript functions are used to perform operations. We can call JavaScript


function many times to reuse the code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many
lines of code each time to perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){


2. //code to be executed
3. }

JavaScript Functions can have 0 or more arguments.

JavaScript Function Example

Let’s see the simple example of function in JavaScript that does not has arguments.

1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>

JavaScript Function Arguments

We can call function by passing arguments. Let’s see the example of function that
has one argument.

1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>

Output of the above example


64
Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.

1. <script>
2. function getInfo(){
3. return "hello! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>

Output of the above example


hello ! How r u?

JavaScript Objects

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

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

Pause
Unmute
Loaded: 100.00%
Remaining Time -4:08
Fullscreen
x
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal

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

object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>
Test it Now

Output of the above example


102 Shyam Kumar 40000

2) By creating instance of Object

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.


Let’s see the example of creating object directly.

1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Test it Now

Output of the above example


101 Ravi 50000

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.

The this keyword refers to the current object.

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

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10.</script>
Test it Now
Output of the above example
103 Vimal Jaiswal 30000

JavaScript Array

JavaScript array is an object that represents a collection of similar type of


elements.

There are 3 ways to construct array in JavaScript

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

1) JavaScript array literal

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

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

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

4.5K
Hands On WIth EVERY Apple Leather Case for iPhone 13!

Let's see the simple example of creating and using array in JavaScript.

1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Test it Now

The .length property returns the length of an array.

Output of the above example

Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

var arrayname=new Array();

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

Let's see the example of creating array directly.

<script>
1. var i;
2. var emp = new Array();
3. emp[0] = "Arun";
4. emp[1] = "Varun";
5. emp[2] = "John";
6.
7. for (i=0;i<emp.length;i++){
8. document.write(emp[i] + "<br>");
9. }
10.</script>
Test it Now
Output of the above example

Arun
Varun
John

3) JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so


that we don't have to provide value explicitly.

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

1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>

Output of the above example

Jai
Vijay
Smith

JavaScript Array Methods

Let's see the list of JavaScript array methods with their description.

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns th
modified array.

entries() It creates an iterator object and a loop that iterates over each key/valu
pair.

every() It determines whether all the elements of an array are satisfying th


provided function conditions.

flat() It creates a new array carrying sub-array elements concatenate


recursively till the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the resul
into a new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provide
function conditions.

find() It returns the value of the first element in the given array that satisfies th
specified condition.

findIndex() It returns the index value of the first element in the given array tha
satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the inde
of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, the
loops through these keys.

lastIndexOf() It searches the specified element in the given array and returns the inde
of the last match.

map() It calls the specified function for every array element and returns the new
array

of() It creates a new array from a variable number of arguments, holding an


type of argument.

pop() It removes and returns the last element of an array.


push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right an
initial) reduces the array to a single value.

reduceRight() It executes a provided function for each value from right to left an
reduces the array to a single value.

some() It determines if any element of the array passes the test of th


implemented function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.


toString() It converts the elements of a specified array into string form, withou
affecting the original array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in th
array.

JavaScript String

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

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

1) By string literal

The string literal is created using double quotes. The syntax of creating string using
string literal is given below.

var stringname="string value";

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

<script>
var str="This is string literal";
document.write(str);
</script>
Test it Now

Output:

This is string literal

2) By string object (using new keyword)

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

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

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

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

<script>
1. var stringname=new String("hello javascript string");
2. document.write(stringname);
3. </script>
Test it Now

Output:

hello javascript string

JavaScript String Methods

Let's see the list of JavaScript string methods with examples.


Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the specifie


index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string b
searching a character from the last position.

search() It searches a specified regular expression in a given string and returns it


position if a match occurs.

match() It searches a specified regular expression in a given string and return


that regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis of the specifie
starting position and length.

substring() It is used to fetch the part of the given string on the basis of the specifie
index.

slice() It is used to fetch the part of the given string. It allows us to assig
positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase( It converts the given string into lowercase letter on the basis of host?
) current locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?
current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that newly create
array.

trim() It trims the white space from the left and right side of the string.

1) JavaScript String charAt(index) Method


The JavaScript String charAt() method returns the character at the given index.

1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Test it Now

Output:

2) JavaScript String concat(str) Method

The JavaScript String concat(str) method concatenates or joins two strings.

1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Test it Now

Output:

javascript concat example

3) JavaScript String indexOf(str) Method

The JavaScript String indexOf(str) method returns the index position of the given
string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Test it Now

Output:

11

4) JavaScript String lastIndexOf(str) Method

The JavaScript String lastIndexOf(str) method returns the last index position of the
given string.

1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
5. </script>
Test it Now

Output:

16

5) JavaScript String toLowerCase() Method

The JavaScript String toLowerCase() method returns the given string in lowercase
letters.

1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>
Test it Now
Output:

javascript tolowercase example

6) JavaScript String toUpperCase() Method

The JavaScript String toUpperCase() method returns the given string in uppercase
letters.

<script>
1. var s1="JavaScript toUpperCase Example";
2. var s2=s1.toUpperCase();
3. document.write(s2);
4. </script>
Test it Now

Output:

JAVASCRIPT TOUPPERCASE EXAMPLE

7) JavaScript String slice(beginIndex, endIndex) Method

The JavaScript String slice(beginIndex, endIndex) method returns the parts of


string from given beginIndex to endIndex. In slice() method, beginIndex is
inclusive and endIndex is exclusive.

1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>
Test it Now

Output:

cde

8) JavaScript String trim() Method

The JavaScript String trim() method removes leading and trailing whitespaces
from the string.

1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>
Test it Now

Output:

javascript trim
9) JavaScript String split() Method

1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>
JavaScript Date Object

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

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

Constructor

You can use 4 variant of Date constructor to create date object.

1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)

JavaScript Date Methods

Let's see the list of JavaScript date methods with their description.

Play Videox

Methods Description

getDate() It returns the integer value between 1 and 31 that represents the day fo
the specified date on the basis of local time.

getDay() It returns the integer value between 0 and 6 that represents the day o
the week on the basis of local time.

getFullYears() It returns the integer value that represents the year on the basis of loca
time.
getHours() It returns the integer value between 0 and 23 that represents the hour
on the basis of local time.

getMilliseconds() It returns the integer value between 0 and 999 that represents th
milliseconds on the basis of local time.

getMinutes() It returns the integer value between 0 and 59 that represents the minute
on the basis of local time.

getMonth() It returns the integer value between 0 and 11 that represents the mont
on the basis of local time.

getSeconds() It returns the integer value between 0 and 60 that represents the second
on the basis of local time.

getUTCDate() It returns the integer value between 1 and 31 that represents the day fo
the specified date on the basis of universal time.

getUTCDay() It returns the integer value between 0 and 6 that represents the day o
the week on the basis of universal time.

getUTCFullYears() It returns the integer value that represents the year on the basis o
universal time.

getUTCHours() It returns the integer value between 0 and 23 that represents the hour
on the basis of universal time.

getUTCMinutes() It returns the integer value between 0 and 59 that represents the minute
on the basis of universal time.

getUTCMonth() It returns the integer value between 0 and 11 that represents the mont
on the basis of universal time.

getUTCSeconds() It returns the integer value between 0 and 60 that represents the second
on the basis of universal time.

setDate() It sets the day value for the specified date on the basis of local time.

setDay() It sets the particular day of the week on the basis of local time.

setFullYears() It sets the year value for the specified date on the basis of local time.

setHours() It sets the hour value for the specified date on the basis of local time.

setMilliseconds() It sets the millisecond value for the specified date on the basis of loca
time.

setMinutes() It sets the minute value for the specified date on the basis of local time.

setMonth() It sets the month value for the specified date on the basis of local time.

setSeconds() It sets the second value for the specified date on the basis of local time.

setUTCDate() It sets the day value for the specified date on the basis of universal time

setUTCDay() It sets the particular day of the week on the basis of universal time.

setUTCFullYears() It sets the year value for the specified date on the basis of universa
time.

setUTCHours() It sets the hour value for the specified date on the basis of universa
time.

setUTCMilliseconds( It sets the millisecond value for the specified date on the basis o
) universal time.

setUTCMinutes() It sets the minute value for the specified date on the basis of universa
time.

setUTCMonth() It sets the month value for the specified date on the basis of universa
time.

setUTCSeconds() It sets the second value for the specified date on the basis of universa
time.

toDateString() It returns the date portion of a Date object.

toISOString() It returns the date in the form ISO format string.

toJSON() It returns a string representing the Date object. It also serializes the Dat
object during JSON serialization.

toString() It returns the date in the form of string.

toTimeString() It returns the time portion of a Date object.

toUTCString() It converts the specified date in the form of string using UTC time zone

valueOf() It returns the primitive value of a Date object.

JavaScript Date Example

Let's see the simple example to print date object. It prints date and time both.

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


2. <script>
3. var today=new Date();
4. document.getElementById('txt').innerHTML=today;
5. </script>
Test it Now

Output:
Current Date and Time: Sun Aug 28 2022 10:25:50 GMT+0530 (India Standard
Time)

Let's see another code to print date/month/year.

1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>

Output:

Date is: 28/8/2022

JavaScript Current Time Example

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

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


2. <script>
3. var today=new Date();
4. var h=today.getHours();
5. var m=today.getMinutes();
6. var s=today.getSeconds();
7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
8. </script>
Test it Now

Output:

Current Time: 10:25:50

JavaScript Digital Clock Example

Let's see the simple example to display digital clock using JavaScript date object.
There are two ways to set interval in JavaScript: by setTimeout() or setInterval()
method.

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


2. <script>
3. window.onload=function(){getTime();}
4. function getTime(){
5. var today=new Date();
6. var h=today.getHours();
7. var m=today.getMinutes();
8. var s=today.getSeconds();
9. // add a zero in front of numbers<10
10.m=checkTime(m);
11.s=checkTime(s);
12.document.getElementById('txt').innerHTML=h+":"+m+":"+s;
13.setTimeout(function(){getTime()},1000);
14.}
15.//setInterval("getTime()",1000);//another way
16.function checkTime(i){
17.if (i<10){
18. i="0" + i;
19. }
20.return i;
21.}
22.</script>
Test it Now

Output:

Current Time: 10:26:19

JavaScript Math

The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.

JavaScript Math Methods


Let's see the list of JavaScript Math methods with description.

Methods Description

abs() It returns the absolute value of the given number.

acos() It returns the arccosine of the given number in radians.

asin() It returns the arcsine of the given number in radians.

atan() It returns the arc-tangent of the given number in radians.

cbrt() It returns the cube root of the given number.

ceil() It returns a smallest integer value, greater than or equal to the given number.

cos() It returns the cosine of the given number.

cosh() It returns the hyperbolic cosine of the given number.

exp() It returns the exponential form of the given number.

floor() It returns largest integer value, lower than or equal to the given number.

hypot() It returns square root of sum of the squares of given numbers.

log() It returns natural logarithm of a number.

max() It returns maximum value of the given numbers.

min() It returns minimum value of the given numbers.


pow() It returns value of base to the power of exponent.

random() It returns random number between 0 (inclusive) and 1 (exclusive).

round() It returns closest integer value of the given number.

sign() It returns the sign of the given number

sin() It returns the sine of the given number.

sinh() It returns the hyperbolic sine of the given number.

sqrt() It returns the square root of the given number

tan() It returns the tangent of the given number.

tanh() It returns the hyperbolic tangent of the given number.

trunc() It returns an integer part of the given number.

Math.sqrt(n)

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

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


2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>
Test it Now

Output:

8.7M
83
Competitive questions on Structures
Square Root of 17 is: 4.123105625617661

Math.random()

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

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


2. <script>
3. document.getElementById('p2').innerHTML=Math.random();
4. </script>
Test it Now

Output:

Random Number is: 0.37262016027071065

Math.pow(m,n)

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

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


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

Output:

3 to the power of 4 is: 81

Math.floor(n)

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

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


2. <script>
3. document.getElementById('p4').innerHTML=Math.floor(4.6);
4. </script>
Test it Now
Output:

Floor of 4.6 is: 4

Math.ceil(n)

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

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


2. <script>
3. document.getElementById('p5').innerHTML=Math.ceil(4.6);
4. </script>
Test it Now

Output:

Ceil of 4.6 is: 5

Math.round(n)

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

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


2. Round of 4.7 is: <span id="p7"></span>
3. <script>
4. document.getElementById('p6').innerHTML=Math.round(4.3);
5. document.getElementById('p7').innerHTML=Math.round(4.7);
6. </script>
Test it Now

Output:

Round of 4.3 is: 4


Round of 4.7 is: 5

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

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


2. <script>
3. document.getElementById('p8').innerHTML=Math.abs(-4);
4. </script>
Test it Now

Output:

Absolute value of -4 is: 4

JavaScript Number Object

The JavaScript number object enables you to represent a numeric value. It may
be integer or floating-point. JavaScript number object follows IEEE standard to
represent the floating-point numbers.

By the help of Number() constructor, you can create number object in JavaScript.
For example:

1. var n=new Number(value);

If value can't be converted to number, it returns NaN(Not a Number) that can be


checked by isNaN() method.

You can direct assign a number to a variable also. For example:

59.4M
1.1K
C++ vs Java
1. var x=102;//integer value
2. var y=102.7;//floating point value
3. var z=13e4;//exponent value, output: 130000
4. var n=new Number(16);//integer value by number object
Test it Now
Output:

102 102.7 130000 16

JavaScript Number Constants

Let's see the list of JavaScript number constants with description.

Constant Description

MIN_VALUE returns the largest minimum value.

MAX_VALUE returns the largest maximum value.

POSITIVE_INFINITY returns positive infinity, overflow value.

NEGATIVE_INFINITY returns negative infinity, overflow value.

NaN represents "Not a Number" value.

JavaScript Number Methods

Let's see the list of JavaScript number methods with their description.

Methods Description

isFinite() It determines whether the given value is a finite number.

isInteger() It determines whether the given value is an integer.

parseFloat() It converts the given string into a floating point number.

parseInt() It converts the given string into an integer number.


toExponential( It returns the string that represents exponential notation of the given number.
)

toFixed() It returns the string that represents a number with exact digits after a decima
point.

toPrecision() It returns the string representing a number of specified precision.

toString() It returns the given number in the form of string.

JavaScript Boolean

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

1. Boolean b=new Boolean(value);

The default value of JavaScript Boolean object is false.

JavaScript Boolean Example


1. <script>
2. document.write(10<20);//true
3. document.write(10<5);//false
4. </script>

JavaScript Boolean Properties

Property Description

constructor returns the reference of Boolean function that created Boolean object.

prototype enables you to add properties and methods in Boolean prototype.

JavaScript Boolean Methods

Method Description

toSource() returns the source of Boolean object as a string.

toString() converts Boolean into String.

valueOf() converts other type into Boolean.

JavaScript Debugging

Sometimes a code may contain certain mistakes. Being a scripting language,


JavaScript didn't show any error message in a browser. But these mistakes can
affect the output.

The best practice to find out the error is to debug the code. The code can be
debugged easily by using web browsers like Google Chrome, Mozilla Firebox.
JavaScript Debugging Example

Here, we will find out errors using built-in web browser debugger. To perform
debugging, we can use any of the following approaches:

o Using console.log() method


o Using debugger keyword

Using console.log() method

The console.log() method displays the result in the console of the browser. If there
is any mistake in the code, it generates the error message.

50.5M
928
HTML Tutorial

Let's see the simple example to print the result on console.

1. <script>
2. x = 10;
3. y = 15;
4. z = x + y;
5. console.log(z);
6. console.log(a);//a is not intialized
7. </script>

Output:

To open the console on browser, press F12 key.


Using debugger keyword

In debugging, generally we set breakpoints to examine each line of code step by


step. There is no requirement to perform this task manually in JavaScript.

JavaScript provides debugger keyword to set the breakpoint through the code
itself. The debugger stops the execution of the program at the position it is
applied. Now, we can start the flow of execution manually. If an exception occurs,
the execution will stop again on that particular line.

1. <script>
2. x = 10;
3. y = 15;
4. z = x + y;
5. debugger;
6. document.write(z);
7. document.write(a);
8. </script>

Output:

You might also like