SlideShare a Scribd company logo
Lecture 2
In this lecture we will learn
   1. Arrays
   2. Expressions and Operators
   3. Functions
   4. If-else construct
   5. Switch Construct
   6. loop constructs
       •  For
       •  While
       •  do-while


More about data types

As I told in my previous lecture, we can declare a variable by

var variable name;

for example:

      var x;

The variable 'x' can store integers, characters, string, float, boolean.

There are five types of data or five data types in Javascript.
Integer
character
string
float
boolean

For all the data types, there is a common keyword var.
boolean values are only true or false.

String is a sequence (연달아 일어남, 연속) of characters enclosed (둘러싸다) inside
double quotes (“ “). For example “hello” .

Integer is a numeric (수) value without decimal. For example 2

Float is a numeric value with decimal. For example 2.5 or 2.0

character is a single character enclosed (둘러싸다) inside single quote (' '). For
example 'a'.
Arrays

Like other programming languages, Javascript supports creating arrays.

An array is a collection of data of same type.

By data of same type, I mean, all the data can be either integer or character or
float or string or boolean but not a combination (결합, 짝맞춤, 배합) of either ([긍정
문에서] (둘 중) ) of these.

Like C language, starting index is 0.

For example:
<body>
      <script language="JavaScript">
      <!--
             var myArray = new Array (5);
             myArray [0] = 0;
             myArray [1] = 1;
             myArray [2] = 2;
             myArray [3] = 3;
             myArray [4] = 4;
             myArray [5] = 5;


             var secondArray = new Array(6,7,8,9);


             // printing the elements of the first array
             document.write("The elements of myArray are <br>");
             document.write(myArray[0] + "<br>");
             document.write(myArray[1] + "<br>");
             document.write(myArray[2] + "<br>");
             document.write(myArray[3] + "<br>");
             document.write(myArray[4] + "<br>");
             document.write(myArray[5] + "<br>");


             printing the elements of the second array
             document.write("The elements of SecondArray are <br>");
document.write(secondArray[0] + "<br>");
                document.write(secondArray[1] + "<br>");
                document.write(secondArray[2] + "<br>");
                document.write(secondArray[3] + "<br>");


       // -->
       </script>
</body>

There are 2 ways of declaring arrays in the above example.
  1. var array_name = new Array (size of array);
     array_name[0] = value1;
     array_name[1] = value2;
     array_name[2] = value3;
     .
     .
     .
     array_name[size of array] = valuen;

    2. var array_name = new Array (value1, value12 , value3 ,.....,valuen);

Expressions and Operators

Expression is a sequence (연달아 일어남, 연속) of operators and operands.

For example: 2 + 3 .
The above expression consist of 2 operands and 1 operator.
•  + is an operator
•  2 and 3 are operands.

Another example: z = x + y
The above expression consist of 3 operands and 2 operators.

•   + and = are operators. (= is called as assignment operator)
•   x, y and z are operands.

There are 4 types of expressions.
  1. Arithmetic expression
  2. Logical expression
  3. String Expression
  4. Relational expression
Arithmetic Expression

Expression formed using arithmetic operator are called as arithmetic expression.
There are 5 types of Arithmetic operators.
  1. addition (+)
  2. Subtraction (-)
  3. Multiplication (*)
  4. Division (/) - gives the quotient of division operation.
  5. modulus (%) - gives the remainder of division operation

Relational expression

Expressions formed using comparison operator are called as relational expression.
There are 6 types of Comparison operator.
  1. equal to ( == )
  2. not equal to ( != )
  3. Less than ( < )
  4. Less than or equal to ( <= )
  5. greater than ( > )
  6. greater than or equal to ( >=)

Return value of a relational expression is boolean i.e. true or false.

Logical Expression

Logical expressions are used to combine (결합, 짝맞춤, 배합) different
comparisons. There are 2 types of logical operators.
   1. Logical AND (&&)
   2. Logical OR (||)

For example:

a = (2==3);             ---------------------- (1)
c = (2 != 3);           ---------------------- (2)
e = a && c              ---------------------- (3)

Equation (1) and (2) are relational expression.
Equation (3) is a logical expression.

Logical expression also return boolean values i.e. True or false.

String Expression

Expression formed using Strings and '+' operator are called as String expression.
'+' operator has a dual (둘의;둘을 나타내는, 양자의 ) functionality. When '+'
operator is used with numbers it functions as an arithmetic operator. When '+'
operator is used with strings it functions as a concatenation operator.

Example of '+' as concatenation operator:

var name = “ huh”;
var greeting = “Welcome”;
var welcome = greeting + name;

welcome variable contains “Welcome huh”.

Operator Precedence(앞섬 )

Arithmetic operators has the highest priority (앞섬 ). After arithmetic operator
comes comparison operator and then comes logical operator.

Within ((장소·시간·거리·범위·한계 등) ) each group, operators have priority or
precedence. For example, within the arithmetic operators, '%' has highest
priority, followed by '*' and '/' and then at the end is '+' and '-'.

The priority of arithmetic operator is
  1. '%'
  2. '*', '/'
  3. '+', '-'

Remember these rules
  1. Operators are executed in the order of their priority, i.e. operators with
     highest priority are executed first.
  2. Operators having same priority are executed in Left to right order.
   3. you can override (보다 우위에 서다) operator priority by enclosing (둘러싸다)
      an expression inside parenthesis (괄호, 소괄호 ).

For example:
      var c = 5/9 * F – 32;              ----------------- (1)

In the above expression we are converting (변하게 하다, 전환하다) Fahrenheit (화씨
의 ) to Celsius (섭씨의 ).

If F = 50, then
      var c = 5/9 * 50 – 32;

There are 3 operators on RHS: '/', '*', '-'. Among (…의 사이에, …의 가운데에, …에 둘
러싸여 ) '/', '*', '-' operators, '/' and '*' have highest priority. That means either
of '/' or '*' will be executed first.

'/' and '*' have equal priority, that means, they will evaluated from left to right.

In equation (1), '/' appear on the left, so first '/' operation is executed. That
means 5/9 is executed first, and 5/9 = 0.556
                  var c = 0.556 * 50 - 32

After '/' comes '*', that means 0.56 * 50 = 27.8
                   var c = 27.8 -32

And then comes '-', that means 27.8 – 32 = -4.2
                var c = -4.2

If we apply parenthesis around F – 32 i.e
            var c = 5 / 9 * (F - 32)     ------------------- (2)

If F = 50, then
            var c = 5 /9 * (50 -32)

Rule 3 is applied first, parenthesis are always evaluated first, that means (50 –
32) = 18.
      var c = 5 /9 * 18

Now rule 2 is applied, because '/' and '*' have same priority. This means, execute
from left to right.
      var c = 0.556 * 18

finally answer is
       var c = 10.

Functions
            Like many other programming languages, Javascript also support
functions. A function is a self (자기, 자신 ) contained (억제[자제]하는, 조심스러운)
operation that can be called by function name. If function expects some input
parameters (【수학·컴퓨터】 파라미터, 매개 변수 ) then pass few parameters also.
To call a function, you simply use the following form:
            functionName (argument1, argument2, argument3,.............);


If a function has no input arguments, you still need parenthesis , for example:
            functionName ();
Also, if a function returns some value, you can use the function call to assign (배
당하다) the returned value to some variable, for example:
            var returnValue = functionName ();


Functions are of two types,
   1. System Defined Functions
   2. User Defined Functions


System defined functions are those which are provided by the system, whereas
User defined functions are those for which are made by the user.
An example of System defined function
<body>
         <script language="Javascript">
         <!--
                  window.alert("How are you");
         // -->
         </script>
</body>


Output should be a pop-up dialog with message, "How are you".
The above Javascript code, uses a system defined function,window.alert().
Window is an object. Function alert() is provided by window object.
Confirming with User
      There is another function, which you can be used to ask a question from
user, and get his response (대답) as True or False. The name of the function is
window.confirm(); Window object provides confirm() function, which displays a
dialog box containing text message, and provides two options, "OK" and "Cancel".


This function also returns true or false, depending upon what user clicks. If user
clicks "OK", confirm() returns true, and if user clicks "Cancel", then confirm()
returns false.


For example:
<body>
         <script language="JavaScript">
         <!--
                  var result=window.confirm("How are you");
                  document.write(result);
         // -->
         </script>
</body>


Output should be "true", if you click "Ok" or "false', if you click "Cancel".
Taking input from User
            Sometimes we may need to take some input from the user. We can
ask a user to enter his name or to enter a number. Javascript provides a function
window.prompt(). 'window' is an object in Javascript and prompt() is a function of
window object.


To understand window.prompt(), here is an example:
      <body>
            <script language=”Javascript”>
                  var name = window.prompt(“enter your name”);
                  window.alert(“welcome ” + name);
            </script>
      <body>




Creating your own Functions
                                 Like I told above, functions are of two types,
System defined functions and User defined functions. We have already discussed
about System Defined Functions, Now we will discuss about User defined
functions.


Creating a User Defined function goes like this
function functionName()
{
statement1;
     statement2;
     .
     .
     .
     statementn;
}


For example:


<HTML>
<HEAD>
         <script language="JavaScript">
                function displayHello()
                {
                         document.write("Hello");
                }
         </script>
</HEAD>
<BODY>


         <script language="JavaScript">
                displayHello();
         </script>


</BODY>
</HTML>


In the above program, I have declared a function “displayHello()” in the head
section of the document. Function “displayHello()” is called in the body section of
the document.
Passing an Argument to Your Functions

                        Arguments are needed in a function to pass (유월절 ) the
values. To create a function that accepts arguments, you must specify names for
each argument in the argument definition.
Syntax of function declaration with input arguments,
function functionName(argumentName1)
{
     statement1;
     statement2;
     .
     .
     .
     statementn;
}


For example:
<HTML>
<HEAD>
         <script language="JavaScript">
                function square(num)
                {
                        var result=num * num;
                        document.write(result);
                }
         </script>
</HEAD>
<BODY>


         <script language="JavaScript">
                square(10);
         </script>


</BODY>
</HTML>
Return Values From Function
             Now, we will discuss another example where function will return a
value. In the previous example, our function received a number, the square of
that number was computed, and displayed. But now, our function will receive a
number, compute the square and return the square back.


To return a value, return command is used.


Syntax:
function functionName()
{
     statement1;
     statement2;
     .
     .
     statementn;
     return value;
}


For example:


<HTML>
<HEAD>
          <script language="JavaScript">
                 function square(num)
                 {
                          var result=num * num;
                          return result
                 }
          </script>
</HEAD>
<BODY>
<script language="JavaScript">
                var ans=square(10);
                document.write(ans);
        </script>


</BODY>
</HTML>


Passing Multiple Parameters to Your Function
                  In the Example above, we discussed about passing single
argument, now we will discuss about how to pass more than one argument. It is
very simple similar to the code above.


function functionName(argument1, argument2, argument3,......................)


We will write a program that passes two arguments to a function, that function
multiples the value contained in those two arguments, and returns back the
result.


<HTML>
<HEAD>
        <script language="JavaScript">
                function multiply(num1,num2)
                {
                         var result=num1 * num2;
                         return result;
                }
        </script>
</HEAD>
<BODY>


        <script language="JavaScript">
                var ans=multiply(10,20);
                document.write(ans);
</script>


</BODY>
</HTML>

If-Construct

Syntax
     if (condition or comparison expression)
     {
                  Statement1;
                 Statement2;
                 .
                 .
                 .
                 Statementn;

     }
     else
     {

                 Statement11;
                 Statement12;
                 .
                 .
                 .
                 Statement1n;
     }



If condition evaluates (평가하다 ) to true, first block is executed. If condition
evaluates to false, second block is executed.

For example:

     x=2;
     y=3;
     if (x == y)
     {
            document.write (“x and y are equal”);
}
       else
       {
              document.write(“x and y are not equal”);
       }


Another example of If-construct
In this example, we will ask the user for his Id and password. If he enters correct
Id and password, we will welcome him, otherwise an error message is displayed.

<html>
<head>
<script language="javascript">

var   username="user";
var   password="haveaniceday";
var   entered_username=prompt("enter username: ", " ");
var   entered_password=prompt("enter password: ", " ");

if ((entered_username == username) && (entered_password == password))
{
   document.write("You have been Logged in!")
}
else
{
   document.write("Sorry, either the username or password is incorrect.")
}

</script>
</head>

<body>
</body>
</html>


Switch-Case Construct

If we want to use multiple if, which we do when have lot of conditions to check
and do something. For example, If there are 3 types of user: administrator,
developer, and user.

If user enters his password, we display “you have user access”.
If administrator enters his password, we display, “you have administrator access”
If developer enters his password, we display, “You have developer access”
In the above scenario (【연극】 대본 ), we need to user more than 1 If-else. Using
more than 1 if-else can some times become clumsy. We can use switch-case
instead (그 대신에 ) of using more than one if-else.

For example

<html>
<head>
<script language="javascript">

var password_administrator="ice";
var password_developer="snow";
var password_user="water";

var entered_password=prompt("enter the secret code to continue: ", " ");

      switch (entered_password) {
         case "ice":
alert("you have administrator access");
            break
         case "snow":
alert("you have developer access");
            break
         case "water":
alert("you have user access");
            break
         default:
alert("password incorrect!");
            break
      }

</script>
</head>

<body>
</body>
</html>


Looping statements

loops are used when we want a part of code to be repeated (되풀이하다, 반복하다)
till the condition is true. As the condition becomes false, loop terminates (<행동·상
태 등을> 끝내다 ).
There are three types of looping constructs available in Javascript.
  1. For
  2. While
  3. do-while

Syntax of For:
     for (initialize statement; condition; increment/decrement statemtn)
     {
            statement1;
            statement2;
            .
            .
            .
            statementn.
     }



An example of for loop.
<html>
         <head>
                  <title>Associating a Function with a Link</title>
                  <script language="JavaScript">
                  <!--
                           for(var i=0;i<10;i++)
                                  document.write(i+"<br>");
                  // -->
                  </script>
         </head>
         <body">


         </body>
</html>


Output for the above code is display numbers from 0 to 9.


Syntax of while loop
initialize statement;
     while (condition)
     {
           statement1;
           statement2;
           .
           .
           .
           statementn;
           increment/decrement statement;
     }


Following is a while equivalent of the above code.
<html>
         <head>
                  <title>Associating a Function with a Link</title>
                  <script language="JavaScript">
                  <!--
                           var i=0;
                           while (i<10)
                           {
                                      document.write(i+"<br>");
                                      i=i+1;
                           }
                  // -->
                  </script>
         </head>
         </body>
</html>

Exercise:
What is the output of the following program?

<html>
<head>
<script language="javascript">

var hour;
var ampm;

for (hour=1; hour<24; hour++)
{
  if (hour < 12) {ampm="am"}
  if (hour >= 12) {ampm="pm"}

    if (hour < 13)
    {
       document.write(hour + ampm)
    }
    else
    {
       document.write((hour-12) + ampm)
    }
    document.write("<br>");
}

</script>
</head>

<body>
</body>
</html>

In do-while, a block of code is executed first before testing the condition.
Syntax is
do
{
      statement1;
      statement2;
      .
      .
      .
      statementn;
} (condition);

Statements inside do-while are executed at least once irrespective ([보통 다음 성구
로] ) of whether ([간접의문문의 명사절을 이끌어] …인지 어떤지 ) condition evaluates to
true or false.
Here is an example that uses do-while loop, In this example, we ask the user to
enter any number between 1 – 12, and 0 to exit.

The output is name of month corresponding (상응하는, 일치하는, 대응하는) to a
number. i.e. If user enters 1, output is January. if user enters 2, output is
February. If user enters 12, output is December.

<html>
<head>
<script language="javascript">

var requested_month=0;
var MonthArray=
[
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]

document.write("Enter a a number between 1 and 12, and I will tell you the name
of the month.<br>");
do
{
requested_month=prompt("Enter a number between 1 and 12 (or 0 to exit)", 0);
document.write(MonthArray[requested_month] + "<BR>");
} while (requested_month != "0")

</script>
</head>

<body>
</body>

Exercise:
Write the above program with using while loop.

More Related Content

What's hot (20)

C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
Mohamed Ahmed
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
Objective-c Runtime
Objective-c RuntimeObjective-c Runtime
Objective-c Runtime
Pavel Albitsky
 
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
1st CI&T Lightning Talks: Writing better code with Object Calisthenics1st CI&T Lightning Talks: Writing better code with Object Calisthenics
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
Lucas Arruda
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
Mukesh Tekwani
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
Emertxe Information Technologies Pvt Ltd
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
Mahmoud Samir Fayed
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
Array
ArrayArray
Array
Kongu Engineering College, Perundurai, Erode
 
Introduction to Clean Code
Introduction to Clean CodeIntroduction to Clean Code
Introduction to Clean Code
Julio Martinez
 
Personal Perl 6 compiler
Personal Perl 6 compilerPersonal Perl 6 compiler
Personal Perl 6 compiler
Andrew Shitov
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
psaravanan1985
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
stasimus
 
Memory management of datatypes
Memory management of datatypesMemory management of datatypes
Memory management of datatypes
Monika Sanghani
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
Tendayi Mawushe
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26
SynapseindiaComplaints
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Martin Roy Portfolio
Martin Roy PortfolioMartin Roy Portfolio
Martin Roy Portfolio
MartinRalphRoy
 
Files,blocks and functions in R
Files,blocks and functions in RFiles,blocks and functions in R
Files,blocks and functions in R
Vladimir Bakhrushin
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
Mohamed Ahmed
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
1st CI&T Lightning Talks: Writing better code with Object Calisthenics1st CI&T Lightning Talks: Writing better code with Object Calisthenics
1st CI&T Lightning Talks: Writing better code with Object Calisthenics
Lucas Arruda
 
The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196The Ring programming language version 1.7 book - Part 35 of 196
The Ring programming language version 1.7 book - Part 35 of 196
Mahmoud Samir Fayed
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
Introduction to Clean Code
Introduction to Clean CodeIntroduction to Clean Code
Introduction to Clean Code
Julio Martinez
 
Personal Perl 6 compiler
Personal Perl 6 compilerPersonal Perl 6 compiler
Personal Perl 6 compiler
Andrew Shitov
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
stasimus
 
Memory management of datatypes
Memory management of datatypesMemory management of datatypes
Memory management of datatypes
Monika Sanghani
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
Tendayi Mawushe
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26Synapse india complain sharing info about php chaptr 26
Synapse india complain sharing info about php chaptr 26
SynapseindiaComplaints
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 

Viewers also liked (14)

javascript3
javascript3javascript3
javascript3
osman do
 
[Basic HTML/CSS] 6. css - box sizing, display, margin, padding
[Basic HTML/CSS] 6. css - box sizing, display, margin, padding[Basic HTML/CSS] 6. css - box sizing, display, margin, padding
[Basic HTML/CSS] 6. css - box sizing, display, margin, padding
Hyejin Oh
 
[CSS Drawing] Basic Tutorial (라이언 그리기)
[CSS Drawing] Basic Tutorial (라이언 그리기)[CSS Drawing] Basic Tutorial (라이언 그리기)
[CSS Drawing] Basic Tutorial (라이언 그리기)
Hyejin Oh
 
[Basic HTML/CSS] 7. project
[Basic HTML/CSS] 7. project[Basic HTML/CSS] 7. project
[Basic HTML/CSS] 7. project
Hyejin Oh
 
PROGRESS - CSS BASIC
PROGRESS - CSS BASICPROGRESS - CSS BASIC
PROGRESS - CSS BASIC
UKM PROGRESS
 
Web engineering - HTML Form
Web engineering -  HTML FormWeb engineering -  HTML Form
Web engineering - HTML Form
Nosheen Qamar
 
HTML Dasar : #10 Form
HTML Dasar : #10 FormHTML Dasar : #10 Form
HTML Dasar : #10 Form
Sandhika Galih
 
[Basic HTML/CSS] 4. html - form tags
[Basic HTML/CSS] 4. html - form tags[Basic HTML/CSS] 4. html - form tags
[Basic HTML/CSS] 4. html - form tags
Hyejin Oh
 
[Basic HTML/CSS] 3. html - table tags
[Basic HTML/CSS] 3. html - table tags[Basic HTML/CSS] 3. html - table tags
[Basic HTML/CSS] 3. html - table tags
Hyejin Oh
 
Basic css-tutorial
Basic css-tutorialBasic css-tutorial
Basic css-tutorial
mohamed ashraf
 
Basic css
Basic cssBasic css
Basic css
Gopinath Ambothi
 
Java script basic
Java script basicJava script basic
Java script basic
Vithushan Vinayagamoorthy
 
Java script basics
Java script basicsJava script basics
Java script basics
Shrivardhan Limbkar
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
shafiq sangi
 
javascript3
javascript3javascript3
javascript3
osman do
 
[Basic HTML/CSS] 6. css - box sizing, display, margin, padding
[Basic HTML/CSS] 6. css - box sizing, display, margin, padding[Basic HTML/CSS] 6. css - box sizing, display, margin, padding
[Basic HTML/CSS] 6. css - box sizing, display, margin, padding
Hyejin Oh
 
[CSS Drawing] Basic Tutorial (라이언 그리기)
[CSS Drawing] Basic Tutorial (라이언 그리기)[CSS Drawing] Basic Tutorial (라이언 그리기)
[CSS Drawing] Basic Tutorial (라이언 그리기)
Hyejin Oh
 
[Basic HTML/CSS] 7. project
[Basic HTML/CSS] 7. project[Basic HTML/CSS] 7. project
[Basic HTML/CSS] 7. project
Hyejin Oh
 
PROGRESS - CSS BASIC
PROGRESS - CSS BASICPROGRESS - CSS BASIC
PROGRESS - CSS BASIC
UKM PROGRESS
 
Web engineering - HTML Form
Web engineering -  HTML FormWeb engineering -  HTML Form
Web engineering - HTML Form
Nosheen Qamar
 
[Basic HTML/CSS] 4. html - form tags
[Basic HTML/CSS] 4. html - form tags[Basic HTML/CSS] 4. html - form tags
[Basic HTML/CSS] 4. html - form tags
Hyejin Oh
 
[Basic HTML/CSS] 3. html - table tags
[Basic HTML/CSS] 3. html - table tags[Basic HTML/CSS] 3. html - table tags
[Basic HTML/CSS] 3. html - table tags
Hyejin Oh
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
shafiq sangi
 
Ad

Similar to Java script introducation & basics (20)

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
03. Week 03.pptx
03. Week 03.pptx03. Week 03.pptx
03. Week 03.pptx
Vinc2ntCabrera
 
JavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentationJavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentation
M Sajid R
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
BArulmozhi
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfjavascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
AlexShon3
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
H K
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
Fewd week5 slides
Fewd week5 slidesFewd week5 slides
Fewd week5 slides
William Myers
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
JavaScript for beginners
JavaScript for beginners JavaScript for beginners
JavaScript for beginners
Shahrukh Ali Khan
 
Paca java script slid
Paca java script slidPaca java script slid
Paca java script slid
pacatarpit
 
Js tutorial(Basic concepts, running a program ,console,variable,types etc..)
Js tutorial(Basic concepts, running a program ,console,variable,types etc..)Js tutorial(Basic concepts, running a program ,console,variable,types etc..)
Js tutorial(Basic concepts, running a program ,console,variable,types etc..)
reshmy12
 
CSC PPT 13.pptx
CSC PPT 13.pptxCSC PPT 13.pptx
CSC PPT 13.pptx
DrRavneetSingh
 
Unit2wt
Unit2wtUnit2wt
Unit2wt
vamsi krishna
 
Unit2wt
Unit2wtUnit2wt
Unit2wt
vamsitricks
 
csc ppt 15.pptx
csc ppt 15.pptxcsc ppt 15.pptx
csc ppt 15.pptx
RavneetSingh343801
 
Javascript breakdown-workbook
Javascript breakdown-workbookJavascript breakdown-workbook
Javascript breakdown-workbook
HP IT GROUP (TEBIM TEBITAGEM) TTGRT HP E-TİCARET
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
JavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentationJavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentation
M Sajid R
 
Introduction to javascript.ppt
Introduction to javascript.pptIntroduction to javascript.ppt
Introduction to javascript.ppt
BArulmozhi
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfjavascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
AlexShon3
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
H K
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
Paca java script slid
Paca java script slidPaca java script slid
Paca java script slid
pacatarpit
 
Js tutorial(Basic concepts, running a program ,console,variable,types etc..)
Js tutorial(Basic concepts, running a program ,console,variable,types etc..)Js tutorial(Basic concepts, running a program ,console,variable,types etc..)
Js tutorial(Basic concepts, running a program ,console,variable,types etc..)
reshmy12
 
Ad

More from H K (20)

Assignment4
Assignment4Assignment4
Assignment4
H K
 
Assignment3
Assignment3Assignment3
Assignment3
H K
 
Induction
InductionInduction
Induction
H K
 
Solution3
Solution3Solution3
Solution3
H K
 
Solution2
Solution2Solution2
Solution2
H K
 
Mid-
Mid-Mid-
Mid-
H K
 
Assignment4
Assignment4Assignment4
Assignment4
H K
 
Assignment4
Assignment4Assignment4
Assignment4
H K
 
Dm assignment3
Dm assignment3Dm assignment3
Dm assignment3
H K
 
Proof
ProofProof
Proof
H K
 
Resolution
ResolutionResolution
Resolution
H K
 
Assignment description
Assignment descriptionAssignment description
Assignment description
H K
 
Dm assignment2
Dm assignment2Dm assignment2
Dm assignment2
H K
 
Set
SetSet
Set
H K
 
Dm assignment1
Dm assignment1Dm assignment1
Dm assignment1
H K
 
Logic
LogicLogic
Logic
H K
 
Introduction
IntroductionIntroduction
Introduction
H K
 
Assignment 2 sol
Assignment 2 solAssignment 2 sol
Assignment 2 sol
H K
 
Assignment sw solution
Assignment sw solutionAssignment sw solution
Assignment sw solution
H K
 
Violinphoenix
ViolinphoenixViolinphoenix
Violinphoenix
H K
 
Assignment4
Assignment4Assignment4
Assignment4
H K
 
Assignment3
Assignment3Assignment3
Assignment3
H K
 
Induction
InductionInduction
Induction
H K
 
Solution3
Solution3Solution3
Solution3
H K
 
Solution2
Solution2Solution2
Solution2
H K
 
Mid-
Mid-Mid-
Mid-
H K
 
Assignment4
Assignment4Assignment4
Assignment4
H K
 
Assignment4
Assignment4Assignment4
Assignment4
H K
 
Dm assignment3
Dm assignment3Dm assignment3
Dm assignment3
H K
 
Proof
ProofProof
Proof
H K
 
Resolution
ResolutionResolution
Resolution
H K
 
Assignment description
Assignment descriptionAssignment description
Assignment description
H K
 
Dm assignment2
Dm assignment2Dm assignment2
Dm assignment2
H K
 
Set
SetSet
Set
H K
 
Dm assignment1
Dm assignment1Dm assignment1
Dm assignment1
H K
 
Logic
LogicLogic
Logic
H K
 
Introduction
IntroductionIntroduction
Introduction
H K
 
Assignment 2 sol
Assignment 2 solAssignment 2 sol
Assignment 2 sol
H K
 
Assignment sw solution
Assignment sw solutionAssignment sw solution
Assignment sw solution
H K
 
Violinphoenix
ViolinphoenixViolinphoenix
Violinphoenix
H K
 

Recently uploaded (20)

SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 

Java script introducation & basics

  • 1. Lecture 2 In this lecture we will learn 1. Arrays 2. Expressions and Operators 3. Functions 4. If-else construct 5. Switch Construct 6. loop constructs • For • While • do-while More about data types As I told in my previous lecture, we can declare a variable by var variable name; for example: var x; The variable 'x' can store integers, characters, string, float, boolean. There are five types of data or five data types in Javascript. Integer character string float boolean For all the data types, there is a common keyword var. boolean values are only true or false. String is a sequence (연달아 일어남, 연속) of characters enclosed (둘러싸다) inside double quotes (“ “). For example “hello” . Integer is a numeric (수) value without decimal. For example 2 Float is a numeric value with decimal. For example 2.5 or 2.0 character is a single character enclosed (둘러싸다) inside single quote (' '). For example 'a'.
  • 2. Arrays Like other programming languages, Javascript supports creating arrays. An array is a collection of data of same type. By data of same type, I mean, all the data can be either integer or character or float or string or boolean but not a combination (결합, 짝맞춤, 배합) of either ([긍정 문에서] (둘 중) ) of these. Like C language, starting index is 0. For example: <body> <script language="JavaScript"> <!-- var myArray = new Array (5); myArray [0] = 0; myArray [1] = 1; myArray [2] = 2; myArray [3] = 3; myArray [4] = 4; myArray [5] = 5; var secondArray = new Array(6,7,8,9); // printing the elements of the first array document.write("The elements of myArray are <br>"); document.write(myArray[0] + "<br>"); document.write(myArray[1] + "<br>"); document.write(myArray[2] + "<br>"); document.write(myArray[3] + "<br>"); document.write(myArray[4] + "<br>"); document.write(myArray[5] + "<br>"); printing the elements of the second array document.write("The elements of SecondArray are <br>");
  • 3. document.write(secondArray[0] + "<br>"); document.write(secondArray[1] + "<br>"); document.write(secondArray[2] + "<br>"); document.write(secondArray[3] + "<br>"); // --> </script> </body> There are 2 ways of declaring arrays in the above example. 1. var array_name = new Array (size of array); array_name[0] = value1; array_name[1] = value2; array_name[2] = value3; . . . array_name[size of array] = valuen; 2. var array_name = new Array (value1, value12 , value3 ,.....,valuen); Expressions and Operators Expression is a sequence (연달아 일어남, 연속) of operators and operands. For example: 2 + 3 . The above expression consist of 2 operands and 1 operator. • + is an operator • 2 and 3 are operands. Another example: z = x + y The above expression consist of 3 operands and 2 operators. • + and = are operators. (= is called as assignment operator) • x, y and z are operands. There are 4 types of expressions. 1. Arithmetic expression 2. Logical expression 3. String Expression 4. Relational expression
  • 4. Arithmetic Expression Expression formed using arithmetic operator are called as arithmetic expression. There are 5 types of Arithmetic operators. 1. addition (+) 2. Subtraction (-) 3. Multiplication (*) 4. Division (/) - gives the quotient of division operation. 5. modulus (%) - gives the remainder of division operation Relational expression Expressions formed using comparison operator are called as relational expression. There are 6 types of Comparison operator. 1. equal to ( == ) 2. not equal to ( != ) 3. Less than ( < ) 4. Less than or equal to ( <= ) 5. greater than ( > ) 6. greater than or equal to ( >=) Return value of a relational expression is boolean i.e. true or false. Logical Expression Logical expressions are used to combine (결합, 짝맞춤, 배합) different comparisons. There are 2 types of logical operators. 1. Logical AND (&&) 2. Logical OR (||) For example: a = (2==3); ---------------------- (1) c = (2 != 3); ---------------------- (2) e = a && c ---------------------- (3) Equation (1) and (2) are relational expression. Equation (3) is a logical expression. Logical expression also return boolean values i.e. True or false. String Expression Expression formed using Strings and '+' operator are called as String expression. '+' operator has a dual (둘의;둘을 나타내는, 양자의 ) functionality. When '+'
  • 5. operator is used with numbers it functions as an arithmetic operator. When '+' operator is used with strings it functions as a concatenation operator. Example of '+' as concatenation operator: var name = “ huh”; var greeting = “Welcome”; var welcome = greeting + name; welcome variable contains “Welcome huh”. Operator Precedence(앞섬 ) Arithmetic operators has the highest priority (앞섬 ). After arithmetic operator comes comparison operator and then comes logical operator. Within ((장소·시간·거리·범위·한계 등) ) each group, operators have priority or precedence. For example, within the arithmetic operators, '%' has highest priority, followed by '*' and '/' and then at the end is '+' and '-'. The priority of arithmetic operator is 1. '%' 2. '*', '/' 3. '+', '-' Remember these rules 1. Operators are executed in the order of their priority, i.e. operators with highest priority are executed first. 2. Operators having same priority are executed in Left to right order. 3. you can override (보다 우위에 서다) operator priority by enclosing (둘러싸다) an expression inside parenthesis (괄호, 소괄호 ). For example: var c = 5/9 * F – 32; ----------------- (1) In the above expression we are converting (변하게 하다, 전환하다) Fahrenheit (화씨 의 ) to Celsius (섭씨의 ). If F = 50, then var c = 5/9 * 50 – 32; There are 3 operators on RHS: '/', '*', '-'. Among (…의 사이에, …의 가운데에, …에 둘
  • 6. 러싸여 ) '/', '*', '-' operators, '/' and '*' have highest priority. That means either of '/' or '*' will be executed first. '/' and '*' have equal priority, that means, they will evaluated from left to right. In equation (1), '/' appear on the left, so first '/' operation is executed. That means 5/9 is executed first, and 5/9 = 0.556 var c = 0.556 * 50 - 32 After '/' comes '*', that means 0.56 * 50 = 27.8 var c = 27.8 -32 And then comes '-', that means 27.8 – 32 = -4.2 var c = -4.2 If we apply parenthesis around F – 32 i.e var c = 5 / 9 * (F - 32) ------------------- (2) If F = 50, then var c = 5 /9 * (50 -32) Rule 3 is applied first, parenthesis are always evaluated first, that means (50 – 32) = 18. var c = 5 /9 * 18 Now rule 2 is applied, because '/' and '*' have same priority. This means, execute from left to right. var c = 0.556 * 18 finally answer is var c = 10. Functions Like many other programming languages, Javascript also support functions. A function is a self (자기, 자신 ) contained (억제[자제]하는, 조심스러운) operation that can be called by function name. If function expects some input parameters (【수학·컴퓨터】 파라미터, 매개 변수 ) then pass few parameters also. To call a function, you simply use the following form: functionName (argument1, argument2, argument3,.............); If a function has no input arguments, you still need parenthesis , for example: functionName ();
  • 7. Also, if a function returns some value, you can use the function call to assign (배 당하다) the returned value to some variable, for example: var returnValue = functionName (); Functions are of two types, 1. System Defined Functions 2. User Defined Functions System defined functions are those which are provided by the system, whereas User defined functions are those for which are made by the user. An example of System defined function <body> <script language="Javascript"> <!-- window.alert("How are you"); // --> </script> </body> Output should be a pop-up dialog with message, "How are you". The above Javascript code, uses a system defined function,window.alert(). Window is an object. Function alert() is provided by window object. Confirming with User There is another function, which you can be used to ask a question from user, and get his response (대답) as True or False. The name of the function is window.confirm(); Window object provides confirm() function, which displays a dialog box containing text message, and provides two options, "OK" and "Cancel". This function also returns true or false, depending upon what user clicks. If user clicks "OK", confirm() returns true, and if user clicks "Cancel", then confirm() returns false. For example:
  • 8. <body> <script language="JavaScript"> <!-- var result=window.confirm("How are you"); document.write(result); // --> </script> </body> Output should be "true", if you click "Ok" or "false', if you click "Cancel". Taking input from User Sometimes we may need to take some input from the user. We can ask a user to enter his name or to enter a number. Javascript provides a function window.prompt(). 'window' is an object in Javascript and prompt() is a function of window object. To understand window.prompt(), here is an example: <body> <script language=”Javascript”> var name = window.prompt(“enter your name”); window.alert(“welcome ” + name); </script> <body> Creating your own Functions Like I told above, functions are of two types, System defined functions and User defined functions. We have already discussed about System Defined Functions, Now we will discuss about User defined functions. Creating a User Defined function goes like this function functionName() {
  • 9. statement1; statement2; . . . statementn; } For example: <HTML> <HEAD> <script language="JavaScript"> function displayHello() { document.write("Hello"); } </script> </HEAD> <BODY> <script language="JavaScript"> displayHello(); </script> </BODY> </HTML> In the above program, I have declared a function “displayHello()” in the head section of the document. Function “displayHello()” is called in the body section of the document. Passing an Argument to Your Functions Arguments are needed in a function to pass (유월절 ) the
  • 10. values. To create a function that accepts arguments, you must specify names for each argument in the argument definition. Syntax of function declaration with input arguments, function functionName(argumentName1) { statement1; statement2; . . . statementn; } For example: <HTML> <HEAD> <script language="JavaScript"> function square(num) { var result=num * num; document.write(result); } </script> </HEAD> <BODY> <script language="JavaScript"> square(10); </script> </BODY> </HTML>
  • 11. Return Values From Function Now, we will discuss another example where function will return a value. In the previous example, our function received a number, the square of that number was computed, and displayed. But now, our function will receive a number, compute the square and return the square back. To return a value, return command is used. Syntax: function functionName() { statement1; statement2; . . statementn; return value; } For example: <HTML> <HEAD> <script language="JavaScript"> function square(num) { var result=num * num; return result } </script> </HEAD> <BODY>
  • 12. <script language="JavaScript"> var ans=square(10); document.write(ans); </script> </BODY> </HTML> Passing Multiple Parameters to Your Function In the Example above, we discussed about passing single argument, now we will discuss about how to pass more than one argument. It is very simple similar to the code above. function functionName(argument1, argument2, argument3,......................) We will write a program that passes two arguments to a function, that function multiples the value contained in those two arguments, and returns back the result. <HTML> <HEAD> <script language="JavaScript"> function multiply(num1,num2) { var result=num1 * num2; return result; } </script> </HEAD> <BODY> <script language="JavaScript"> var ans=multiply(10,20); document.write(ans);
  • 13. </script> </BODY> </HTML> If-Construct Syntax if (condition or comparison expression) { Statement1; Statement2; . . . Statementn; } else { Statement11; Statement12; . . . Statement1n; } If condition evaluates (평가하다 ) to true, first block is executed. If condition evaluates to false, second block is executed. For example: x=2; y=3; if (x == y) { document.write (“x and y are equal”);
  • 14. } else { document.write(“x and y are not equal”); } Another example of If-construct In this example, we will ask the user for his Id and password. If he enters correct Id and password, we will welcome him, otherwise an error message is displayed. <html> <head> <script language="javascript"> var username="user"; var password="haveaniceday"; var entered_username=prompt("enter username: ", " "); var entered_password=prompt("enter password: ", " "); if ((entered_username == username) && (entered_password == password)) { document.write("You have been Logged in!") } else { document.write("Sorry, either the username or password is incorrect.") } </script> </head> <body> </body> </html> Switch-Case Construct If we want to use multiple if, which we do when have lot of conditions to check and do something. For example, If there are 3 types of user: administrator, developer, and user. If user enters his password, we display “you have user access”. If administrator enters his password, we display, “you have administrator access” If developer enters his password, we display, “You have developer access”
  • 15. In the above scenario (【연극】 대본 ), we need to user more than 1 If-else. Using more than 1 if-else can some times become clumsy. We can use switch-case instead (그 대신에 ) of using more than one if-else. For example <html> <head> <script language="javascript"> var password_administrator="ice"; var password_developer="snow"; var password_user="water"; var entered_password=prompt("enter the secret code to continue: ", " "); switch (entered_password) { case "ice": alert("you have administrator access"); break case "snow": alert("you have developer access"); break case "water": alert("you have user access"); break default: alert("password incorrect!"); break } </script> </head> <body> </body> </html> Looping statements loops are used when we want a part of code to be repeated (되풀이하다, 반복하다) till the condition is true. As the condition becomes false, loop terminates (<행동·상
  • 16. 태 등을> 끝내다 ). There are three types of looping constructs available in Javascript. 1. For 2. While 3. do-while Syntax of For: for (initialize statement; condition; increment/decrement statemtn) { statement1; statement2; . . . statementn. } An example of for loop. <html> <head> <title>Associating a Function with a Link</title> <script language="JavaScript"> <!-- for(var i=0;i<10;i++) document.write(i+"<br>"); // --> </script> </head> <body"> </body> </html> Output for the above code is display numbers from 0 to 9. Syntax of while loop
  • 17. initialize statement; while (condition) { statement1; statement2; . . . statementn; increment/decrement statement; } Following is a while equivalent of the above code. <html> <head> <title>Associating a Function with a Link</title> <script language="JavaScript"> <!-- var i=0; while (i<10) { document.write(i+"<br>"); i=i+1; } // --> </script> </head> </body> </html> Exercise: What is the output of the following program? <html>
  • 18. <head> <script language="javascript"> var hour; var ampm; for (hour=1; hour<24; hour++) { if (hour < 12) {ampm="am"} if (hour >= 12) {ampm="pm"} if (hour < 13) { document.write(hour + ampm) } else { document.write((hour-12) + ampm) } document.write("<br>"); } </script> </head> <body> </body> </html> In do-while, a block of code is executed first before testing the condition. Syntax is do { statement1; statement2; . . . statementn; } (condition); Statements inside do-while are executed at least once irrespective ([보통 다음 성구 로] ) of whether ([간접의문문의 명사절을 이끌어] …인지 어떤지 ) condition evaluates to true or false.
  • 19. Here is an example that uses do-while loop, In this example, we ask the user to enter any number between 1 – 12, and 0 to exit. The output is name of month corresponding (상응하는, 일치하는, 대응하는) to a number. i.e. If user enters 1, output is January. if user enters 2, output is February. If user enters 12, output is December. <html> <head> <script language="javascript"> var requested_month=0; var MonthArray= [ "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] document.write("Enter a a number between 1 and 12, and I will tell you the name of the month.<br>"); do { requested_month=prompt("Enter a number between 1 and 12 (or 0 to exit)", 0); document.write(MonthArray[requested_month] + "<BR>"); } while (requested_month != "0") </script> </head> <body> </body> Exercise: Write the above program with using while loop.