Javascript
Javascript
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>
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
1. if(expression){
2. //content to be evaluated
3. }
Flowchart of JavaScript If statement
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
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
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.}
JavaScript Functions
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"/>
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>
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>
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 template based not class based. Here, we don't create class to get the
object. But, we direct 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)
object={property1:value1,property2:value2.....propertyN:valueN}
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
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
Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
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
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
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
Sonoo
Vimal
Ratan
<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
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>
Jai
Vijay
Smith
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.
flatMap() It maps all array elements via mapping function, then flattens the resul
into a new array.
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.
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
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.
slice() It returns a new array containing the copy of the part of the given 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
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.
<script>
var str="This is string literal";
document.write(str);
</script>
Test it Now
Output:
The syntax of creating string object using new keyword is given below:
<script>
1. var stringname=new String("hello javascript string");
2. document.write(stringname);
3. </script>
Test it Now
Output:
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.
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.
toLocaleLowerCase( It converts the given string into lowercase letter on the basis of host?
) current locale.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?
current locale.
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. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Test it Now
Output:
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:
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
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
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:
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:
1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>
Test it Now
Output:
cde
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
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
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.
toJSON() It returns a string representing the Date object. It also serializes the Dat
object during JSON serialization.
toUTCString() It converts the specified date in the form of string using UTC time zone
Let's see the simple example to print date object. It prints date and time both.
Output:
Current Date and Time: Sun Aug 28 2022 10:25:50 GMT+0530 (India Standard
Time)
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:
Output:
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.
Output:
JavaScript Math
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
Methods Description
ceil() It returns a smallest integer value, greater than or equal to the given number.
floor() It returns largest integer value, lower than or equal to the given number.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
Output:
8.7M
83
Competitive questions on Structures
Square Root of 17 is: 4.123105625617661
Math.random()
Output:
Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
Output:
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.
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.
Output:
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.
Output:
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.
Output:
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:
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:
Constant Description
Let's see the list of JavaScript number methods with their description.
Methods Description
toFixed() It returns the string that represents a number with exact digits after a decima
point.
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.
Property Description
constructor returns the reference of Boolean function that created Boolean object.
Method Description
JavaScript Debugging
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:
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
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:
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: