Introduction and practice examples of JavaScript

JS

Contributed: by Ms Arifa Orfan

__________________________________________________________________________________

 

It’s useful to start with a short overview of the language’s history. JavaScript was created in 1995 by Brendan Eich while he was an engineer at Netscape. JavaScript was first released with Netscape 2 early in 1996. It was originally going to be called LiveScript, but it was renamed in an ill-fated marketing decision that attempted to capitalize on the popularity of Sun Microsystem’s .

1) What is JavaScript?
JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.
The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

2)Name some JavaScript features ?
Following are the features of JavaScript −
• JavaScript is a lightweight, interpreted programming language.
• JavaScript is designed for creating network-centric applications.
• JavaScript is complementary to and integrated with Java.
• JavaScript is complementary to and integrated with HTML.
• JavaScript is open and cross-platform

3)What are the advantages of using JavaScript?
Following are the advantages of using JavaScript −
• Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

4)What are disadvantages of using JavaScript?

We can not treat JavaScript as a full fledged programming language. It lacks the following important features −
• Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
• JavaScript can not be used for Networking applications because there is no such support available.
• JavaScript doesn’t have any multithreading or multiprocess capabilities.

5)Is JavaScript a case-sensitive language?
Yes! JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

6)How can you create an Object in JavaScript?
JavaScript supports Object concept very well. You can create an object using the object literal as follows –
Var emp={
Name:”Mohammad”,
Age: 21
}

7)How can you read properties of an object in JavaScript?

You can write and read properties of an object using the dot notation as follows

//Getting object properties
Emp.name //==> Mohammad
Emp.age //==> 21
// Setting Object properties
Emp.name =”Ahamd” //Ahmad
Emp.age =20 //20

8)How can you create an Array in JavaScript?

You can define arrays using the array literal as follows
Var x = [];
Var y = [1,2,3,4,5,6,,9,8];

9)What is a named function in JavaScript? How to define a named function?

function named(){
// do some stuff here
}
10)What many types of function JavaScript support?
A function in JavaScript can be either named or anonymous.

11)How to define a anonymous function?
An anonymous function can be defined in similar way as a normal function but it would not have any name.

12)Can you assign a anonymous function to a variable ?
Yes! An anonymous function can be assigned to a variable.

13)Can you pass a anonymous function as an argument to another function?
Yes! An anonymous function can be passed as an argument to another function.

14)What is arguments object in JavaScript?
JavaScript variable arguments represents the arguments passed to a function

15)How can you get the type of arguments passed to a function?
Using typeof operator, we can get the type of arguments passed to a function. For example –
function func(x){
Console.log(typeof x, argument.length);
}
Func(); //“undefined”,0
Func(1); // “number”,1
Func(“1”,”2”,”3”); // “number”,3

16)How can you get the reference of a caller function inside a function?
The arguments object has a callee property, which refers to the function you’re inside of. For example –
Function myfunction(){
Return arguments .callee;
}
Myfunction();

17)What is the purpose of ‘this ‘ operator in JavaScript?
We use this similar to the way we use pronouns in natural languages like English and French. We write, “Hadisa is running fast because she is trying to catch the train.” Note the use of the pronoun “she.” We could have written this: “Hadisa is running fast because Hadisa is trying to catch the train.” We don’t reuse “Hadisa” in this manner, for if we do, our family, friends, and colleagues would abandon us. Yes, they would. Well, maybe not your family, but those of us with fair-weather friends and colleagues. In a similar graceful manner, in JavaScript, we use the this keyword as a shortcut, a referent; it refers to an object; that is, the subject in context, or the subject of the executing code. Consider this example:
function doSomething(){
This.style.color=’#cc0000’;
}

18)What are the valid scope of a variable in JavaScript?
The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
• Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code.
• Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Which type of variable among global and local, takes precedence over other if names are same?
A local variable takes precedence over a global variable with the same name.
19)What is callback?
A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.

20)What is closure?
Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.
Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them
Function create(){
Var counter=0;
Return{
Increment: function(){
Counter++;
},
Print: function(){
Console.log(counter);
}
}
}
Var c=create();
C.increment();
c.print(); //1

21)Which built-in method returns the character at the specified index?
charAt() method returns the character at the specified index.
Str=sicsr
document.write(”
“+ str.charAt(3).bold())

22)Which built-in method combines the text of two strings and returns a new string ?
concat() method returns the character at the specified index.

23)Which built – in method returns the lengths the index within the calling string object of the first occurrence of the specified value?

indexOf() method returns the index within the calling String object of the first occurrence of the specified value, or −1 if not found.
e.g:
str=sicsr
document.write(”
“+ str.indexOf(‘c’))

24)Which built-in methods returns the length of the string ?
length() method returns the length of the string.
e.g:
document.write(”
“+ str.length)

25)Which built –in method adds one or more elements to end of an array and returns the new length of the array?
push() method adds one or more elements to the end of an array and returns the new length of the array.
And pop() method removes the last element from an array and returns that element.

26)Which built –in method reverses the order of the elements of an array?
reverse() method reverses the order of the elements of an array −− the first becomes the last, and the last becomes the first.

27)Wich built-in method sort the elements of an array?
sort() method sorts the elements of an array.

28)Which built –in method returns the calling string value converted to lowercase?
toLowerCase() method returns the calling string value converted to lower case.
And toUpperCase() method returns the calling string value converted to upper case.

29)Which built –in method returns the characters in a string beginning at the specified location?
substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

30)Which built –in method returns the string representation of the number’s value?
toString() method returns the string representation of the number’s value.

31)What are the variable naming conventions in javascript ?
While naming your variables in JavaScript keep following rules in mind.
You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
JavaScript variable names are case sensitive. For example, Name and name are two different variables.

32)What typeof operator?
The “typeof” operator in JavaScript allows you to probe the data type of its operand, such as whether a variable is string, numeric, or even undefined. The below simple example alerts the data type of the variable “myvar”
e.g

var myvar =5
alert(typeof myvar) //alerts “number”

34)What is Date object in javaScript?
The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ).
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
e.g

d=new Date()
document.write(d.getDate()+”
“)
document.write(d.getHours()+”
“)
document.write(d.getTime()+”
“)
/*******************************************/
/*
d.setDate()
d.setHours()
d.setTime()
*/
/******************************************/

35)What is Number object in JavaScript?
he Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.
Syntax −
Creating a number object –
Var a1=new Number(number);
If the argument cannot be converted into a number, it returns NaN (Not-a-Number).

36)Write a JavaScript Program to print a simple welcome message to the user?

Code:

document.write(”

Welcome to the world of JavaScript!

“)

37)Write a JavaScript program to print a static timetable for an airline company?

Code:

document.write(”

“) document.write(“”)
document.write(”
“)
document.write(”
“)
document.write(”
“)
document.write(”
“)document.write(”
“)
document.write(”

Fly India international flights schedules
Fight No Source Destination Arival Time Departure time Via JF78533 Pune kabul 6:50am 4:00pm Delhi JF67533 Delhi Stockholm 7:15am 6:00am Dubai JF45533 Banglore Bangkok 7:15am 12:30pm Mumbai JF77533 Delhi Istanbul 7:15am 6:00am Direct

“)

38)Write a JavaScript program to accept grade like (A, B, C…) from user and displays a message accordingly.Use Switch statement

var grade= prompt(“Enter your grade in capital letters: “)
switch(grade){
case ‘A’:document.write(“Well done!”)
break

case ‘B’:document.write(“Good Grade!”)
break

case ‘C’:document.write(“Fair Grade!”)
break

case ‘D’:document.write(“Passed!”)
break

case ‘F’:document.write(“Fail!”)
break

default:document.write(“Unknown grade!”)
}

39)Write a JavaScript program to calculate area of Triangle, area of Square and Valume of Cylinder using Switch.

Code:

alert(“Enter (1) for area of triangle, (2) for area of square and (3) for valume of Cylinder!”)
choice= parseInt(prompt(“Enter the chioce: “))
switch(choice){
case 1:
var base= parseInt(prompt(“Enter the base: “))
var height= parseInt(prompt(“Enter the height: “))
var area= 1/2*base*height
document.write(“Area= “+area+”
“)
break

case 2:
var side= parseInt(prompt(“Enter the side of square: “))
var area= side*side
document.write(“Area= “+area+”
“)
break

case 3:
var pi= Math.PI
var h= parseInt(prompt(“Enter the Height of Cylinder: “))
var r= parseInt(prompt(“Enter th radius of Cylinder: “))
var valume;
valume= pi*r*r*h
document.write(“Valume= “+ valume+”
“)
break

default:
document.write(“Invalid option!”)
}

40)Write a JavaScript code to find all numbers divisible by 7 between from ‘0’ to ‘100’.
Code:

var num= 1
var count= 0
while(num<=100){
if (num%7==0){
document.write(num+”
“)
count=count+1
}
num=num+1
}
document.write(“Numbers divisible by 7 : ” + count + ”
“)

41)Write a JavaScript code to find reverse of a number or a string.

Code:

var string= prompt(“Enter a string: “)
rev= ”
index= string.length // Checks the length of the string using length property

for(var i= index; i>0; i–){ //Reverse the string
rev= rev+string[i-1] }
document.write(string + ”
“)
document.write(rev)

42)Write a JavaScript code to print the inatials of your name
Code:

var name= prompt(“Enter Your Name: “)
document.write(“The inatials are: ” + name.charAt(0))
for(var i=0; i<name.length; i++){
if (name.charAt(i)==” “&&name.charAt(i+1) != ” “){
document.write( name.charAt(i+1))
}
}

43)Write a JavaScript code to to sort elements in an Array.(Without using built-in function ‘sort()’)

Code:

arr= Array(33, 24, 78, 90, 55, 44, 97, 38)
var length=8
var index=0
var temp=0
var itr=1

for(itr =1; itr < length; itr++)
{
for(index = 0; index arr[index+1] )
{
// Swapping the elements
temp = arr[index];
arr[index]=arr[index+1];
arr[index+1] = temp;
}
}
}
document.write(arr)

44)Write a js code to accept a character from user and print 10th after that character.
Code:

var ch1= prompt(“Enter a character: “)
var index= string.indexOf(ch1)
if(index<17)
document.write(string.charAt(index+10))
else
document.write(“No more 10th char after ” + ch1)

Copyright © 2016 All Rights Reserved

45)Write a javaScript program when user enter her/his date of birth it can calculate the age ?

<!–
var Drop1,Drop2,Drop3;
function Dropdown1 () {
Drop1=document.myform.dr1.value
}
function Dropdown2 () {
Drop2=document.myform.dr2.value

}
function Dropdown3 () {
Drop1=document.myform.dr1.value
Drop2=document.myform.dr2.value
Drop3=document.myform.dr3.value
document.myform.txt1.value=Drop1+”/”+Drop2+”/”+Drop3

}

function calc(c)
{

if(c==”bt2″){

var sum=0
for (var i=Drop3;i

Days:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Month:

01
02
03
04
05
06
07
08
09
10
11
12

Years:

1900
1950
1955
1960
1966
1970
1980
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016

 

About the author: Arifa Orfan

Leave a Reply

Your email address will not be published.