mercredi 24 juillet 2013
JavaScript While Loop
In JavaScript, WHILE loop has same function as the FOR loop. The Syntax however is bit different. The WHILE Loop will check if a condition is being met, if yes then it will execute the code lines specified within the Brackets, else it will stop the looping process.
The counter variable must be incremented within the code lines to enable the while command to work properly. Unlike the FOR loop, the syntax does not provide a special spot for specifying the increment.
The initial value of the variable must also be specified before the While command.
Syntax
While(Condition)
{
code lines to be executed
}
Simple JavaScript While Loop Example
We will use the same example as used in the last lesson. Here we will achieve the same objective with While Loop instead of the FOR loop. It will help you easily compare both.
Create a mathematical table for the number 5, i.e. multiply it with numbers 1 to 10 and display results.
Js While Loop
Step 1- We declared a variable called 'a' and assigned it a value of 5.
Step 2- We declared a variable called counter and assigned it a value of 1. We called it counter because its value will change every time the loop is run.
Step 3- The condition- Until the condition in the following round brackets is true (counter <= 10), execute the code in the curly brackets below.
Step 4- We then print on the screen, the number 5, multiplication symbol x, the current value of the variable counter and the result of 5 multiplied with the current value of counter.
Step 5- After printing it will increment the value of variable counter and then go back to top of the loop command. Note that unlike the For Loop example in the last lesson, we enter the increment code within the code to be executed.
STEP 6- When the counter variable value becomes 11 and the loop goes back to top, the condition becomes FALSE as 11 is neither 10 nor less than it. So the loop will no longer be executed.
First time the code is executed, 5 x 1 and the result is a *5 which is five.
Now the next time code is executed, all values remain same but the value of the variable counter is incremented by 1 as we instructed in the for command- counter++ which is same as counter = counter+1. So the second time the loop runs, a * counter is 5 * 2 which results in 10.
While loop result
Example-
Make a JavaScript Program for creating/displaying mathematical tables of any number that user wants
Much similar to the example above. Just that here we will ask the user to enter a number through a Prompt PopUp box, whose mathematical table she wants. Instead of incrementing the value of counter variable by 1, we will do it by 2 in this example.
Instead of providing a value for a, here user will enter a value in the prompt box, which we will assign to a.
javascript while loop
Here we increment the value of the variable counter by 2. counter=counter + 2 means, the new value of counter is equal to the old value of counter + 2.
Once the value of counter becomes 11, it no longer meets the condition of < = 10. therefore the loop stops.
Result
A popup box will prompt the user to enter a number.
popup box JS for loops
table result for Javascript for loop
JavaScript Variable Types by Scope
Another way variables are classified in Javascript are by Scope. i.e. whether the variable is usable only within a function or throughout the whole page.
The two types are
Local Variable
Global Variable
Local Variable
A local variable is one that is declared / Created within a function in Javascript. It is usable only within that function, in other words has a local scope. Such variables are deleted, once the function has been executed.
Global Variable
All the variables that are not declared within a function are called Global variables. Can be used anywhere throughout the page and any function or other code can alter its value i.e. they have a global scope.
The two types are
Local Variable
Global Variable
Local Variable
A local variable is one that is declared / Created within a function in Javascript. It is usable only within that function, in other words has a local scope. Such variables are deleted, once the function has been executed.
Global Variable
All the variables that are not declared within a function are called Global variables. Can be used anywhere throughout the page and any function or other code can alter its value i.e. they have a global scope.
JavaScript Variables naming Conventions
In javascript programming, it is useful to give meaningful variable names that are easier to remember, recall and understand. Instead of calling the variable that holds country names 'x', we called it 'countryname', this helps in better programming as when working with thousand of lines of codes, you will forget what x refered to. but the word countryname will tell you what the variable actually holds.
Basic Rules
It can contain letters, numbers and some symbols.
First character of the variable name should be a letter or an underscore. It cannot start with a number.
What cannot be used as Variable names
Javascript reserved words like var, with , .. etc that are used by javascript as commands
Variables names cannot contain blank spaces. if you want to separate words in a variable name, used Underscore '_' Ex. 'student_age'
Ampersand & or the Percent sign % cannot be used.
Variable name cannot start with a number however in later characters(after first one), numbers can be used.
Case Sensitivity
In javascript variable names are case sensitive. Variable names 'studentage', 'Studentage' and 'STUDENTAGE' are considered different variables. Although the letters are same but the case is different in all the three names.
Hungarian notation
JavaScript tutorials
Advance user concept- (you can skip this Paragraph if you want to).
Although variable types are not declared in javascript, it is good programming practice to add a prefix to the variable name describing the type of data you wish to assign with the data. For example, variable studentage will be assigned a numeric value. So we might want to name it num_studentage
a Variable student name that will hold string(text) data might be called str_studentname
Basic Rules
It can contain letters, numbers and some symbols.
First character of the variable name should be a letter or an underscore. It cannot start with a number.
What cannot be used as Variable names
Javascript reserved words like var, with , .. etc that are used by javascript as commands
Variables names cannot contain blank spaces. if you want to separate words in a variable name, used Underscore '_' Ex. 'student_age'
Ampersand & or the Percent sign % cannot be used.
Variable name cannot start with a number however in later characters(after first one), numbers can be used.
Case Sensitivity
In javascript variable names are case sensitive. Variable names 'studentage', 'Studentage' and 'STUDENTAGE' are considered different variables. Although the letters are same but the case is different in all the three names.
Hungarian notation
JavaScript tutorials
Advance user concept- (you can skip this Paragraph if you want to).
Although variable types are not declared in javascript, it is good programming practice to add a prefix to the variable name describing the type of data you wish to assign with the data. For example, variable studentage will be assigned a numeric value. So we might want to name it num_studentage
a Variable student name that will hold string(text) data might be called str_studentname
JavaScript Variables
Variables are an important concept of computer programming in general.
What are Variables?
If you recall school algebra, there were 'x' and 'y'. Sometimes x had a value of 1, you could add 2 to the value of x and then its value became 3. Thus the value of the letter x varied or changed over time. Though back in school it did not make much sense to why we were using X and Y, why all that much algebra? what was the use? Well in programming you will find them to be very useful.
Simply put, a variable is a container of a value. This container has a name, that we call 'variable name' A variable is represented by a letter like 'x' or any other variable name like combination of letters ex 'customername'. Its value can vary.
Imagine an empty box. If you put carrots in it, it is a box of carrots. At another time it may contain potatoes and then it is a box of potatoes. The contents of the box changes or varies at different instances of time. This box or container has a name like 'smallbox'.
Variables in Programming
In Programming, Variables can hold values or expressions(combination of values and variables joined by operators like +, - , etc). Values can be numbers, text and many other kinds of values.
Example customername = 'Jessica', employeesalary = 60,000
The variable customername has a text value containing customer name, while the variable employeesalary has a numeric value of 60,000.
monthlysalary = employeesalary / 12
The value of the variable monthly salary has a value in the form of an expression. divide employeesalary by 12 (no. of months) and you will get the value for this variable.
Why do we use Variables
We use variables to store data. When we need to use that data in calculations or other purposes, we can refer to the data by referring to its container(variable name) instead of writing the data values themselves. In other words variables represent data.
For example
On top right section of every page of our company website we need to display the total number of Desktop Computers we have sold to date. One way to do it is to change the value of total sales every morning on every page of the website. The other way is to refer to the variable 'Total sales' on every page and update the value of the variable 'total sales' in the system memory, and every webpage thus automatically displays the current value of the Total sales by extracting the information from the main system memory.
If you are still not fully clear about variables, don't worry. You will better understand their use as use them in examples in the lessons ahead. Above description is sufficient foundation knowledge and you can move on.
Declaring a Variable in Javascript
To Create / Declare variables in Javascript, we use the var command.
SYNTAX
var variable_name;
There are two ways to declare a variable.
1. Just declare a variable (assign it a value later)
var countryname; This will create a variable called 'countryname' without assigning value to it.
2.Declare a Variable and also assign value to it.
var countryname = "Australia";
What are Variables?
If you recall school algebra, there were 'x' and 'y'. Sometimes x had a value of 1, you could add 2 to the value of x and then its value became 3. Thus the value of the letter x varied or changed over time. Though back in school it did not make much sense to why we were using X and Y, why all that much algebra? what was the use? Well in programming you will find them to be very useful.
Simply put, a variable is a container of a value. This container has a name, that we call 'variable name' A variable is represented by a letter like 'x' or any other variable name like combination of letters ex 'customername'. Its value can vary.
Imagine an empty box. If you put carrots in it, it is a box of carrots. At another time it may contain potatoes and then it is a box of potatoes. The contents of the box changes or varies at different instances of time. This box or container has a name like 'smallbox'.
Variables in Programming
In Programming, Variables can hold values or expressions(combination of values and variables joined by operators like +, - , etc). Values can be numbers, text and many other kinds of values.
Example customername = 'Jessica', employeesalary = 60,000
The variable customername has a text value containing customer name, while the variable employeesalary has a numeric value of 60,000.
monthlysalary = employeesalary / 12
The value of the variable monthly salary has a value in the form of an expression. divide employeesalary by 12 (no. of months) and you will get the value for this variable.
Why do we use Variables
We use variables to store data. When we need to use that data in calculations or other purposes, we can refer to the data by referring to its container(variable name) instead of writing the data values themselves. In other words variables represent data.
For example
On top right section of every page of our company website we need to display the total number of Desktop Computers we have sold to date. One way to do it is to change the value of total sales every morning on every page of the website. The other way is to refer to the variable 'Total sales' on every page and update the value of the variable 'total sales' in the system memory, and every webpage thus automatically displays the current value of the Total sales by extracting the information from the main system memory.
If you are still not fully clear about variables, don't worry. You will better understand their use as use them in examples in the lessons ahead. Above description is sufficient foundation knowledge and you can move on.
Declaring a Variable in Javascript
To Create / Declare variables in Javascript, we use the var command.
SYNTAX
var variable_name;
There are two ways to declare a variable.
1. Just declare a variable (assign it a value later)
var countryname; This will create a variable called 'countryname' without assigning value to it.
2.Declare a Variable and also assign value to it.
var countryname = "Australia";
JavaScript in External file. Link JS to HTML
As noted in the previous lesson, Javascript can also be put into an external file and the Html page that we wish to use the Javascript code on, is linked to that external file.
It works in a similar way as CSS code is put in External Style sheets.
Advantages of placing Javascript code in External File
Security and Privacy- Competitors and Hackers cannot see the code. The external file can be blocked from public view.
Reusability- The same code can be used on multiple pages and
Easy Updating- In case of updating the JS code, it has to be done only in the external file instead of all the individual pages.
How to link the Javascript and Html files?
STEP 1- Create JavaScript external file
Create a new file, write in the Javascript code and SAVE AS it with .JS extension.
javascript external file
The external file will just contain the javascript code and not the html <script> </script> tags.
js code external
STEP 2- Link html to Javascript File
Use the Script tags, however instead writing in the code specify the location of the file that contains the code. Path of the file is defined with 'src'
In the example below the JS file was in the same folder as the html file. If folders are different, appropriate path needs to be defined.
<html>
<head>
<title> JavaScript in external file</title>
<script type="text/javascript" src=sample.js>
</script>
</head>
<body>
</body>
</html>
STEP 3- Load the html file which will call Javascript
Open the html file in a browser.
Result.
javascript html link result
It works in a similar way as CSS code is put in External Style sheets.
Advantages of placing Javascript code in External File
Security and Privacy- Competitors and Hackers cannot see the code. The external file can be blocked from public view.
Reusability- The same code can be used on multiple pages and
Easy Updating- In case of updating the JS code, it has to be done only in the external file instead of all the individual pages.
How to link the Javascript and Html files?
STEP 1- Create JavaScript external file
Create a new file, write in the Javascript code and SAVE AS it with .JS extension.
javascript external file
The external file will just contain the javascript code and not the html <script> </script> tags.
js code external
STEP 2- Link html to Javascript File
Use the Script tags, however instead writing in the code specify the location of the file that contains the code. Path of the file is defined with 'src'
In the example below the JS file was in the same folder as the html file. If folders are different, appropriate path needs to be defined.
<html>
<head>
<title> JavaScript in external file</title>
<script type="text/javascript" src=sample.js>
</script>
</head>
<body>
</body>
</html>
STEP 3- Load the html file which will call Javascript
Open the html file in a browser.
Result.
javascript html link result
Embedding JavaScript code in HTML documents
javaScript code can be included in simple html documents. To enable browser to differentiate between html and Javascript code, JS code is placed within script tags.
OPENING TAG <script type = "text/javascript">
Javascript commands go between these tags.
ENDING TAG </script>
Javascript in HTML Example
In this example we will use a very basic Javascript command called 'document.write' . This command is used to output/display some text, number, result or value of a variable on screen. For example, Browser calculates the price after 10% discount. In order to display that value on the screen, document.write command has to be used. We will however use a very simple output for this example.
<html>
<head>
<title> My first Javascript Page </title>
<script type="text/javascript">
document.write("Welcome to my first page");
</script>
</head>
<body>
</body>
</html>
In the example above, you can see how we can insert javascript within an html document. This simple document.write code will output/display the text on the screen of the browser.
NOTE: Some users prefer to put Javascript coding within the html <head> </head> tags , while some prefer body tags. You can place it in either location or also some code in head while other bit of code in the body.
Result- How to write Javascript in html
Here is how it will appear in the browser
Javascript code in html page
Apart from writing JAVASCRIPT in html documents, it can also be put it a separate file.
OPENING TAG <script type = "text/javascript">
Javascript commands go between these tags.
ENDING TAG </script>
Javascript in HTML Example
In this example we will use a very basic Javascript command called 'document.write' . This command is used to output/display some text, number, result or value of a variable on screen. For example, Browser calculates the price after 10% discount. In order to display that value on the screen, document.write command has to be used. We will however use a very simple output for this example.
<html>
<head>
<title> My first Javascript Page </title>
<script type="text/javascript">
document.write("Welcome to my first page");
</script>
</head>
<body>
</body>
</html>
In the example above, you can see how we can insert javascript within an html document. This simple document.write code will output/display the text on the screen of the browser.
NOTE: Some users prefer to put Javascript coding within the html <head> </head> tags , while some prefer body tags. You can place it in either location or also some code in head while other bit of code in the body.
Result- How to write Javascript in html
Here is how it will appear in the browser
Javascript code in html page
Apart from writing JAVASCRIPT in html documents, it can also be put it a separate file.
Editor Software Required for JavaScript
Although javascript can be written simply in a notepad file, using an editing software helps in many ways like there are line numbers, error checking, different font color for javascript, css and html codes etc.
Adobe DreamWeaver CS5
The Professional Web development standard is the Adobe Dreamweaver, which supports various web scripting and programming languages including javascript, php, ASP and CSS. However Adobe Dreamweaver is pretty expensive and often students and beginners avoid buying it while in the learning phase. It typically costs $400 or above. To learn more about Dreamweaver. Official Dreamweaver site.
Komodo Edit- Open Source and FREE
An excellent alternate software for students and Freelancers is Komodo Edit. We strongly recommend using it instead of working simply on a windows notepad. Komodo Edit although Free and OpenSource is a powerful and efficient tool for coding in JavaScript.
STEP 1- Click on the link to go to Official Komodo site and download the software. Download Komodo Edit
The file size is about 43MB and will take 6-10 mins to download on a 1Mbps speed connection.
STEP 2- Go to the folder where you downloaded the file and click to run the setup and Install Komodo Edit on your PC.
komodo edit setup wizard
STEP 3- From file menu click New to start a new document
javascript editor new file
Adobe DreamWeaver CS5
The Professional Web development standard is the Adobe Dreamweaver, which supports various web scripting and programming languages including javascript, php, ASP and CSS. However Adobe Dreamweaver is pretty expensive and often students and beginners avoid buying it while in the learning phase. It typically costs $400 or above. To learn more about Dreamweaver. Official Dreamweaver site.
Komodo Edit- Open Source and FREE
An excellent alternate software for students and Freelancers is Komodo Edit. We strongly recommend using it instead of working simply on a windows notepad. Komodo Edit although Free and OpenSource is a powerful and efficient tool for coding in JavaScript.
STEP 1- Click on the link to go to Official Komodo site and download the software. Download Komodo Edit
The file size is about 43MB and will take 6-10 mins to download on a 1Mbps speed connection.
STEP 2- Go to the folder where you downloaded the file and click to run the setup and Install Komodo Edit on your PC.
komodo edit setup wizard
STEP 3- From file menu click New to start a new document
javascript editor new file
Inscription à :
Articles (Atom)