Example let x, y, z; // Statement 1 Show
Try it Yourself » JavaScript ProgramsA computer program is a list of "instructions" to be "executed" by a computer. In a programming language, these programming instructions are called statements. A JavaScript program is a list of programming statements. In HTML, JavaScript programs are executed by the web browser. JavaScript StatementsJavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments. This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo": Exampledocument.getElementById("demo").innerHTML = "Hello Dolly."; Try it Yourself » Most JavaScript programs contain many JavaScript statements. The statements are executed, one by one, in the same order as they are written. JavaScript programs (and JavaScript statements) are often called JavaScript code. Semicolons ;Semicolons separate JavaScript statements. Add a semicolon at the end of each executable statement: Examples let a, b, c; // Declare 3 variables Try it Yourself » When separated by semicolons, multiple statements on one line are allowed: On the web, you might see examples without semicolons. JavaScript White SpaceJavaScript ignores multiple spaces. You can add white space to your script to make it more readable. The following lines are equivalent: let person = "Hege"; A good practice is to put spaces around operators ( = + - * / ): JavaScript Line Length and Line BreaksFor best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript statement does not fit on one line, the best place to break it is after an operator: JavaScript Code BlocksJavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The purpose of code blocks is to define statements to be executed together. One place you will find statements grouped together in blocks, is in JavaScript functions: Example function myFunction() { Try it Yourself » In this tutorial we use 2 spaces of indentation for code blocks. JavaScript KeywordsJavaScript statements often start with a keyword to identify the JavaScript action to be performed. Our Reserved Words Reference lists all JavaScript keywords. Here is a list of some of the keywords you will learn about in this tutorial:
JavaScript keywords are reserved words. Reserved words cannot be used as names for variables. Moving through the eleven statements supported by JavaScriptStatements are used in JavaScript to control its program flow. Unlike properties, methods, and events, which are fundamentally tied to the object that owns them, statements are designed to work independently of any JavaScript object. That means you can use a statement whether you're working with the document object, the window object, the history object, or some other object. As a language, JavaScript supports relatively few statements -- just enough to get by. It does, however, offer the bare minimum of statements that are needed to construct a fully-functional application. JavaScript currently supports the following eleven statements. Note that some of these -- such as comment, var, and new -- aren't bona fide statements, but they are often treated as such. They are included in this discussion for the sake of completeness.
A few of the statements offered in Java are notably lacking in JavaScript. This includes the switch statement, as well as all forms of error-trapping statements (such as catch and throw). JavaScript keeps these statements as reserved words, and perhaps in some future version, they will be implemented. Comment (//)The // characters tell JavaScript that you want to include explanatory comments in your program. The comment ends at the first hard return that is encountered. JavaScript places no limit on the length of the comment, as long as there is no hard return before the comment ends. JavaScript assumes text after the hard return is valid code.
You can place the // comment characters anywhere on a line. JavaScript will treat all the text on that line after the // as a comment. MyVariable="This is a test" // assigns text variable MyVariable Comments are ignored when the script is played, so they do not greatly affect the speed of execution. However, lots of comments increase the file size of scripts and take longer to download to the user's computer over a dial-up Internet connection. For best results, limit comments in JavaScript programs to brief, single lines. When writing long comments it's better to use the alternate commenting characters /* and */. Text between these characters is treated as a comment. Alternatively, you can start each line with the // comment characters. // This section checks to see if the Enter key is pressed, // then continues on or /* This section checks to see if the Enter key is pressed, then continues on */ Back to index BreakThe break statement tells JavaScript to exit a "controlled structure" and resume execution at a point after the structure. The break statement is used with structures built using the following commands:
The break statement is most commonly used to prematurely end a for loop. For example: for (Count=1; Count<=10; Count++) { if (Count == 6) break; document.write ("<P>Loop: " + Count + "</P>"); } This example shows a for loop that counts from 1 to 10 and prints the number at each iteration of the loop. An if statement inside the for loop is used to test if the value in the Count variable is equal to 6. If Count equals 6, the break statement is executed, and the script exits the for loop. As used in this simple example, the script will count from 1 to 6, then stop. It exits the for loop before it can count up to 10. Back to index ContinueThe continue statement tells JavaScript to skip any instructions that may follow in a for, for...in, or while loop, and proceed with the next iteration. The most common use of the continue statement is to conditionally skip instructions in the loop but not exit the loop (as the break statement does). For example: for (Count=1; Count<=10; Count++) { if (Count == 6) continue; document.write ("<P>Loop: " + Count + "</P>"); } The example above shows a for loop that counts from 1 to 10 and prints the number at each iteration of the loop. An if statement inside the for loop is used to test if the value in the Count variable is equal to 6. If Count equals 6, the continue statement is executed, and the script skips the document.write instruction on the next line. But the loop doesn't end. Instead, it continues and prints lines for the remaining numbers. As used in this simple example, the script will count from 1 to 5, skip 6, then print 7 through 10. Back to index ForThe for statement repeats a block of instructions one or more times. The number of iterations is controlled by values supplied as arguments. The syntax of the for statement is: for (InitVal; Test; Increment)
Note that unlike all of the other constructs in JavaScript, the for statement uses semicolons, rather than commas, to separate its arguments. This is in keeping with the syntax used in C, C++, and Java. Here's an example of a for loop that counts from 1 to 10, stepping one digit at a time. At each iteration, the script inserts some text and begins a new line. The JavaScript you wish to repeat is enclosed in { and } characters following the for statement; this forms the for statement block. You can provide one line or many within the { and } characters. for (Count=1; Count<=10; Count++) { document.write ("Iteration: "+Count+"<BR>"); } Count is the variable name used to store the for loop counter. The for loop starts out with 1 and proceeds to 10. The test expression is Count<=10, which reads: Count is less than or equal to 10 As long as this expression is true, the for loop continues. Do note that the Increment argument is also an expression and in the example uses the Count variable to increment the for loop by 1 for each iteration. There's no law that says you must increment the for loop by ones. Here's just one of the many alternatives. This example counts by tens, from 10 to 100. for (Count=1; Count<101; Count+=10) { document.write ("Iteration: "+Count+"<BR>"); } Back to index For...inThe for...in statement is a special version of the for statement described in the previous section. For...in is used to display the property names and/or property contents of objects. It is mostly handy as a debugging and testing tool: If a portion of your JavaScript code isn't working properly, and you suspect it may be the fault of a JavaScript object you are trying to use, you can examine all of the properties for that object with the for...in statement. Unlike the for statement, for...in doesn't use incrementing tests or other expressions. You provide the name of a holding variable (the name of the variable is up to you) and the object you want to use. The basic syntax for the for...in statement is: for (var in object) { statements }
As an example, suppose you want to determine the properties of the navigator object (this object contains details about the Netscape Navigator or other browser you are using). The following code displays each property name in an alert box. When running the script, click OK to proceed to the next property name. The loop automatically ends when there are no more properties in the object. for (temp in navigator) { alert (temp); } A variation of this example is shown below. It not only displays the property names but also displays the contents of each property (some properties are empty and therefore no contents are shown for them). The contents of the properties are displayed by using the syntax object[var], or in this case navigator[temp]. for (temp in navigator) { alert (temp + ": " + navigator[temp]); } The for..in loop can be used for all object types. You can use it to iterate through all the properties for a form in a document, for example, or through the properties of a user-defined object. For instance, to cycle through all the properties of a form, you'd use the for...in loop as in the following example (assume the form name is "myform"): <SCRIPT> function test() { for (temp in document.myform) { alert (temp); } } </SCRIPT> <FORM NAME="myform"> <INPUT TYPE="text" NAME="box1"><BR> <INPUT TYPE="text" NAME="box2"><BR> <INPUT TYPE="text" NAME="box3"><P> <INPUT TYPE="button" VALUE="Click" onClick="test()"> </FORM> Back to index FunctionThe function statement lets you create your own user-defined functions (as well as user-defined objects and methods for those objects). Functions are self-contained routines that can be "called" elsewhere within your JavaScript code. For example, if you have a function named
, which displays your name in headline text, you can activate it by merely referring to the name
someplace within your JavaScript code. Here's a short test that shows how this might work: <HTML> <HEAD> <TITLE>Function Test</TITLE> <SCRIPT LANGUAGE="JavaScript"> function writeMyName () { MyName="John Doe" alert (MyName) } </SCRIPT> </HEAD> <BODY> <FORM> <INPUT TYPE="button" NAME="button1" VALUE="Click Me!" onClick="writeMyName()"><P> </FORM> </BODY> </HTML> The Back to index If...elseThe if, along with its optional else, statement is used to build an "if conditional" expression. It is called a conditional expression because it tests for a specific condition.
The syntax for if is: if (expression) The result of the if expression is always either true or false. The following syntax is acceptable when there's only one instruction following the if and else statements: if (ExampleVar == 10) Start(); else Stop(); Should more than one instruction follow the if or else statement, the { and } characters must be used to define an if statement block. With the { and } characters in place, JavaScript knows to execute all of the instructions within the block. if (ExampleVar == 10) { Count = 1; Start(); } else { Count = 0; Stop(); } Expressions in if statements are not limited to the == equality operator. You can test if values are not equal to one another, greater than, less than, and more. For more information on the operators you can use, see the references list at the end of this column. It points to valuable JavaScript documentation, including documentation provided by Netscape. Back to index NewThe new statement creates a new copy of an object. It is used in either of two ways:
The syntax is the same with either use: varname = new objectName(params);
The following example shows how to use the new statement to create a copy -- otherwise known as an "instance" -- of the Date object: now = new Date(); The now object, which can be considered a JavaScript variable, has all the properties and methods of the JavaScript Date object. For example, you use the now object to determine the current hour of the day: now = new Date(); HourNow = now.getHours(); What is the use of this in JavaScript?In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
What is JavaScript statement with example?A computer program is a list of "instructions" to be "executed" by a computer. In a programming language, these programming instructions are called statements. A JavaScript program is a list of programming statements. In HTML, JavaScript programs are executed by the web browser.
What are the three types of statements in JavaScript?JavaScript supports the for , do while , and while loop statements, as well as label (label is not itself a looping statement, but is frequently used with these statements). In addition, you can use the break and continue statements within loop statements.
|