Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

1. Functions used in JavaScript

The document provides an overview of JavaScript functions, including built-in functions like parseInt(), parseFloat(), isNaN(), and various mathematical operations using the Math object. It explains the syntax, usage, and examples for each function, along with string operations such as length, charAt(), and toUpperCase(). Additionally, it covers the behavior of these functions with different input types and edge cases.

Uploaded by

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

1. Functions used in JavaScript

The document provides an overview of JavaScript functions, including built-in functions like parseInt(), parseFloat(), isNaN(), and various mathematical operations using the Math object. It explains the syntax, usage, and examples for each function, along with string operations such as length, charAt(), and toUpperCase(). Additionally, it covers the behavior of these functions with different input types and edge cases.

Uploaded by

salwa siddiqui
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.


JavaScript provides several built-in functions.

parseInt()
The parseInt() function parses a string and returns an integer:
Syntax:
parseInt(string)
parseInt(string, radix)
Example:
document.write(parseInt("100")) //100
document.write(parseInt("xyz") // NaN
A radix parameter specifies the number system to use:
– It is Optional.
– Default is 10.
– A number (2 to 36) specifying the number system.
– If the value of the radix is less than 2 or greater than 36 then NaN is returned.
– 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal.
– If the radix is omitted then 10 is taken as the default.
– If the string begins with "0x", the radix is 16 (hexadecimal)
– If the string begins with any other value, the radix is 10 (decimal)
– Only the first number in the string is returned!
– Leading and trailing spaces are allowed.
– If the first character cannot be converted to a number, parseInt() returns NaN.
Example:
document.write(parseInt("11", 2)) //3
document.write(parseInt("11", 8)) //9
document.write(parseInt("11", 10)) //11
document.write(parseInt("11", 16)) //17

parseFloat( )
The parseFloat() function parses a string and returns a floating point number which use base 10:
Syntax:
parseFloat(value)
Example:
document.write(parseFloat("100")) //100
document.write(parseFloat("33.33")) //33.33

– If the first character cannot be converted, NaN is returned.


– Leading and trailing spaces are ignored.
– Only the first number found is returned.
– NaN if no number is found.

Page 1 of 16
isNaN()
It returns true, if the object is NOT a number, it returns false, if the object is a number.
Syntax:
isNaN(value)
Example:
document.write(isNaN(5)) // false
document.write(isNaN("55")) // false, "55" is converted to the number 55
document.write(isNaN("six")) // true

– In JavaScript NaN is short for "Not-a-Number".


– The isNaN() method returns true if a value is NaN.
– The isNaN() method converts the value to a number before testing it.
– If we provide NaN as an input to any mathematical operation the result will be NaN.
document.write(NaN+5) //NaN

valueOf( )
It returns the value of the variable.
Syntax:
string.valueOf()
Example:
var X=365
document.write(X.valueOf( )) //365

var str="Hello"
result=str.valueOf( )
document.write(result) //Hello

– It does not accept any parameter.


– It returns the primitive value of a string.
– It does not change the original string.
– It can be used to convert a string object into a string.

isFinite( )
isFinite() returns true if a value is a finite number.
Syntax:
isFinite(value)
Example:
document.write(isFinite(365)) //true
document.write(isFinite("365")) //true
– It returns a Boolean value
– It returns true if a value is a finite number.
– It returns false if the value is +infinity, -infinity, or NaN
– Javascript has the special values +Infinity and -Infinity
document.write(-1/0) // -Infinity
Page 2 of 16
document.write(+1/0) // Infinity

– +Infinity is a number that represents positive infinity.


– -Infinity is a number that represents negative infinity.
– A number reaches Infinity when it exceeds the upper limit for a number: 1.797693134862315E+308.
– A number reaches -Infinity when it exceeds the lower limit for a number: -1.797693134862316E+308.

We can test +Infinity, -Infinity and NaN values using isFinite() function
– document.write(isFinite(1/0)) // false
– document.write(isFinite(-1/0)) // false
– document.write(isFinite(NaN)) // false
– document.write(isFinite(-Infinity)) // false
– document.write(isFinite(Infinity)) // false

Number( )
– The Number() method converts a value to a number.
– If the value cannot be converted, NaN is returned.
Syntax
Number(value)
Example:
document.write(Number(999)); //999
document.write(Number("Hello John")); //NaN

– Returns the value as a number.


– Numbers are returned as-it is.
– For strings, returns a number or NaN.
– If the value cannot be converted to a number, NaN is returned.
– If no value is provided, 0 is returned.
– For booleans, true turns into 1; false turns into 0.
– For dates, returns milliseconds since January 1, 1970 00:00:00.
– undefined turns into NaN.
– null turns into 0.
– Leading and trailing whitespace/line terminators are ignored.
– Parsing failure results in NaN.
– Leading and trailing whitespace/line terminators are ignored.
– A leading 0 digit does not cause the number to become an octal literal
– + and - are allowed at the start of the string to indicate its sign
– Infinity and -Infinity are recognized as literals. In actual code, they are global variables.
– Empty or whitespace-only strings are converted to 0.
– Numeric separators are not allowed.

String( )
String( ) method is used to convert any type to string value.
Syntax:

Page 3 of 16
String(value)
Example:
var Str=String(100+200)
document.write(Str) //300
document.write(typeof(Str)) //string

Boolean( )
Boolean( ) method is used to find out if an expression (or a variable) is true.
Syntax:
Boolean(variable/expression)
Example:
document.write(Boolean(0)) //returns false
document.write(Boolean(1)) //returns true
document.write(Boolean("hello")) //returns true

– The Boolean value of 0 (zero) is false


– The Boolean value of -0 (minus zero) is false
– The Boolean value of "" (empty string) is false
– The Boolean value of undefined is false
– The Boolean value of null is false
– The Boolean value of false is false
– The Boolean value of NaN is false

Mathematical operations
JavaScript Math object perform the common mathematical operations.

Math.round (x)
– It returns the rounded value of passing number to its nearest integer.
– 2.49 will be rounded down (2), and 2.5 will be rounded up (3).
Syntax:
Math.round(x)
Example:
document.write(Math.round (5.7)) //returns 6
document.write(Math.round (5.49)) //returns 5

Math.pow (x,y)
– It returns the power of x based on y.
Syntax:
Math.pow(x, y)
Example:
document.write(Math.pow(5,2)) //returns 25
document.write(Math.pow(3,4)) //returns 81
Page 4 of 16
Math.sqrt(x)
– It returns the square root of x.
– NaN if the number negative.
Syntax:
Math.sqrt(x)
Example:
document.write(Math.sqrt(25)) // returns 5
document.write(Math.sqrt(225)) //returns 15

Math.ceil(x)
– It returns the greater or equal to integer value of x.
– The nearest integer to the number rounding UP
Syntax:
Math.ceil(x)
Example:
document.write(Math.ceil(4.1)) //returns 5
document.write(Math.ceil(5.9)) //returns 6

Math.floor (x)
– It returns the less or equal to integer value of x.
– The nearest integer to the number, rounding DOWN.
Syntax:
Math.floor(x)
Example:
document.write(Math.floor(4.1)) //returns 4
document.write(Math.floor(5.9)) //returns 5

Math.max()
– The Math.max() method returns the number with the highest value.
– The highest number of the arguments.
– - Infinity if no arguments are given.
– NaN if one of the arguments is not a number.
Syntax:
Math.max(n1, n2,...)
Example:
document.write(Math.max(0, 150, -30, 20, 38)); // 150

Math.min()
– The Math.min() method returns the number with the lowest value.
– The lowest number of the arguments.
– Infinity if no arguments are given.
– NaN if one of the arguments is not a number.

Page 5 of 16
Syntax:
Math.min(n1, n2,...)
Example:
document.write(Math.min(0, 150, -30, -20, 38)); // -30

Math.random()
– Math.random() returns a random number between 0 (inclusive), and 1 (exclusive).
Syntax:
Math.random()
Example:
document.write(Math.random()) // 0.6138888930340729
document.write(Math.random()*10) // 5.943257399399435

Math.sign()
– The Math.sign() method retuns whether a number is negative, positive or zero.
– If the number is positive, this method returns 1.
– If the number is negative, it returns -1.
– If the number is zero, it returns 0.
– If the number is negative zero, it returns -0
– If the number is not a number, it returns NaN
Syntax:
Math.sign(x)
Example:
document.write(Math.sign(3)); // 1
document.write(Math.sign(-22)); // -1

Math.abs()
– The Math.abs() method returns the absolute value of a number.
– NaN if the value is not a number.
– 0 if the value is null.
Syntax:
Math.abs(x)
Example:
document.write(Math.abs(-7.25)); // 7.25
document.write(Math.abs("Hello")); // NaN
document.write(Math.abs(33-66)); // 33

Math.PI
– Math.PI returns PI (the ratio of a circle's area to the square of its radius, approximately 3.14)
Syntax:
Math.PI
Example:
var x = Math.PI;
document.write(x) // 3.141592653589793

Page 6 of 16
String Operations
length
– It returns the length of a string including white space(s).
– The length property of an empty string is 0.
Syntax:
string.length
Example:
var str = " ";
document. write(str. length) // it returns 16.

at( )
– The at() method returns an indexed character from a string.
– -1 returns the last character.
– Index is optional. Default is 0.
Syntax:
string.at(index)
Example:
var text = "Indian Schools";
var character = text.at(7);
document.write(character) // S

charAt( )
– The charAt() method returns the character at a specified index (position) in a string.
Syntax:
string.charAt(index)
Example:
var text = "HELLO WORLD";
document.write(text.charAt(0)); // H

charCodeAt( )
– The charCodeAt() method returns the code of the character at a specified index in a string:
Syntax:
string.charCodeAt(index)
Example:
text = "Apple";
code=text.charCodeAt(4)
document.write(code); // 101

codePointAt( )
– The codePointAt() method returns the Unicode value at an index (position) in a string.
– The index of the first position is 0, the second is 1, ....
– Index Optional, Default value = 0.
– charCodeAt() is UTF-16, codePointAt() is Unicode.
Page 7 of 16
– Both methods return an integer representing the UTF-16 code of a character, but
only codePointAt() can return the full value of a Unicode value greather 0xFFFF (65535).
Syntax:
string.codePointAt(index)
Example:
text = "HELLO WORLD";
code = text.codePointAt(0);
document.write(code) // 72

indexOf( )
– The indexOf() method returns the position of the first occurrence of a value in a string.
– It returns -1 if the value is not found.
– This method is case sensitive.
Syntax:
string.indexOf(searchvalue)
string.indexOf(searchvalue, start)
Example:
document.write("welcome".indexOf('e')) // 1
document.write("welcome".indexOf('e',2)) // 6
Str = "Hello world, welcome to the world.";
result = Str.indexOf("World");
document.write(result) // -1

lastIndexOf( )
– The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a
string.
– It searches the string from the end to the beginning.
– It returns the index from the beginning (position 0).
– It returns -1 if the value is not found.
– It is case sensitive.
Syntax:
string.lastIndexOf(searchvalue)
string.lastIndexOf(searchvalue, start)
Example:
text = "Hello planet earth, you are a great planet.";
result = text.lastIndexOf("planet");
document.write(result) // 36
document.write(text.lastIndexOf("Planet")); // -1
document.write(text.lastIndexOf("planet", 10)); // 6

endsWith( )
– The endsWith() method returns true if a string ends with a specified string.
– Otherwise, it returns false.
– The endsWith() method is case sensitive.

Page 8 of 16
– Length is optional, The length of the string to search.
– Default value is the length of the string
Syntax:
string.endsWith(searchvalue)
string.endsWith(searchvalue, length)
Example:
var text = "Hello world";
var result = text.endsWith("World");
document.write(result) // false

startsWith( )
– The startsWith() method returns true if a string starts with a specified string.
– Otherwise it returns false.
– The startsWith() method is case sensitive.
Syntax:
string.startsWith(searchValue)
string.startsWith(searchValue, start)
Example:
var text = "Hello world, welcome to the universe.";
result=text.startsWith("Hello");
document.write(result) //true

toUpperCase( )
– The toUpperCase() method converts a string to uppercase letters.
– It does not change the original string.
Syntax:
string.toUpperCase()
Example:
text = "Hello World!";
result = text.toUpperCase();
document.write(result) // HELLO WORLD!

toLowerCase()
– The toLowerCase() method converts a string to lowercase letters.
– The toLowerCase() method does not change the original string.
Syntax:
string.toLowerCase()
Example:
text = "Hello World!";
result = text.toLowerCase();
document.write(result) // hello world!

Page 9 of 16
concat( )
– It joins two or more strings.
– It does not change the existing strings.
– It returns a new string.
– The concat() method can be used instead of the plus operator.
Syntax:
string.concat(string1, string2, ..., stringX)
Example:
var text1 = "Hello"
var text2 = "World"
document.write(text1.concat( text2)) // HelloWorld!
document.write(text1.concat( " ", text2)) // Hello World!

search( )
– It returns the starting location of passing string otherwise returns -1.
– It returns the index (position) of the first match.
– It returns -1 if no match is found.
– The search() method is case sensitive.
– The search() method cannot take a start position argument.
– The indexOf() method cannot search against a regular expression.
Syntax:
string.search(searchValue)
Example:
var str = "This is my first webpage"
document.write(str. search("first")) // 11

replace( )
– Thís method replaces a specified value with another value in a string:
Syntax:
string.replace(searchValue, newValue)
Example:
str="Please visit My website !";
var n = str. replace("website", "JavaScript");
document.write(n) // Please visit My JavaScript

replaceAll( )
– The replaceAll() method returns a new string with all values replaced.
– The replaceAll() method does not change the original string.
Syntax:
string.replaceAll(searchValue, newValue)
Example:
text = "I love Cats. Cats are very easy to love. Cats are very friendly."
text = text.replaceAll("Cats","Dogs");
Page 10 of 16
document.write(text) // I love Dogs. Dogs are very easy to love. Dogs are very friendly.

substring( )
– It extract the substring by taking the starting and ending position as argument. You can omit ending
position then it will extract the string from starting position to end of the string.
– First character is at index 0.
– end - End position (up to, but not including). If omitted: the rest of the string.

Syntax:
string.substring(start, end)
Example:
var str ="This is my first script in JavaScript"
sub=str.substring(7, 16)
document.write(sub) // returns "my first" as substring

String.fromCharCode( )
– The String.fromCharCode() method converts Unicode values to characters.
– The String.fromCharCode() is a static method of the String object.
Syntax:
String.fromCharCode(n1, n2, ..., nX)
n1, n2, ..., nX are Required. One or more Unicode values to be converted.
Example:
var text = String.fromCharCode(72, 69, 76, 76, 79);
document.write(text) // HELLO

var char = String.fromCharCode(65);


document.write(char) // A

includes( )
– The includes() method returns true if a string contains a specified string.
– Otherwise it returns false.
– The includes() method is case sensitive.
Syntax:
string.includes(searchvalue)
string.includes(searchvalue, start)
Example:
var text = "Hello world, welcome to the IT world.";
var result = text.includes("world");
document.write(result) //true

var text = "Hello world, welcome to the IT world.";


var result = text.includes("world", 15);
document.write(result) //true

Page 11 of 16
match( )
– The match() method matches a string against a regular expression **
– ** If the search value is a string, it is converted to a regular expression.
– The match() method returns an array with the matches.
– The match() method returns null if no match is found.
– The match() method returns an array of matches.
– The search() method returns the position of the first match.
Syntax
string.match(match)
Example:
//A search for "ain" using a string:
text = "The rain in SPAIN stays mainly in the plain";
result=text.match("ain");
document.write(result) ain

//A global search for "ain":


let text = "The rain in SPAIN stays mainly in the plain";
document.write(text.match(/ain/g)) // ain,ain,ain

//A global, case-insensitive search:


let text = "The rain in SPAIN stays mainly in the plain";
document.write(text.match(/ain/gi)); // ain,AIN,ain,ain

padEnd( )
– The padEnd() method pads a string at the end.
– The padEnd() method pads a string with another string (multiple times) until it reaches a given length.
– The padEnd() method is a string method.
– To pad a number, convert the number to a string first.
Syntax:
string.padEnd(length, string)
Example:
text = "5";
padded = text.padEnd(4,"x");
document.write(padded) // 5xxx

padStart( )
– The padStart() method pads a string from the start.
– The padStart() method pads a string with another string (multiple times) until it reaches a given
length.
– Default is space.
Syntax:
string.padStart(length, string)
Example:
text = "8";
padded = text.padStart(3,"#");
Page 12 of 16
document.write(padded) // ##8

repeat( )
– The repeat() method returns a string with a number of copies of a string.
– The repeat() method returns a new string.
– The repeat() method does not change the original string.
Syntax:
string.repeat(count)
Example:
var text = " Hello ISD ";
var result = text.repeat(3);
document.write(result)

replace( )
– The replace() method searches a string for a value or a regular expression.
– The replace() method returns a new string with the value(s) replaced.
– The replace() method does not change the original string.
Syntax:
string.replace(searchValue, newValue)
Example:
var text = "Mr Blue has a Blue house and a Blue car";
var result = text.replace("Blue", "Red");
document.write(result) // Mr Red has a Blue house and a Blue car

slice( )
– The slice() method extracts a part of a string.
– The slice() method returns the extracted part in a new string.
– The slice() method does not change the original string.
– The start and end parameters specifies the part of the string to extract.
– The first position is 0, the second is 1, ...
– A negative number selects from the end of the string.
Syntax:
string.slice(start)
string.slice(start, end)
Example:
var text = "Hello world!";
var result = text.slice(0, 5);
document.write(result) // Hello

var text = "Hello world!";


var result = text.slice(6);
document.write(result) // world!

Page 13 of 16
split( )
– The split() method splits a string into an array of substrings.
– The split() method returns the new array.
– The split() method does not change the original string.
– If (" ") is used as separator, the string is split between words.
– limit are integer that limits the number of splits.
– If the separator parameter is omitted, an array with the original string is returned
Syntax:
string.split(separator)
string.split(separator, limit)
Example:
text = "How are you doing today?";
myArray = text.split(" ");
document.write(myArray) // How,are,you,doing,today?

substr()
– The substr() method extracts a part of a string.
– The substr() method begins at a specified position, and returns a specified number of characters.
– The substr() method does not change the original string.
– length - The number of characters to extract. If omitted, it extracts the rest of the string
– To extract characters from the end of the string, use a negative start position.
Syntax:
string.substr(start)
string.substr(start, length)
Example:
var text = "Hello world!";
var result = text.substr(2);
document.write(result) // llo world!

substring( )
– The substring() method extracts characters, between two indices (positions), from a string, and
returns the substring.
– The substring() method extracts characters from start to end (exclusive).
– The substring() method does not change the original string.
– If start is greater than end, arguments are swapped: (4, 1) = (1, 4).
– Start or end values less than 0, are treated as 0.
– If "start" is less than 0, it will start from index 0
Syntax:
string.substring(start)
string.substring(start, end)
Example:
var text = "Hello world!";
var result = text.substring(1, 4);
document.write(result) // ell

Page 14 of 16
trim( )
– The trim() method removes whitespace from both sides of a string.
– The trim() method does not change the original string.
Syntax:
string.trim()
Example:
text = " Hello World! ";
document.write(text.length) // 27
result1 = text.trim();
document.write(result1) // Hello World!
document.write(result1.length) // 12

trimStart( )
– The trimStart() method removes whitespace from the beginning of a string.
– The trimStart() method does not change the original string.
– The trimStart() method works like trim(), but removes whitespace only from the start of a string.
Syntax:
string.trimStart()
Example:
text = " Hello World! ";
result2 = text.trimStart();
document.write(result2) // Hello World!
document.write(result2.length) // 20

trimEnd( )
– The trimEnd() method removes whitespace from the end of a string.
– The trimEnd() method does not change the original string.
– The trimEnd() method works like trim(), but removes whitespace only from the end of a string.
Syntax:
string.trimEnd()
Example:
text = " Hello World! ";
result3 = text.trimEnd();
document.write(result3) // Hello World!
document.write(result3.length) // 19

Page 15 of 16
Name Description
charAt() Returns the character at a specified index (position)
charCodeAt() Returns the Unicode of the character at a specified index
concat() Returns two or more joined strings
constructor Returns the string's constructor function
endsWith() Returns if a string ends with a specified value
fromCharCode() Returns Unicode values as characters
includes() Returns if a string contains a specified value
indexOf() Returns the index (position) of the first occurrence of a value in a string
lastIndexOf() Returns the index (position) of the last occurrence of a value in a string
length Returns the length of a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a value, or a regular expression, and returns the matches
prototype Allows you to add properties and methods to an object
repeat() Returns a new string with a number of copies of a string
replace() Searches a string for a pattern, and returns a string where the first match is replaced
replaceAll() Searches a string for a pattern and returns a new string where all matches are replaced
search() Searches a string for a value, or regular expression, and returns the index (position) of the
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
substr() Extracts a number of characters from a string, from a start index (position)
substring() Extracts characters from a string, between two specified indices (positions)
toLocaleLowerCase() Returns a string converted to lowercase letters, using the host's locale
toLocaleUpperCase() Returns a string converted to uppercase letters, using the host's locale
toLowerCase() Returns a string converted to lowercase letters
toString() Returns a string or a string object as a string
toUpperCase() Returns a string converted to uppercase letters
trim() Returns a string with removed whitespaces
trimEnd() Returns a string with removed whitespaces from the end
trimStart() Returns a string with removed whitespaces from the start
valueOf() Returns the primitive value of a string or a string object

Page 16 of 16

You might also like