Вы находитесь на странице: 1из 15

JavaScript

JavaScript is the programming language of HTML and the Web.

JavaScript and Java are completely different languages, both in concept and design.

JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name of the standard. ECMAScript is the official name of the
language.

Why Study JavaScript?


JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

Web pages are not the only place where JavaScript is used. Many desktop and server
programs use JavaScript. Node.js is the best known. Some databases, like MongoDB and
CouchDB, also use JavaScript as their programming language.

JavaScript Introduction
JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

This example uses the method to "find" an HTML element (with id="demo") and changes the
element content (innerHTML) to "Hello JavaScript":

JavaScript accepts both double and single quotes:


document.getElementById("demo").innerHTML = "Hello JavaScript";
document.getElementById('demo').innerHTML = 'Hello JavaScript';’

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:


JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

JavaScript Can Show HTML Elements

Showing hidden HTML elements can also be done by changing the display style:

The <script> Tag

In HTML, JavaScript code must be inserted between <script> and </script> tags.

Old JavaScript examples may use a type attribute: <script type="text/javascript">.


The type attribute is not required. JavaScript is the default scripting language in HTML.

JavaScript in <head> or <body>


You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:

External JavaScript
Scripts can also be placed in external files:
External file: myScript.js

External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is located.

External scripts cannot contain <script> tags.


External JavaScript Advantages

Placing scripts in external files has some advantages:

 It separates HTML and code


 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads

To add several script files to one page - use several script tags:

External References

External scripts can be referenced with a full URL or with a path relative to the current web
page.

This example uses a full URL to link to a script:

<script src="https://www.w3schools.com/js/myScript1.js"></script>

<script src="/js/myScript1.js"></script>

This example links to a script located in the same folder as the current page:
<script src="myScript1.js"></script>

JavaScript Display Possibilities

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML

To access an HTML element, JavaScript can use


the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML
content:

Changing the innerHTML property of an HTML element is a common way to display data in
HTML.

Using document.write()

For testing purposes, it is convenient to use document.write():

Using document.write() after an HTML document is loaded, will delete all existing HTML:
JavaScript Statements
JavaScript Programs
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.

JavaScript Statements
JavaScript 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":

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:

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;

JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.

The following lines are equivalent:

var person = "Hege";


var person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

var x = y + z;

JavaScript Line Length and Line Breaks


For 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:

document.getElementById("demo").innerHTML ="Hello Dolly!";


JavaScript Code Blocks
JavaScript 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:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
</script>
</body>
</html>

we use 2 spaces of indentation for code blocks.


You will learn more about functions LATER
JavaScript Keywords

Keyword Description

break Terminates a switch or a loop

continue Jumps out of a loop and starts at the top

debugger Stops the execution of JavaScript, and calls (if available) the debugging function

do ... while Executes a block of statements, and repeats the block, while a condition is true

for Marks a block of statements to be executed, as long as a condition is true

function Declares a function

if ... else Marks a block of statements to be executed, depending on a condition

return Exits a function

switch Marks a block of statements to be executed, depending on different cases

try ... catch Implements error handling to a block of statements

var Declares a variable

JavaScript keywords are reserved words. Reserved words cannot be used as names for
variables.

JavaScript Syntax

JavaScript syntax is the set of rules, how JavaScript programs are constructed:

var x, y, z; // How to declare variables


x = 5; y = 6; // How to assign values
z = x + y; // How to compute values

JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:

10.50
1001

Strings are text, written within double or single quotes:

"John Doe"
'John Doe'

JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to declare variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

var x;
x = 6;

JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10

JavaScript uses an assignment operator ( = ) to assign values to variables:

var x, y;
x = 5;
y = 6;
JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a
value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10

Expressions can also contain variable values:


x * 10

The values can be of various types, such as numbers and strings.


For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"

JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;

JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.

Numbers are not allowed as the first character.


This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive


All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables:
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
JavaScript does not interpret VAR or Var as the keyword var.

Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
firstName, lastName, masterCard, interCity.

JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.

Single Line Comments


Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
This example uses a single-line comment before each code line:

// Change heading:
document.getElementById("myH").innerHTML = "My First Page";

// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";

Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the code:
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

It is most common to use single line comments.


Block comments are often used for formal documentation.

JavaScript Variables
JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:
var x = 5;
var y = 6;
var z = x + y;
From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 z stores the value 11

Much Like Algebra

In this example, price1, price2, and total, are variables:

var price1 = 5;
var price2 = 6;
var total = price1 + price2;

In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total = price1 + price2).
From the example above, you can calculate the total to be 11.

JavaScript variables are containers for storing data values.

JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

JavaScript identifiers are case-sensitive.

The Assignment Operator


In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
This is different from algebra. The following does not make sense in algebra:
x = x + 5

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.


(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
The "equal to" operator is written like == in JavaScript.

JavaScript Data Types


JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
var pi = 3.14;

var person = "John Doe";


var answer = 'Yes I am!';

Declaring (Creating) JavaScript Variables


Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var keyword:
var carName;

After the declaration, the variable has no value (technically it has the value of undefined).
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
var carName = "Volvo";
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
<p id="demo"></p>

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

It's a good programming practice to declare all variables at the beginning of a script.

One Statement, Many Variables


You can declare many variables in one statement.
Start the statement with var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:
var person = "John Doe",
carName = "Volvo",
price = 200;

Value = undefined
In computer programs, variables are often declared without a value. The value can be something that has to be
calculated, or something that will be provided later, like user input.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this statement:

var carName

Re-Declaring JavaScript Variables


If you re-declare a JavaScript variable, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
var carName = "Volvo";
var carName;
JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators
like = and +:

var x = 5 + 2 + 3;

You can also add strings, but strings will be concatenated:

var x = "John" + " " + "Doe";

Also try this:

var x = "5" + 2 + 3;

If you put a number in quotes, the rest of the numbers will be treated as strings, and
concatenated.

Now try this:

var x = 2 + 3 + "5";
JavaScript Arithmetic Operator
Arithmetic operators are used to perform arithmetic on numbers:

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.

Operator Example Same As

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

**= x **= y x = x ** y

JavaScript String Operators

The + operator can also be used to add (concatenate) strings.

var txt1 = "John";


var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
The += assignment operator can also be used to add (concatenate) strings:

var txt1 = "What a very ";


txt1 += "nice day";

The result of txt1 will be:


What a very nice day

Adding Strings and Numbers


Adding two numbers, will return the sum, but adding a number and a string will return a string:
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5

If you add a number and a string, the result will be a string!

JavaScript Comparison Operators

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator
JavaScript Type Operators

Operator Description

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of an object type

JavaScript Bitwise Operators


Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript
number.

Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0001 0100 4

<< Zero fill left shift 5 << 1 0101 << 1 1010 10

>> Signed right shift 5 >> 1 0101 >> 1 0010 2

>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2

Вам также может понравиться